From 6af079673ee2adb4bc8416355f3c1ef413f20892 Mon Sep 17 00:00:00 2001 From: Alex Pooley Date: Tue, 21 Feb 2017 18:55:19 -0500 Subject: [PATCH 001/282] Kernel#quietly was deprecated in Rails 4.2 --- lib/tasks/apartment.rake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 3c70df94..844c1550 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -7,7 +7,7 @@ apartment_namespace = namespace :apartment do tenants.each do |tenant| begin puts("Creating #{tenant} tenant") - quietly { Apartment::Tenant.create(tenant) } + Apartment::Tenant.create(tenant) rescue Apartment::TenantExists => e puts e.message end From ace6ffad169e63f5876e1503b986ee49ddac1fcb Mon Sep 17 00:00:00 2001 From: Rui Date: Fri, 3 Jan 2020 15:38:14 +0800 Subject: [PATCH 002/282] [Resolves] Basic support for Rails 6 - N/a # Describe the changes made. What does this PR changes that might be critical. If any critical decisions have been made, make sure you explain the rationale for these decisions. - Updated JRuby minor version to fix some tests - Updated travis.yml to latest syntax - Fixed Rakefile to run in rails 6 - Updated gemspec to have URLs matching # How does the implementation addresses the problem After merging this all test suite for apartment gem is passing using rails 6. --- .travis.yml | 19 ++++++++++--------- Gemfile | 2 +- README.md | 4 +++- Rakefile | 10 +++++++++- apartment.gemspec | 38 ++++++++++++++++++++------------------ lib/apartment/version.rb | 2 +- 6 files changed, 44 insertions(+), 31 deletions(-) diff --git a/.travis.yml b/.travis.yml index 78067b58..cefc8560 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,10 @@ -sudo: required +os: linux + language: ruby services: - docker rvm: - - jruby-9.1.15.0 + - jruby-9.1.17.0 - 2.1.9 - 2.2.9 - 2.3.6 @@ -29,11 +30,11 @@ before_install: env: RUBY_GC_MALLOC_LIMIT: 90000000 RUBY_GC_HEAP_FREE_SLOTS: 200000 -matrix: +jobs: allow_failures: - rvm: ruby-head - gemfile: gemfiles/rails_master.gemfile - - rvm: jruby-9.1.15.0 + - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_5_0.gemfile exclude: - rvm: 2.1.9 @@ -46,19 +47,19 @@ matrix: gemfile: gemfiles/rails_6_0.gemfile - rvm: 2.1.9 gemfile: gemfiles/rails_master.gemfile - - rvm: 2.2.9 + - rvm: 2.2.9 gemfile: gemfiles/rails_6_0.gemfile - rvm: 2.3.6 gemfile: gemfiles/rails_6_0.gemfile - rvm: 2.4.3 gemfile: gemfiles/rails_6_0.gemfile - - rvm: jruby-9.1.15.0 + - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_5_1.gemfile - - rvm: jruby-9.1.15.0 + - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_5_2.gemfile - - rvm: jruby-9.1.15.0 + - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_6_0.gemfile - - rvm: jruby-9.1.15.0 + - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_master.gemfile fast_finish: true cache: bundler diff --git a/Gemfile b/Gemfile index 6c13b34a..bdbf6fe1 100644 --- a/Gemfile +++ b/Gemfile @@ -2,7 +2,7 @@ source 'http://rubygems.org' gemspec -gem 'rails', '>= 3.1.2' +gem 'rails', '>= 3.1.2' group :local do gem 'pry' diff --git a/README.md b/README.md index 6713baaa..65f85886 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,8 @@ [![Code Climate](https://codeclimate.com/github/influitive/apartment/badges/gpa.svg)](https://codeclimate.com/github/influitive/apartment) [![Build Status](https://travis-ci.org/influitive/apartment.svg?branch=development)](https://travis-ci.org/influitive/apartment) +# NOT ACTIVELY MAINTAINED YET. SOLELY FOR TESTING PURPOSES ATM + *Multitenancy for Rails and ActiveRecord* Apartment provides tools to help you deal with multiple tenants in your Rails @@ -484,7 +486,7 @@ Note that you can disable the default migrating of all tenants with `db:migrate` Apartment supports parallelizing migrations into multiple threads when you have a large number of tenants. By default, parallel migrations is -turned off. You can enable this by setting `parallel_migration_threads` to +turned off. You can enable this by setting `parallel_migration_threads` to the number of threads you want to use in your initializer. Keep in mind that because migrations are going to access the database, diff --git a/Rakefile b/Rakefile index df67edc6..8eaec6d0 100644 --- a/Rakefile +++ b/Rakefile @@ -119,10 +119,18 @@ def activerecord_below_5_2? ActiveRecord.version.release < Gem::Version.new('5.2.0') end +def activerecord_below_6_0? + ActiveRecord.version.release < Gem::Version.new('6.0.0') +end + def migrate if activerecord_below_5_2? ActiveRecord::Migrator.migrate('spec/dummy/db/migrate') - else + elsif activerecord_below_6_0? ActiveRecord::MigrationContext.new('spec/dummy/db/migrate').migrate + else + # TODO: Figure out if there is any other possibility that can/should be + # passed here as the second argument for the migration context + ActiveRecord::MigrationContext.new('spec/dummy/db/migrate', ActiveRecord::SchemaMigration).migrate end end diff --git a/apartment.gemspec b/apartment.gemspec index eb59070f..0b51d8a7 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -1,42 +1,44 @@ -# -*- encoding: utf-8 -*- -$: << File.expand_path("../lib", __FILE__) -require "apartment/version" +# frozen_string_literal: true + +$LOAD_PATH << File.expand_path('lib', __dir__) +require 'apartment/version' Gem::Specification.new do |s| - s.name = %q{apartment} + s.name = 'ros-apartment' s.version = Apartment::VERSION - s.authors = ["Ryan Brunner", "Brad Robertson"] - s.summary = %q{A Ruby gem for managing database multitenancy} - s.description = %q{Apartment allows Rack applications to deal with database multitenancy through ActiveRecord} - s.email = ["ryan@influitive.com", "brad@influitive.com"] + s.authors = ['Ryan Brunner', 'Brad Robertson', 'Rui Baltazar'] + s.summary = 'A Ruby gem for managing database multitenancy. Apartment Gem drop in replacement' + s.description = 'Apartment allows Rack applications to deal with database multitenancy through ActiveRecord' + s.email = ['ryan@influitive.com', 'brad@influitive.com', 'rui.p.baltazar@gmail.com'] s.files = `git ls-files`.split($/) - s.executables = s.files.grep(%r{^bin/}).map{ |f| File.basename(f) } + s.executables = s.files.grep(%r{^bin/}).map { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) - s.require_paths = ["lib"] + s.require_paths = ['lib'] - s.homepage = %q{https://github.com/influitive/apartment} - s.licenses = ["MIT"] + s.homepage = 'https://github.com/rails-on-services/apartment' + s.licenses = ['MIT'] # must be >= 3.1.2 due to bug in prepared_statements s.add_dependency 'activerecord', '>= 3.1.2', '< 6.1' - s.add_dependency 'rack', '>= 1.3.6' - s.add_dependency 'public_suffix', '>= 2' s.add_dependency 'parallel', '>= 0.7.1' + s.add_dependency 'public_suffix', '>= 2' + s.add_dependency 'rack', '>= 1.3.6' s.add_development_dependency 'appraisal' + s.add_development_dependency 'bundler', '~> 2.0' + s.add_development_dependency 'capybara', '~> 2.0' + s.add_development_dependency 'perx-rubocop', '~> 0.0' s.add_development_dependency 'rake', '~> 0.9' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'rspec-rails', '~> 3.4' - s.add_development_dependency 'capybara', '~> 2.0' - s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' if defined?(JRUBY_VERSION) s.add_development_dependency 'activerecord-jdbc-adapter' - s.add_development_dependency 'activerecord-jdbcpostgresql-adapter' s.add_development_dependency 'activerecord-jdbcmysql-adapter' - s.add_development_dependency 'jdbc-postgres' + s.add_development_dependency 'activerecord-jdbcpostgresql-adapter' s.add_development_dependency 'jdbc-mysql' + s.add_development_dependency 'jdbc-postgres' s.add_development_dependency 'jruby-openssl' else s.add_development_dependency 'mysql2' diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 40b2f751..5e87051d 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,3 +1,3 @@ module Apartment - VERSION = "2.2.1" + VERSION = "2.3.0.alpha2" end From 675e6a2b1c9ed1c0eeb1bce4f23950f1b40572f2 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Jan 2020 16:02:16 +0800 Subject: [PATCH 003/282] [Hotfix] Updated readme --- README.md | 40 +++++++++++++++++++--------------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 65f85886..5afce9dd 100644 --- a/README.md +++ b/README.md @@ -4,34 +4,27 @@ [![Code Climate](https://codeclimate.com/github/influitive/apartment/badges/gpa.svg)](https://codeclimate.com/github/influitive/apartment) [![Build Status](https://travis-ci.org/influitive/apartment.svg?branch=development)](https://travis-ci.org/influitive/apartment) -# NOT ACTIVELY MAINTAINED YET. SOLELY FOR TESTING PURPOSES ATM - *Multitenancy for Rails and ActiveRecord* Apartment provides tools to help you deal with multiple tenants in your Rails application. If you need to have certain data sequestered based on account or company, but still allow some data to exist in a common tenant, Apartment can help. -## HELP! - -In order to help drive the direction of development and clean up the codebase, we'd like to take a poll -on how people are currently using Apartment. If you can take 5 seconds (1 question) to answer -this poll, we'd greatly appreciated it. - -[View Poll](http://www.poll-maker.com/poll391552x4Bfb41a9-15) +## Apartment drop in replacement gem -## Excessive Memory Issues on ActiveRecord 4.x +After having reached out via github issues and email directly, no replies ever +came. Since we wanted to upgrade our application to Rails 6 we decided to fork +and start some development to support Rails 6. Because we don't have access +to the apartment gem itself, the solution was to release it under a different +name but providing the exact same API as it was before. -> If you're noticing ever growing memory issues (ie growing with each tenant you add) -> when using Apartment, that's because there's [an issue](https://github.com/rails/rails/issues/19578) -> with how ActiveRecord maps Postgresql data types into AR data types. -> This has been patched and will be released for AR 4.2.2. It's apparently hard -> to backport to 4.1 unfortunately. -> If you're noticing high memory usage from ActiveRecord with Apartment please upgrade. +## Help wanted -```ruby -gem 'rails', '4.2.1', github: 'influitive/rails', tag: 'v4.2.1.memfix' -``` +We were never involved with the development of Apartment gem in the first place +and this project started out of our own needs. We will be more than happy +to collaborate to maintain the gem alive and supporting the latest versions +of ruby and rails, but your help is appreciated. Either by reporting bugs you +may find or proposing improvements to the gem itself. Feel free to reach out. ## Installation @@ -40,7 +33,7 @@ gem 'rails', '4.2.1', github: 'influitive/rails', tag: 'v4.2.1.memfix' Add the following to your Gemfile: ```ruby -gem 'apartment' +gem 'ros-apartment' ``` Then generate your `Apartment` config file using @@ -533,7 +526,12 @@ end ## Background workers -See [apartment-sidekiq](https://github.com/influitive/apartment-sidekiq) or [apartment-activejob](https://github.com/influitive/apartment-activejob). +Both these gems have been forked as a side consequence of having a new gem name. +You can use them exactly as you were using before. They are, just like this one +a drop-in replacement. + +See [apartment-sidekiq](https://github.com/rails-on-services/apartment-sidekiq) +or [apartment-activejob](https://github.com/rails-on-services/apartment-activejob). ## Callbacks From b5cfd1896bc62034b873b0a8d38357535e30b18a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Jan 2020 16:21:14 +0800 Subject: [PATCH 004/282] [Hotfix] preparing version 2.3.0 --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 5e87051d..25f180b1 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,3 +1,3 @@ module Apartment - VERSION = "2.3.0.alpha2" + VERSION = "2.3.0" end From 700c54819f7c9690de720c1accd4db646f22e0b5 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Jan 2020 16:24:26 +0800 Subject: [PATCH 005/282] [Hotfix] Updated travis config and history.md --- HISTORY.md | 7 +++++++ apartment.gemspec | 3 +-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index c6e1398f..5bf2609c 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,10 @@ +# 2.3.0 + * January 3, 2020 + +## Added + - Basic support for rails 6 + - Released different gem name, with same API as apartment + # 2.2.1 * June 19, 2019 diff --git a/apartment.gemspec b/apartment.gemspec index 0b51d8a7..e00a1304 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -26,9 +26,8 @@ Gem::Specification.new do |s| s.add_dependency 'rack', '>= 1.3.6' s.add_development_dependency 'appraisal' - s.add_development_dependency 'bundler', '~> 2.0' + s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' s.add_development_dependency 'capybara', '~> 2.0' - s.add_development_dependency 'perx-rubocop', '~> 0.0' s.add_development_dependency 'rake', '~> 0.9' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'rspec-rails', '~> 3.4' From 8aa5b1330837d5862e39cbf816fafd5404250d91 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 4 Feb 2020 11:03:42 +0800 Subject: [PATCH 006/282] [Hotfix] updated README to include require --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5afce9dd..f6c6d03b 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ may find or proposing improvements to the gem itself. Feel free to reach out. Add the following to your Gemfile: ```ruby -gem 'ros-apartment' +gem 'ros-apartment', require: 'apartment' ``` Then generate your `Apartment` config file using From 428a035fa84dd76bb8c6663df6d2401b624b7c7a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 15:31:35 +0800 Subject: [PATCH 007/282] [Hotfix] Added story_branch local config --- .story_branch.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .story_branch.yml diff --git a/.story_branch.yml b/.story_branch.yml new file mode 100644 index 00000000..d9ad6922 --- /dev/null +++ b/.story_branch.yml @@ -0,0 +1,4 @@ +--- +tracker: github +project_id: +- rails-on-services/apartment From 4a4c62c855da330a3adba7ee80c35acaa5656bc9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 15:37:24 +0800 Subject: [PATCH 008/282] [Hotfix] added rubocop to the project --- .rubocop.yml | 5 + .rubocop_todo.yml | 755 ++++++++++++++++++ Gemfile | 4 +- apartment.gemspec | 1 + .../apartment_rake_integration_spec.rb | 4 +- 5 files changed, 766 insertions(+), 3 deletions(-) create mode 100644 .rubocop.yml create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..902dcf64 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,5 @@ +inherit_from: .rubocop_todo.yml + +inherit_gem: + perx-rubocop: + - default.yml diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 00000000..383eaf02 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,755 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2020-02-16 15:36:55 +0800 using RuboCop version 0.77.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 13 +# Cop supports --auto-correct. +# Configuration parameters: TreatCommentsAsGroupSeparators, Include. +# Include: **/*.gemfile, **/Gemfile, **/gems.rb +Bundler/OrderedGems: + Exclude: + - 'gemfiles/rails_4_2.gemfile' + - 'gemfiles/rails_5_0.gemfile' + - 'gemfiles/rails_5_1.gemfile' + - 'gemfiles/rails_5_2.gemfile' + - 'gemfiles/rails_6_0.gemfile' + - 'gemfiles/rails_master.gemfile' + +# Offense count: 13 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: outdent, indent +Layout/AccessModifierIndentation: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/adapters/sqlite3_adapter.rb' + - 'lib/apartment/elevators/subdomain.rb' + +# Offense count: 4 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: with_first_argument, with_fixed_indentation +Layout/ArgumentAlignment: + Exclude: + - 'lib/apartment/adapters/sqlite3_adapter.rb' + - 'lib/apartment/elevators/host_hash.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. +# SupportedStylesAlignWith: start_of_line, def +Layout/DefEndAlignment: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Layout/ElseAlignment: + Exclude: + - 'lib/apartment/elevators/subdomain.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Layout/EmptyLineAfterGuardClause: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/elevators/host.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +Layout/EmptyLineAfterMagicComment: + Exclude: + - 'spec/schemas/v1.rb' + - 'spec/schemas/v2.rb' + - 'spec/schemas/v3.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Layout/EmptyLines: + Exclude: + - 'Appraisals' + +# Offense count: 54 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, no_empty_lines +Layout/EmptyLinesAroundBlockBody: + Enabled: false + +# Offense count: 18 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only +Layout/EmptyLinesAroundClassBody: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' + - 'lib/apartment/adapters/jdbc_mysql_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/elevators/domain.rb' + - 'lib/apartment/elevators/first_subdomain.rb' + - 'lib/apartment/elevators/generic.rb' + - 'lib/apartment/railtie.rb' + - 'lib/apartment/reloader.rb' + - 'lib/apartment/tasks/enhancements.rb' + - 'lib/generators/apartment/install/install_generator.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +Layout/EmptyLinesAroundExceptionHandlingKeywords: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Layout/EmptyLinesAroundMethodBody: + Exclude: + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/tasks/enhancements.rb' + +# Offense count: 15 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines +Layout/EmptyLinesAroundModuleBody: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/jdbc_mysql_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + - 'lib/apartment/adapters/postgis_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/deprecation.rb' + - 'lib/apartment/migrator.rb' + - 'lib/apartment/tenant.rb' + - 'spec/support/apartment_helpers.rb' + - 'spec/support/config.rb' + - 'spec/support/requirements.rb' + - 'spec/support/setup.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'lib/apartment/elevators/subdomain.rb' + +# Offense count: 15 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. +Layout/ExtraSpacing: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/tasks/apartment.rake' + - 'spec/dummy/config.ru' + - 'spec/dummy/config/environments/test.rb' + - 'spec/dummy/script/rails' + - 'spec/dummy_engine/test/dummy/config.ru' + - 'spec/examples/generic_adapter_examples.rb' + - 'spec/examples/schema_adapter_examples.rb' + - 'spec/integration/apartment_rake_integration_spec.rb' + - 'spec/tasks/apartment_rake_spec.rb' + - 'spec/unit/reloader_spec.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. +# SupportedHashRocketStyles: key, separator, table +# SupportedColonStyles: key, separator, table +# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit +Layout/HashAlignment: + Exclude: + - 'spec/examples/generic_adapter_custom_configuration_example.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: normal, indented_internal_methods +Layout/IndentationConsistency: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: Width, IgnoredPatterns. +Layout/IndentationWidth: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/elevators/subdomain.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AllowDoxygenCommentStyle. +Layout/LeadingCommentSpace: + Exclude: + - 'spec/dummy_engine/config/initializers/apartment.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, IndentationWidth. +# SupportedStyles: aligned, indented, indented_relative_to_receiver +Layout/MultilineMethodCallIndentation: + Exclude: + - 'spec/examples/generic_adapter_examples.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: space, no_space +Layout/SpaceAroundEqualsInParameterDefault: + Exclude: + - 'lib/apartment/console.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment. +Layout/SpaceAroundOperators: + Exclude: + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'spec/dummy/config/environments/test.rb' + +# Offense count: 82 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: space, no_space +# SupportedStylesForEmptyBraces: space, no_space +Layout/SpaceBeforeBlockBraces: + EnforcedStyleForEmptyBraces: no_space + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AllowForAlignment. +Layout/SpaceBeforeFirstArg: + Exclude: + - 'lib/tasks/apartment.rake' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: require_no_space, require_space +Layout/SpaceInLambdaLiteral: + Exclude: + - 'lib/apartment/migrator.rb' + +# Offense count: 14 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. +# SupportedStyles: space, no_space +# SupportedStylesForEmptyBraces: space, no_space +Layout/SpaceInsideBlockBraces: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'spec/dummy/db/seeds/import.rb' + - 'spec/examples/generic_adapter_custom_configuration_example.rb' + - 'spec/support/contexts.rb' + - 'spec/unit/elevators/generic_spec.rb' + +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: space, no_space +Layout/SpaceInsideStringInterpolation: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 12 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: final_newline, final_blank_line +Layout/TrailingEmptyLines: + Exclude: + - 'lib/apartment/elevators/first_subdomain.rb' + - 'lib/apartment/elevators/host.rb' + - 'spec/dummy/app/models/company.rb' + - 'spec/dummy/app/models/user.rb' + - 'spec/dummy/config/boot.rb' + - 'spec/dummy/config/environments/development.rb' + - 'spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb' + - 'spec/support/capybara_sessions.rb' + - 'spec/support/config.rb' + - 'spec/support/contexts.rb' + - 'spec/unit/elevators/first_subdomain_spec.rb' + - 'spec/unit/reloader_spec.rb' + +# Offense count: 6 +# Cop supports --auto-correct. +# Configuration parameters: AllowInHeredoc. +Layout/TrailingWhitespace: + Exclude: + - 'lib/apartment/elevators/domain.rb' + - 'spec/dummy/app/controllers/application_controller.rb' + - 'spec/support/capybara_sessions.rb' + - 'spec/unit/elevators/first_subdomain_spec.rb' + +# Offense count: 7 +# Cop supports --auto-correct. +Lint/DeprecatedClassMethods: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/sqlite3_adapter.rb' + - 'spec/adapters/sqlite3_adapter_spec.rb' + +# Offense count: 3 +Lint/ParenthesesAsGroupedExpression: + Exclude: + - 'spec/adapters/sqlite3_adapter_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Lint/RedundantStringCoercion: + Exclude: + - 'spec/examples/schema_adapter_examples.rb' + +# Offense count: 2 +# Configuration parameters: AllowComments. +Lint/SuppressedException: + Exclude: + - 'lib/apartment/railtie.rb' + - 'spec/spec_helper.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. +Lint/UnusedMethodArgument: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/elevators/generic.rb' + - 'spec/support/capybara_sessions.rb' + +# Offense count: 5 +Metrics/AbcSize: + Max: 33 + +# Offense count: 11 +# Configuration parameters: CountComments, ExcludedMethods. +# ExcludedMethods: refine +Metrics/BlockLength: + Max: 176 + +# Offense count: 1 +# Configuration parameters: CountComments. +Metrics/ClassLength: + Max: 155 + +# Offense count: 18 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Metrics/LineLength: + Max: 237 + +# Offense count: 4 +# Configuration parameters: CountComments, ExcludedMethods. +Metrics/MethodLength: + Max: 24 + +# Offense count: 1 +Naming/AccessorMethodName: + Exclude: + - 'spec/examples/generic_adapter_custom_configuration_example.rb' + +# Offense count: 4 +# Cop supports --auto-correct. +# Configuration parameters: PreferredName. +Naming/RescuedExceptionsVariableName: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Rails/ApplicationRecord: + Exclude: + - 'spec/dummy/app/models/company.rb' + - 'spec/dummy/app/models/user.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: Whitelist. +# Whitelist: find_by_sql +Rails/DynamicFindBy: + Exclude: + - 'spec/integration/query_caching_spec.rb' + +# Offense count: 3 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: slashes, arguments +Rails/FilePath: + Exclude: + - 'lib/apartment.rb' + - 'spec/tenant_spec.rb' + - 'spec/unit/config_spec.rb' + +# Offense count: 1 +# Configuration parameters: Include. +# Include: app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb +Rails/Output: + Exclude: + - '**/rails_helper.rb' + - 'lib/apartment/console.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Security/YAMLLoad: + Exclude: + - 'spec/support/config.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: prefer_alias, prefer_alias_method +Style/Alias: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 16 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. +# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces +# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object +# FunctionalMethods: let, let!, subject, watch +# IgnoredMethods: lambda, proc, it +Style/BlockDelimiters: + Exclude: + - 'spec/examples/connection_adapter_examples.rb' + - 'spec/examples/generic_adapter_custom_configuration_example.rb' + - 'spec/examples/generic_adapter_examples.rb' + - 'spec/examples/schema_adapter_examples.rb' + - 'spec/tasks/apartment_rake_spec.rb' + - 'spec/tenant_spec.rb' + - 'spec/unit/elevators/generic_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: braces, no_braces, context_dependent +Style/BracesAroundHashParameters: + Exclude: + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: Keywords. +# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW +Style/CommentAnnotation: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'spec/tenant_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: compact, expanded +Style/EmptyMethod: + Exclude: + - 'spec/dummy/app/controllers/application_controller.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +Style/Encoding: + Exclude: + - 'spec/schemas/v1.rb' + - 'spec/schemas/v2.rb' + - 'spec/schemas/v3.rb' + +# Offense count: 14 +# Cop supports --auto-correct. +Style/ExpandPathArguments: + Exclude: + - 'lib/generators/apartment/install/install_generator.rb' + - 'spec/adapters/sqlite3_adapter_spec.rb' + - 'spec/dummy/config/application.rb' + - 'spec/dummy/config/boot.rb' + - 'spec/dummy/config/environment.rb' + - 'spec/dummy/script/rails' + - 'spec/dummy_engine/test/dummy/config/application.rb' + - 'spec/dummy_engine/test/dummy/config/boot.rb' + - 'spec/dummy_engine/test/dummy/config/environment.rb' + - 'spec/integration/use_within_an_engine_spec.rb' + - 'spec/spec_helper.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: format, sprintf, percent +Style/FormatString: + Exclude: + - 'spec/support/apartment_helpers.rb' + +# Offense count: 1 +# Configuration parameters: . +# SupportedStyles: annotated, template, unannotated +Style/FormatStringToken: + EnforcedStyle: unannotated + +# Offense count: 107 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: always, never +Style/FrozenStringLiteralComment: + Enabled: false + +# Offense count: 2 +# Configuration parameters: MinBodyLength. +Style/GuardClause: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/tasks/apartment.rake' + +# Offense count: 33 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. +# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys +Style/HashSyntax: + Exclude: + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'spec/dummy/config/initializers/session_store.rb' + - 'spec/dummy/config/routes.rb' + - 'spec/examples/schema_adapter_examples.rb' + - 'spec/integration/apartment_rake_integration_spec.rb' + - 'spec/schemas/v1.rb' + - 'spec/schemas/v2.rb' + - 'spec/schemas/v3.rb' + - 'spec/support/contexts.rb' + - 'spec/tenant_spec.rb' + - 'spec/unit/elevators/first_subdomain_spec.rb' + - 'spec/unit/reloader_spec.rb' + +# Offense count: 6 +# Cop supports --auto-correct. +Style/IfUnlessModifier: + Exclude: + - '.pryrc' + - 'lib/apartment.rb' + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + +# Offense count: 7 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: line_count_dependent, lambda, literal +Style/Lambda: + Exclude: + - 'lib/generators/apartment/install/templates/apartment.rb' + - 'spec/dummy/config/initializers/apartment.rb' + - 'spec/integration/apartment_rake_integration_spec.rb' + - 'spec/integration/query_caching_spec.rb' + - 'spec/unit/config_spec.rb' + +# Offense count: 1 +Style/MixinUsage: + Exclude: + - '.pryrc' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, Autocorrect. +# SupportedStyles: module_function, extend_self +Style/ModuleFunction: + Exclude: + - 'spec/support/apartment_helpers.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +Style/MultilineIfModifier: + Exclude: + - 'lib/apartment/adapters/sqlite3_adapter.rb' + - 'lib/apartment/elevators/host_hash.rb' + - 'spec/support/requirements.rb' + +# Offense count: 2 +Style/MultilineTernaryOperator: + Exclude: + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/mysql2_adapter.rb' + +# Offense count: 7 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: literals, strict +Style/MutableConstant: + Exclude: + - 'lib/apartment.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/tasks/enhancements.rb' + - 'lib/apartment/version.rb' + - 'spec/dummy_engine/lib/dummy_engine/version.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: Strict. +Style/NumericLiterals: + MinDigits: 15 + +# Offense count: 2 +# Cop supports --auto-correct. +Style/ParallelAssignment: + Exclude: + - 'lib/apartment/adapters/postgresql_adapter.rb' + +# Offense count: 29 +# Cop supports --auto-correct. +# Configuration parameters: PreferredDelimiters. +Style/PercentLiteralDelimiters: + Exclude: + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/tasks/enhancements.rb' + - 'spec/dummy/config/application.rb' + - 'spec/dummy_engine/config/initializers/apartment.rb' + - 'spec/examples/schema_adapter_examples.rb' + - 'spec/integration/apartment_rake_integration_spec.rb' + - 'spec/support/requirements.rb' + - 'spec/unit/elevators/host_spec.rb' + - 'spec/unit/elevators/subdomain_spec.rb' + - 'spec/unit/migrator_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: short, verbose +Style/PreferredHashMethods: + Exclude: + - 'lib/apartment/elevators/host_hash.rb' + +# Offense count: 13 +# Cop supports --auto-correct. +Style/Proc: + Exclude: + - 'lib/apartment/console.rb' + - 'spec/unit/elevators/domain_spec.rb' + - 'spec/unit/elevators/generic_spec.rb' + - 'spec/unit/elevators/host_hash_spec.rb' + - 'spec/unit/elevators/host_spec.rb' + - 'spec/unit/elevators/subdomain_spec.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: compact, exploded +Style/RaiseArgs: + Exclude: + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/RandomWithOffset: + Exclude: + - 'spec/integration/apartment_rake_integration_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/RedundantBegin: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, AllowInnerSlashes. +# SupportedStyles: slashes, percent_r, mixed +Style/RegexpLiteral: + Exclude: + - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' + - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' + - 'spec/examples/schema_adapter_examples.rb' + +# Offense count: 9 +# Cop supports --auto-correct. +Style/RescueModifier: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + - 'spec/adapters/sqlite3_adapter_spec.rb' + - 'spec/examples/schema_adapter_examples.rb' + - 'spec/support/apartment_helpers.rb' + - 'spec/support/requirements.rb' + - 'spec/tenant_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AllowAsExpressionSeparator. +Style/Semicolon: + Exclude: + - 'spec/adapters/postgresql_adapter_spec.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle. +# SupportedStyles: use_perl_names, use_english_names +Style/SpecialGlobalVars: + Exclude: + - 'spec/dummy/config/boot.rb' + +# Offense count: 518 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. +# SupportedStyles: single_quotes, double_quotes +Style/StringLiterals: + Enabled: false + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: MinSize. +# SupportedStyles: percent, brackets +Style/SymbolArray: + EnforcedStyle: brackets + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: IgnoredMethods. +# IgnoredMethods: respond_to, define_method +Style/SymbolProc: + Exclude: + - 'lib/tasks/apartment.rake' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleForMultiline. +# SupportedStylesForMultiline: comma, consistent_comma, no_comma +Style/TrailingCommaInArrayLiteral: + Exclude: + - 'lib/apartment/adapters/postgresql_adapter.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethod. +# AllowedMethod: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym +Style/TrivialAccessors: + Exclude: + - 'lib/apartment/elevators/host.rb' + - 'lib/apartment/elevators/subdomain.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +Style/UnlessElse: + Exclude: + - 'lib/apartment/adapters/abstract_adapter.rb' + +# Offense count: 5 +# Cop supports --auto-correct. +# Configuration parameters: WordRegex. +# SupportedStyles: percent, brackets +Style/WordArray: + EnforcedStyle: percent + MinSize: 3 diff --git a/Gemfile b/Gemfile index bdbf6fe1..d24bee04 100644 --- a/Gemfile +++ b/Gemfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + source 'http://rubygems.org' gemspec @@ -5,6 +7,6 @@ gemspec gem 'rails', '>= 3.1.2' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end diff --git a/apartment.gemspec b/apartment.gemspec index e00a1304..f693da01 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -28,6 +28,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'appraisal' s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' s.add_development_dependency 'capybara', '~> 2.0' + s.add_development_dependency 'perx-rubocop', '~> 0.0.3' s.add_development_dependency 'rake', '~> 0.9' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'rspec-rails', '~> 3.4' diff --git a/spec/integration/apartment_rake_integration_spec.rb b/spec/integration/apartment_rake_integration_spec.rb index 4b9b098d..67013069 100644 --- a/spec/integration/apartment_rake_integration_spec.rb +++ b/spec/integration/apartment_rake_integration_spec.rb @@ -1,8 +1,9 @@ +# frozen_string_literal: true + require 'spec_helper' require 'rake' describe "apartment rake tasks", database: :postgresql do - before do @rake = Rake::Application.new Rake.application = @rake @@ -30,7 +31,6 @@ after { Rake.application = nil } context "with x number of databases" do - let(:x){ 1 + rand(5) } # random number of dbs to create let(:db_names){ x.times.map{ Apartment::Test.next_db } } let!(:company_count){ db_names.length } From 3846636b0c1e356d36bbd4a924eb59942e80416c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 11:05:34 +0800 Subject: [PATCH 009/282] WIP - moved rubocop to gemfile instead of dev dependency --- Gemfile | 1 + README.md | 7 +++++++ apartment.gemspec | 1 - 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index d24bee04..8bad8db6 100644 --- a/Gemfile +++ b/Gemfile @@ -5,6 +5,7 @@ source 'http://rubygems.org' gemspec gem 'rails', '>= 3.1.2' +gem 'perx-rubocop', '~> 0.0.3' group :local do gem 'guard-rspec', '~> 4.2' diff --git a/README.md b/README.md index f6c6d03b..cb6c82b9 100644 --- a/README.md +++ b/README.md @@ -569,6 +569,13 @@ end * If you're looking to help, check out the TODO file for some upcoming changes I'd like to implement in Apartment. +### Running bundle install + +mysql2 gem in some cases fails to install. +If you face problems running bundle install in OSX, try installing the gem running: + +`gem install mysql2 -v '0.5.3' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include` + ## License Apartment is released under the [MIT License](http://www.opensource.org/licenses/MIT). diff --git a/apartment.gemspec b/apartment.gemspec index f693da01..e00a1304 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -28,7 +28,6 @@ Gem::Specification.new do |s| s.add_development_dependency 'appraisal' s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' s.add_development_dependency 'capybara', '~> 2.0' - s.add_development_dependency 'perx-rubocop', '~> 0.0.3' s.add_development_dependency 'rake', '~> 0.9' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'rspec-rails', '~> 3.4' From 44e86eb602a3b0a6602d851048b8caa750c3f42c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 11:18:54 +0800 Subject: [PATCH 010/282] WIP - moved rails 5.2 with ruby 2.2.9 to allowed failures --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index cefc8560..9c634d9a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,6 +36,10 @@ jobs: - gemfile: gemfiles/rails_master.gemfile - rvm: jruby-9.1.17.0 gemfile: gemfiles/rails_5_0.gemfile + # Rails 5.2.4.1 is currently broken. Code has been fixed but no release + # for it yet - https://github.com/rails/rails/issues/38137 + - rvm: 2.2.9 + gemfile: gemfiles/rails_5_2.gemfile exclude: - rvm: 2.1.9 gemfile: gemfiles/rails_5_0.gemfile From 812d1292dfb3f6390cb415603b4c0e1157d9223a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 11:26:53 +0800 Subject: [PATCH 011/282] WIP - added rubocop lint --- .github/workflows/.rubocop-linter.yml | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 .github/workflows/.rubocop-linter.yml diff --git a/.github/workflows/.rubocop-linter.yml b/.github/workflows/.rubocop-linter.yml new file mode 100644 index 00000000..cab9704b --- /dev/null +++ b/.github/workflows/.rubocop-linter.yml @@ -0,0 +1,22 @@ +name: Rubocop Lint + +on: [push] + +jobs: + build: + + runs-on: ubuntu-latest + + container: + image: ruby:2.6.5 + + steps: + - uses: actions/checkout@v1 + - name: Rubocop Linter + uses: andrewmcodes/rubocop-linter-action@v2.0.0 + with: + additional_gems: 'perx-rubocop:0.0.3' + fail_level: 'warning' + version: '0.77.0' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 40d335035d5c9573521bcae1ccc0f5c883913bba Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 15:47:38 +0800 Subject: [PATCH 012/282] WIP - starting to cleanup --- .rubocop_todo.yml | 3 +-- spec/unit/migrator_spec.rb | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 383eaf02..e31033be 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -426,7 +426,7 @@ Style/Alias: # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. # SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces -# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object +# ProceduralMethods: benchmark, bm, create, each_with_object, measure, new, realtime, tap, with_object # FunctionalMethods: let, let!, subject, watch # IgnoredMethods: lambda, proc, it Style/BlockDelimiters: @@ -623,7 +623,6 @@ Style/PercentLiteralDelimiters: - 'spec/support/requirements.rb' - 'spec/unit/elevators/host_spec.rb' - 'spec/unit/elevators/subdomain_spec.rb' - - 'spec/unit/migrator_spec.rb' # Offense count: 1 # Cop supports --auto-correct. diff --git a/spec/unit/migrator_spec.rb b/spec/unit/migrator_spec.rb index 242b6b97..ade34c73 100644 --- a/spec/unit/migrator_spec.rb +++ b/spec/unit/migrator_spec.rb @@ -3,19 +3,19 @@ describe Apartment::Migrator do - let(:tenant){ Apartment::Test.next_db } + let(:tenant) { Apartment::Test.next_db } # Don't need a real switch here, just testing behaviour before { allow(Apartment::Tenant.adapter).to receive(:connect_to_new) } - context "with ActiveRecord below 5.2.0", skip: ActiveRecord.version >= Gem::Version.new("5.2.0") do + context 'with ActiveRecord below 5.2.0', skip: ActiveRecord.version >= Gem::Version.new('5.2.0') do before do allow(ActiveRecord::Migrator).to receive(:migrations_paths) { %w(spec/dummy/db/migrate) } allow(Apartment::Migrator).to receive(:activerecord_below_5_2?) { true } end - describe "::migrate" do - it "switches and migrates" do + describe '::migrate' do + it 'switches and migrates' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect(ActiveRecord::Migrator).to receive(:migrate) @@ -23,8 +23,8 @@ end end - describe "::run" do - it "switches and runs" do + describe '::run' do + it 'switches and runs' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect(ActiveRecord::Migrator).to receive(:run).with(:up, anything, 1234) @@ -32,8 +32,8 @@ end end - describe "::rollback" do - it "switches and rolls back" do + describe '::rollback' do + it 'switches and rolls back' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect(ActiveRecord::Migrator).to receive(:rollback).with(anything, 2) @@ -42,13 +42,13 @@ end end - context "with ActiveRecord above or equal to 5.2.0", skip: ActiveRecord.version < Gem::Version.new("5.2.0") do + context 'with ActiveRecord above or equal to 5.2.0', skip: ActiveRecord.version < Gem::Version.new('5.2.0') do before do allow(Apartment::Migrator).to receive(:activerecord_below_5_2?) { false } end - describe "::migrate" do - it "switches and migrates" do + describe '::migrate' do + it 'switches and migrates' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect_any_instance_of(ActiveRecord::MigrationContext).to receive(:migrate) @@ -56,8 +56,8 @@ end end - describe "::run" do - it "switches and runs" do + describe '::run' do + it 'switches and runs' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect_any_instance_of(ActiveRecord::MigrationContext).to receive(:run).with(:up, 1234) @@ -65,8 +65,8 @@ end end - describe "::rollback" do - it "switches and rolls back" do + describe '::rollback' do + it 'switches and rolls back' do expect(Apartment::Tenant).to receive(:switch).with(tenant).and_call_original expect_any_instance_of(ActiveRecord::MigrationContext).to receive(:rollback).with(2) From b335c2a97058bfc0acf26e0744b8b047960124c7 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 15:51:16 +0800 Subject: [PATCH 013/282] WIP - ran autocorrect --- lib/apartment.rb | 2 +- lib/apartment/adapters/abstract_adapter.rb | 4 ++-- lib/apartment/console.rb | 2 +- lib/apartment/tenant.rb | 4 +--- spec/adapters/mysql2_adapter_spec.rb | 2 +- spec/adapters/postgresql_adapter_spec.rb | 8 ++++---- spec/adapters/sqlite3_adapter_spec.rb | 2 +- spec/dummy/config/initializers/apartment.rb | 2 +- spec/examples/connection_adapter_examples.rb | 2 +- spec/examples/generic_adapter_examples.rb | 4 ++-- spec/examples/schema_adapter_examples.rb | 20 +++++++++---------- .../apartment_rake_integration_spec.rb | 10 +++++----- spec/integration/query_caching_spec.rb | 6 +++--- spec/integration/use_within_an_engine_spec.rb | 4 ++-- spec/spec_helper.rb | 2 +- spec/support/apartment_helpers.rb | 2 +- spec/support/contexts.rb | 8 ++++---- spec/support/setup.rb | 6 +++--- spec/tasks/apartment_rake_spec.rb | 12 +++++------ spec/tenant_spec.rb | 20 +++++++++---------- spec/unit/config_spec.rb | 4 ++-- spec/unit/elevators/domain_spec.rb | 2 +- spec/unit/elevators/generic_spec.rb | 6 +++--- spec/unit/elevators/host_hash_spec.rb | 2 +- spec/unit/elevators/host_spec.rb | 2 +- spec/unit/elevators/subdomain_spec.rb | 2 +- spec/unit/migrator_spec.rb | 2 +- spec/unit/reloader_spec.rb | 2 +- 28 files changed, 71 insertions(+), 73 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index b20a7728..594dc1bd 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -84,7 +84,7 @@ def pg_excluded_names # Reset all the config for Apartment def reset - (ACCESSOR_METHODS + WRITER_METHODS).each{|method| remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") } + (ACCESSOR_METHODS + WRITER_METHODS).each {|method| remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") } end def extract_tenant_config diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 78b844b9..c3982ee9 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -93,7 +93,7 @@ def switch(tenant = nil) # def each(tenants = Apartment.tenant_names) tenants.each do |tenant| - switch(tenant){ yield tenant } + switch(tenant) { yield tenant } end end @@ -116,7 +116,7 @@ def reset # def seed_data # Don't log the output of seeding the db - silence_warnings{ load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file + silence_warnings { load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file end alias_method :seed, :seed_data diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 6ce18832..66cefda2 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -5,7 +5,7 @@ def reload!(print=true) puts "Reloading..." if print # This triggers the to_prepare callbacks - ActionDispatch::Callbacks.new(Proc.new {}).call({}) + ActionDispatch::Callbacks.new(Proc.new{}).call({}) # Manually init Apartment again once classes are reloaded Apartment::Tenant.init true diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index acabad31..83e3cdd5 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -40,9 +40,7 @@ def adapter raise "The adapter `#{adapter_method}` is not yet supported" end - unless respond_to?(adapter_method) - raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter" - end + raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter" unless respond_to?(adapter_method) send(adapter_method, config) end diff --git a/spec/adapters/mysql2_adapter_spec.rb b/spec/adapters/mysql2_adapter_spec.rb index 78f7b589..831affed 100644 --- a/spec/adapters/mysql2_adapter_spec.rb +++ b/spec/adapters/mysql2_adapter_spec.rb @@ -4,7 +4,7 @@ describe Apartment::Adapters::Mysql2Adapter, database: :mysql do unless defined?(JRUBY_VERSION) - subject(:adapter){ Apartment::Tenant.mysql2_adapter config } + subject(:adapter) { Apartment::Tenant.mysql2_adapter config } def tenant_names ActiveRecord::Base.connection.execute("SELECT schema_name FROM information_schema.schemata").collect { |row| row[0] } diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index e246fd10..16a85eca 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -4,11 +4,11 @@ describe Apartment::Adapters::PostgresqlAdapter, database: :postgresql do unless defined?(JRUBY_VERSION) - subject{ Apartment::Tenant.postgresql_adapter config } + subject { Apartment::Tenant.postgresql_adapter config } context "using schemas with schema.rb" do - before{ Apartment.use_schemas = true } + before { Apartment.use_schemas = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names @@ -23,7 +23,7 @@ def tenant_names context "using schemas with SQL dump" do - before{ Apartment.use_schemas = true; Apartment.use_sql = true } + before { Apartment.use_schemas = true; Apartment.use_sql = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names @@ -44,7 +44,7 @@ def tenant_names context "using connections" do - before{ Apartment.use_schemas = false } + before { Apartment.use_schemas = false } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names diff --git a/spec/adapters/sqlite3_adapter_spec.rb b/spec/adapters/sqlite3_adapter_spec.rb index 55004952..f6efa035 100644 --- a/spec/adapters/sqlite3_adapter_spec.rb +++ b/spec/adapters/sqlite3_adapter_spec.rb @@ -4,7 +4,7 @@ describe Apartment::Adapters::Sqlite3Adapter, database: :sqlite do unless defined?(JRUBY_VERSION) - subject{ Apartment::Tenant.sqlite3_adapter config } + subject { Apartment::Tenant.sqlite3_adapter config } context "using connections" do def tenant_names diff --git a/spec/dummy/config/initializers/apartment.rb b/spec/dummy/config/initializers/apartment.rb index a49dda91..d7d0fcfc 100644 --- a/spec/dummy/config/initializers/apartment.rb +++ b/spec/dummy/config/initializers/apartment.rb @@ -1,4 +1,4 @@ Apartment.configure do |config| config.excluded_models = ["Company"] - config.tenant_names = lambda{ Company.pluck(:database) } + config.tenant_names = lambda { Company.pluck(:database) } end diff --git a/spec/examples/connection_adapter_examples.rb b/spec/examples/connection_adapter_examples.rb index a7d4ac9b..b335e182 100644 --- a/spec/examples/connection_adapter_examples.rb +++ b/spec/examples/connection_adapter_examples.rb @@ -3,7 +3,7 @@ shared_examples_for "a connection based apartment adapter" do include Apartment::Spec::AdapterRequirements - let(:default_tenant){ subject.switch{ ActiveRecord::Base.connection.current_database } } + let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } describe "#init" do after do diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 6c1b32ac..1ba59291 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -56,7 +56,7 @@ expect(subject.current).not_to eq(db2) - subject.switch(db2){ expect(User.count).to eq(@count + 1) } + subject.switch(db2) { expect(User.count).to eq(@count + 1) } end it "should raise error when the schema.rb is missing unless Apartment.use_sql is set to true" do @@ -115,7 +115,7 @@ subject.switch!(db2) expect { - subject.switch(db1){ subject.drop(db2) } + subject.switch(db1) { subject.drop(db2) } }.to_not raise_error end end diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 5eed5091..606033b9 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -3,9 +3,9 @@ shared_examples_for "a schema based apartment adapter" do include Apartment::Spec::AdapterRequirements - let(:schema1){ db1 } - let(:schema2){ db2 } - let(:public_schema){ default_tenant } + let(:schema1) { db1 } + let(:schema2) { db2 } + let(:public_schema) { default_tenant } describe "#init" do @@ -75,11 +75,11 @@ expect(connection.schema_search_path).not_to start_with %{"#{schema2}"} - subject.switch(schema2){ expect(User.count).to eq(@count + 1) } + subject.switch(schema2) { expect(User.count).to eq(@count + 1) } end context "numeric database names" do - let(:db){ 1234 } + let(:db) { 1234 } it "should allow them" do expect { subject.create(db) @@ -87,7 +87,7 @@ expect(tenant_names).to include(db.to_s) end - after{ subject.drop(db) } + after { subject.drop(db) } end end @@ -100,7 +100,7 @@ end context "numeric database names" do - let(:db){ 1234 } + let(:db) { 1234 } it "should be able to drop them" do subject.create(db) @@ -176,7 +176,7 @@ end context "numeric databases" do - let(:db){ 1234 } + let(:db) { 1234 } it "should connect to them" do subject.create(db) @@ -187,7 +187,7 @@ expect(connection.schema_search_path).to start_with %{"#{db.to_s}"} end - after{ subject.drop(db) } + after { subject.drop(db) } end describe "with default_schema specified", :default_schema => true do @@ -206,7 +206,7 @@ context "persistent_schemas", :persistent_schemas => true do - before{ subject.switch!(schema1) } + before { subject.switch!(schema1) } it "maintains the persistent schemas in the schema_search_path" do expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %{"#{schema}"} }.join(', ') diff --git a/spec/integration/apartment_rake_integration_spec.rb b/spec/integration/apartment_rake_integration_spec.rb index 67013069..c8e822cf 100644 --- a/spec/integration/apartment_rake_integration_spec.rb +++ b/spec/integration/apartment_rake_integration_spec.rb @@ -20,7 +20,7 @@ Apartment.configure do |config| config.use_schemas = true config.excluded_models = ["Company"] - config.tenant_names = lambda{ Company.pluck(:database) } + config.tenant_names = lambda { Company.pluck(:database) } end Apartment::Tenant.reload!(config) @@ -31,9 +31,9 @@ after { Rake.application = nil } context "with x number of databases" do - let(:x){ 1 + rand(5) } # random number of dbs to create - let(:db_names){ x.times.map{ Apartment::Test.next_db } } - let!(:company_count){ db_names.length } + let(:x) { 1 + rand(5) } # random number of dbs to create + let(:db_names) { x.times.map { Apartment::Test.next_db } } + let!(:company_count) { db_names.length } before do db_names.collect do |db_name| @@ -43,7 +43,7 @@ end after do - db_names.each{ |db| Apartment::Tenant.drop(db) } + db_names.each { |db| Apartment::Tenant.drop(db) } Company.delete_all end diff --git a/spec/integration/query_caching_spec.rb b/spec/integration/query_caching_spec.rb index 7bf08996..10cbaa97 100644 --- a/spec/integration/query_caching_spec.rb +++ b/spec/integration/query_caching_spec.rb @@ -7,7 +7,7 @@ before do Apartment.configure do |config| config.excluded_models = ["Company"] - config.tenant_names = lambda{ Company.pluck(:database) } + config.tenant_names = lambda { Company.pluck(:database) } config.use_schemas = true end @@ -20,7 +20,7 @@ end after do - db_names.each{ |db| Apartment::Tenant.drop(db) } + db_names.each { |db| Apartment::Tenant.drop(db) } Apartment::Tenant.reset Company.delete_all end @@ -47,7 +47,7 @@ before do Apartment.configure do |config| config.excluded_models = ["Company"] - config.tenant_names = lambda{ Company.pluck(:database) } + config.tenant_names = lambda { Company.pluck(:database) } config.use_schemas = false end diff --git a/spec/integration/use_within_an_engine_spec.rb b/spec/integration/use_within_an_engine_spec.rb index 904a9238..21873df1 100644 --- a/spec/integration/use_within_an_engine_spec.rb +++ b/spec/integration/use_within_an_engine_spec.rb @@ -10,11 +10,11 @@ end it 'sucessfully runs rake db:migrate in the engine root' do - expect{ Rake::Task['db:migrate'].invoke }.to_not raise_error + expect { Rake::Task['db:migrate'].invoke }.to_not raise_error end it 'sucessfully runs rake app:db:migrate in the engine root' do - expect{ Rake::Task['app:db:migrate'].invoke }.to_not raise_error + expect { Rake::Task['app:db:migrate'].invoke }.to_not raise_error end context 'when Apartment.db_migrate_tenants is false' do diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 73cca8f4..74aa9c8d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -22,7 +22,7 @@ begin require 'pry' - silence_warnings{ IRB = Pry } + silence_warnings { IRB = Pry } rescue LoadError end diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 795f172a..9c4a43bf 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -28,7 +28,7 @@ def create_schema(schema) def load_schema(version = 3) file = File.expand_path("../../schemas/v#{version}.rb", __FILE__) - silence_warnings{ load(file) } + silence_warnings { load(file) } end def migrate diff --git a/spec/support/contexts.rb b/spec/support/contexts.rb index ffb10a04..3fbf1a42 100644 --- a/spec/support/contexts.rb +++ b/spec/support/contexts.rb @@ -1,7 +1,7 @@ # Some shared contexts for specs shared_context "with default schema", :default_schema => true do - let(:default_schema){ Apartment::Test.next_db } + let(:default_schema) { Apartment::Test.next_db } before do Apartment::Test.create_schema(default_schema) @@ -38,15 +38,15 @@ end shared_context "persistent_schemas", :persistent_schemas => true do - let(:persistent_schemas){ ['hstore', 'postgis'] } + let(:persistent_schemas) { ['hstore', 'postgis'] } before do - persistent_schemas.map{|schema| subject.create(schema) } + persistent_schemas.map {|schema| subject.create(schema) } Apartment.persistent_schemas = persistent_schemas end after do Apartment.persistent_schemas = [] - persistent_schemas.map{|schema| subject.drop(schema) } + persistent_schemas.map {|schema| subject.drop(schema) } end end \ No newline at end of file diff --git a/spec/support/setup.rb b/spec/support/setup.rb index 8441da3d..d4a68512 100644 --- a/spec/support/setup.rb +++ b/spec/support/setup.rb @@ -4,9 +4,9 @@ module Setup def self.included(base) base.instance_eval do - let(:db1){ Apartment::Test.next_db } - let(:db2){ Apartment::Test.next_db } - let(:connection){ ActiveRecord::Base.connection } + let(:db1) { Apartment::Test.next_db } + let(:db2) { Apartment::Test.next_db } + let(:connection) { ActiveRecord::Base.connection } # This around ensures that we run these hooks before and after # any before/after hooks defined in individual tests diff --git a/spec/tasks/apartment_rake_spec.rb b/spec/tasks/apartment_rake_spec.rb index 0f86aeee..0514676d 100644 --- a/spec/tasks/apartment_rake_spec.rb +++ b/spec/tasks/apartment_rake_spec.rb @@ -27,12 +27,12 @@ Apartment::Test.load_schema end - let(:version){ '1234' } + let(:version) { '1234' } context 'database migration' do - let(:tenant_names){ 3.times.map{ Apartment::Test.next_db } } - let(:tenant_count){ tenant_names.length } + let(:tenant_names) { 3.times.map { Apartment::Test.next_db } } + let(:tenant_count) { tenant_names.length } before do allow(Apartment).to receive(:tenant_names).and_return tenant_names @@ -57,7 +57,7 @@ end it "requires a version to migrate to" do - expect{ + expect { @rake['apartment:migrate:up'].invoke }.to raise_error("VERSION is required") end @@ -84,7 +84,7 @@ end it "requires a version to migrate to" do - expect{ + expect { @rake['apartment:migrate:down'].invoke }.to raise_error("VERSION is required") end @@ -104,7 +104,7 @@ end describe "apartment:rollback" do - let(:step){ '3' } + let(:step) { '3' } it "should rollback dbs" do expect(Apartment::Migrator).to receive(:rollback).exactly(tenant_count).times diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index 261185a6..17dfe801 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -18,7 +18,7 @@ before do subject.create db1 end - after{ subject.drop db1 } + after { subject.drop db1 } # it "should recover from incorrect database" do # session = Capybara::Session.new(:rack_test, Capybara.app) @@ -94,7 +94,7 @@ subject.create db1 end - after{ subject.drop db1 } + after { subject.drop db1 } describe "#create" do it "should seed data" do @@ -105,19 +105,19 @@ describe "#switch!" do - let(:x){ rand(3) } + let(:x) { rand(3) } context "creating models" do - before{ subject.create db2 } - after{ subject.drop db2 } + before { subject.create db2 } + after { subject.drop db2 } it "should create a model instance in the current schema" do subject.switch! db2 - db2_count = User.count + x.times{ User.create } + db2_count = User.count + x.times { User.create } subject.switch! db1 - db_count = User.count + x.times{ User.create } + db_count = User.count + x.times { User.create } subject.switch! db2 expect(User.count).to eq(db2_count) @@ -146,10 +146,10 @@ it "should create excluded models in public schema" do subject.reset # ensure we're on public schema - count = Company.count + x.times{ Company.create } + count = Company.count + x.times { Company.create } subject.switch! db1 - x.times{ Company.create } + x.times { Company.create } expect(Company.count).to eq(count + x) subject.reset expect(Company.count).to eq(count + x) @@ -167,7 +167,7 @@ end end - after{ subject.drop db1 } + after { subject.drop db1 } it 'should seed from default path' do subject.create db1 diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index 44901952..40320a31 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -4,8 +4,8 @@ describe "#config" do - let(:excluded_models){ ["Company"] } - let(:seed_data_file_path){ "#{Rails.root}/db/seeds/import.rb" } + let(:excluded_models) { ["Company"] } + let(:seed_data_file_path) { "#{Rails.root}/db/seeds/import.rb" } def tenant_names_from_array(names) names.each_with_object({}) do |tenant, hash| diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index cbdf9fb2..713cd88c 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Domain do - subject(:elevator){ described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(Proc.new{}) } describe "#parse_tenant_name" do it "parses the host for a domain name" do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index 6278dfe7..bca84dc9 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -9,11 +9,11 @@ def parse_tenant_name(*) end end - subject(:elevator){ described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(Proc.new{}) } describe "#call" do it "calls the processor if given" do - elevator = described_class.new(Proc.new{}, Proc.new{'tenant1'}) + elevator = described_class.new(Proc.new{}, Proc.new {'tenant1'}) expect(Apartment::Tenant).to receive(:switch).with('tenant1') @@ -35,7 +35,7 @@ def parse_tenant_name(*) end it "calls the block implementation of `switch`" do - elevator = MyElevator.new(Proc.new{}, Proc.new{'tenant2'}) + elevator = MyElevator.new(Proc.new{}, Proc.new {'tenant2'}) expect(Apartment::Tenant).to receive(:switch).with('tenant2').and_yield elevator.call('HTTP_HOST' => 'foo.bar.com') diff --git a/spec/unit/elevators/host_hash_spec.rb b/spec/unit/elevators/host_hash_spec.rb index c748b70d..039912ec 100644 --- a/spec/unit/elevators/host_hash_spec.rb +++ b/spec/unit/elevators/host_hash_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::HostHash do - subject(:elevator){ Apartment::Elevators::HostHash.new(Proc.new{}, 'example.com' => 'example_tenant') } + subject(:elevator) { Apartment::Elevators::HostHash.new(Proc.new{}, 'example.com' => 'example_tenant') } describe "#parse_tenant_name" do it "parses the host for a domain name" do diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index 96ea057c..c8daaa37 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Host do - subject(:elevator){ described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(Proc.new{}) } describe "#parse_tenant_name" do diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index 1df11466..71feb6c7 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Subdomain do - subject(:elevator){ described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(Proc.new{}) } describe "#parse_tenant_name" do context "assuming one tld" do diff --git a/spec/unit/migrator_spec.rb b/spec/unit/migrator_spec.rb index ade34c73..0022be74 100644 --- a/spec/unit/migrator_spec.rb +++ b/spec/unit/migrator_spec.rb @@ -10,7 +10,7 @@ context 'with ActiveRecord below 5.2.0', skip: ActiveRecord.version >= Gem::Version.new('5.2.0') do before do - allow(ActiveRecord::Migrator).to receive(:migrations_paths) { %w(spec/dummy/db/migrate) } + allow(ActiveRecord::Migrator).to receive(:migrations_paths) { %w[spec/dummy/db/migrate] } allow(Apartment::Migrator).to receive(:activerecord_below_5_2?) { true } end diff --git a/spec/unit/reloader_spec.rb b/spec/unit/reloader_spec.rb index ffe30988..5034f7dc 100644 --- a/spec/unit/reloader_spec.rb +++ b/spec/unit/reloader_spec.rb @@ -13,7 +13,7 @@ Company.reset_table_name # ensure we're clean end - subject{ Apartment::Reloader.new(double("Rack::Application", :call => nil)) } + subject { Apartment::Reloader.new(double("Rack::Application", :call => nil)) } it "should initialize apartment when called" do expect(Company.table_name).not_to include('public.') From 017c7a8d8935b741e96d8fd1b45f8c3eba27d8da Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:01:51 +0800 Subject: [PATCH 014/282] [Hotfix] Fixed modifier indentation --- .rubocop_todo.yml | 16 +--------------- lib/apartment/adapters/abstract_adapter.rb | 4 ++-- lib/apartment/adapters/abstract_jdbc_adapter.rb | 2 +- .../adapters/jdbc_postgresql_adapter.rb | 4 ++-- lib/apartment/adapters/mysql2_adapter.rb | 4 ++-- lib/apartment/adapters/postgresql_adapter.rb | 8 ++++---- lib/apartment/adapters/sqlite3_adapter.rb | 4 ++-- lib/apartment/elevators/subdomain.rb | 2 +- 8 files changed, 15 insertions(+), 29 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index e31033be..7f794fec 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,20 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 13 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: outdent, indent -Layout/AccessModifierIndentation: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/adapters/sqlite3_adapter.rb' - - 'lib/apartment/elevators/subdomain.rb' - # Offense count: 4 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, IndentationWidth. @@ -426,7 +412,7 @@ Style/Alias: # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. # SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces -# ProceduralMethods: benchmark, bm, create, each_with_object, measure, new, realtime, tap, with_object +# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object # FunctionalMethods: let, let!, subject, watch # IgnoredMethods: lambda, proc, it Style/BlockDelimiters: diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index c3982ee9..7974a769 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -139,7 +139,7 @@ def environmentify(tenant) end end - protected + protected def process_excluded_model(excluded_model) excluded_model.constantize.establish_connection @config @@ -234,7 +234,7 @@ def db_connection_config(tenant) Apartment.db_config_for(tenant).clone end - def with_neutral_connection(tenant, &block) + def with_neutral_connection(tenant, &block) if Apartment.with_multi_server_setup # neutral connection is necessary whenever you need to create/remove a database from a server. # example: when you use postgresql, you need to connect to the default postgresql database before you create your own. diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index c4f7f32f..be72414e 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -4,7 +4,7 @@ module Apartment module Adapters class AbstractJDBCAdapter < AbstractAdapter - private + private def multi_tenantify_with_tenant_db_name(config, tenant) config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}" diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index f0922d8c..4278a2d6 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -15,7 +15,7 @@ module Adapters # Default adapter when not using Postgresql Schemas class JDBCPostgresqlAdapter < PostgresqlAdapter - private + private def multi_tenantify_with_tenant_db_name(config, tenant) config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}" @@ -46,7 +46,7 @@ def connect_to_new(tenant = nil) raise TenantNotFound, "One of the following schema(s) is invalid: #{full_search_path}" end - private + private def rescue_from ActiveRecord::JDBCError diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index d1e324ca..780710d3 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -19,7 +19,7 @@ def initialize(config) @default_tenant = config[:database] end - protected + protected def rescue_from Mysql2::Error @@ -40,7 +40,7 @@ def reset Apartment.connection.execute "use `#{default_tenant}`" end - protected + protected # Connect to new tenant # diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 446b9b5d..cd1a6df5 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -15,7 +15,7 @@ module Adapters # Default adapter when not using Postgresql Schemas class PostgresqlAdapter < AbstractAdapter - private + private def rescue_from PG::Error @@ -44,7 +44,7 @@ def current @current || default_tenant end - protected + protected def process_excluded_model(excluded_model) excluded_model.constantize.tap do |klass| @@ -79,7 +79,7 @@ def connect_to_new(tenant = nil) raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}" end - private + private def create_tenant_command(conn, tenant) conn.execute(%{CREATE SCHEMA "#{tenant}"}) @@ -122,7 +122,7 @@ def import_database_schema end end - private + private # Re-set search path after the schema is imported. # Postgres now sets search path to empty before dumping the schema diff --git a/lib/apartment/adapters/sqlite3_adapter.rb b/lib/apartment/adapters/sqlite3_adapter.rb index dff5a21b..e16dd544 100644 --- a/lib/apartment/adapters/sqlite3_adapter.rb +++ b/lib/apartment/adapters/sqlite3_adapter.rb @@ -26,7 +26,7 @@ def current File.basename(Apartment.connection.instance_variable_get(:@config)[:database], '.sqlite3') end - protected + protected def connect_to_new(tenant) raise TenantNotFound, @@ -46,7 +46,7 @@ def create_tenant(tenant) end end - private + private def database_file(tenant) "#{@default_dir}/#{environmentify(tenant)}.sqlite3" diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index c625e29b..b522bfef 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -29,7 +29,7 @@ def parse_tenant_name(request) tenant.presence end - protected + protected # *Almost* a direct ripoff of ActionDispatch::Request subdomain methods From 7d66739c33ed67a83eb8094ed432f53d97d8e9b6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:03:12 +0800 Subject: [PATCH 015/282] WIP - fixed braces around hash params --- .rubocop_todo.yml | 8 -------- lib/apartment/adapters/jdbc_postgresql_adapter.rb | 2 +- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 7f794fec..6932727c 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -425,14 +425,6 @@ Style/BlockDelimiters: - 'spec/tenant_spec.rb' - 'spec/unit/elevators/generic_spec.rb' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: braces, no_braces, context_dependent -Style/BracesAroundHashParameters: - Exclude: - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - # Offense count: 5 # Cop supports --auto-correct. # Configuration parameters: Keywords. diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 4278a2d6..6b0f18cb 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -22,7 +22,7 @@ def multi_tenantify_with_tenant_db_name(config, tenant) end def create_tenant_command(conn, tenant) - conn.create_database(environmentify(tenant), { :thisisahack => '' }) + conn.create_database(environmentify(tenant), :thisisahack => '') end def rescue_from From 0cadb661207f25bc4f44e1e1d286cc879d4be633 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:05:41 +0800 Subject: [PATCH 016/282] WIP - fixed array of strings --- .rubocop_todo.yml | 14 -------------- lib/apartment/adapters/abstract_adapter.rb | 2 +- spec/support/contexts.rb | 4 ++-- spec/unit/config_spec.rb | 4 ++-- 4 files changed, 5 insertions(+), 19 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 6932727c..9514bce9 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -716,17 +716,3 @@ Style/TrivialAccessors: Exclude: - 'lib/apartment/elevators/host.rb' - 'lib/apartment/elevators/subdomain.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/UnlessElse: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: WordRegex. -# SupportedStyles: percent, brackets -Style/WordArray: - EnforcedStyle: percent - MinSize: 3 diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 7974a769..4ad8f870 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -126,7 +126,7 @@ def seed_data # @return {String} tenant name with Rails environment *optionally* prepended # def environmentify(tenant) - unless tenant.include?(Rails.env) + if !tenant.include?(Rails.env) if Apartment.prepend_environment "#{Rails.env}_#{tenant}" elsif Apartment.append_environment diff --git a/spec/support/contexts.rb b/spec/support/contexts.rb index 3fbf1a42..844f4e0a 100644 --- a/spec/support/contexts.rb +++ b/spec/support/contexts.rb @@ -38,7 +38,7 @@ end shared_context "persistent_schemas", :persistent_schemas => true do - let(:persistent_schemas) { ['hstore', 'postgis'] } + let(:persistent_schemas) { %w[hstore postgis] } before do persistent_schemas.map {|schema| subject.create(schema) } @@ -49,4 +49,4 @@ Apartment.persistent_schemas = [] persistent_schemas.map {|schema| subject.drop(schema) } end -end \ No newline at end of file +end diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index 40320a31..eea2e2fe 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -60,7 +60,7 @@ def tenant_names_from_array(names) end context "tenant_names as string array" do - let(:tenant_names) { ['users', 'companies'] } + let(:tenant_names) { %w[users companies] } it "should return object if it doesnt respond_to call" do expect(Apartment.tenant_names).to eq(tenant_names_from_array(tenant_names).keys) @@ -72,7 +72,7 @@ def tenant_names_from_array(names) end context "tenant_names as proc returning an array" do - let(:tenant_names) { lambda { ['users', 'companies'] } } + let(:tenant_names) { lambda { %w[users companies] } } it "should return object if it doesnt respond_to call" do expect(Apartment.tenant_names).to eq(tenant_names_from_array(tenant_names.call).keys) From 8ba3245a357c630c929d9a0b48ed7a9ba81e78a9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:07:43 +0800 Subject: [PATCH 017/282] [Hotfix] fixed array of strings for schemas rb --- .rubocop.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 902dcf64..50fd0197 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -3,3 +3,7 @@ inherit_from: .rubocop_todo.yml inherit_gem: perx-rubocop: - default.yml + +Style/WordArray: + Exclude: + - spec/schemas/**/*.rb From b4371899893414c8e1019015575e33b9631c5175 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:14:03 +0800 Subject: [PATCH 018/282] WIP - removed a few more broken rules in rubocop --- .rubocop_todo.yml | 17 ----------------- lib/apartment/adapters/postgresql_adapter.rb | 2 +- lib/apartment/elevators/host.rb | 8 +++----- lib/apartment/elevators/subdomain.rb | 6 ++---- 4 files changed, 6 insertions(+), 27 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 9514bce9..f0c67aff 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -699,20 +699,3 @@ Style/SymbolArray: Style/SymbolProc: Exclude: - 'lib/tasks/apartment.rake' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleForMultiline. -# SupportedStylesForMultiline: comma, consistent_comma, no_comma -Style/TrailingCommaInArrayLiteral: - Exclude: - - 'lib/apartment/adapters/postgresql_adapter.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: ExactNameMatch, AllowPredicates, AllowDSLWriters, IgnoreClassMethods, AllowedMethod. -# AllowedMethod: to_ary, to_a, to_c, to_enum, to_h, to_hash, to_i, to_int, to_io, to_open, to_path, to_proc, to_r, to_regexp, to_str, to_s, to_sym -Style/TrivialAccessors: - Exclude: - - 'lib/apartment/elevators/host.rb' - - 'lib/apartment/elevators/subdomain.rb' diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index cd1a6df5..070415a0 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -111,7 +111,7 @@ class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter /SET row_security/i, # new in postgresql 9.5 /SET idle_in_transaction_session_timeout/i, # new in postgresql 9.6 /CREATE SCHEMA public/i, - /COMMENT ON SCHEMA public/i, + /COMMENT ON SCHEMA public/i ] diff --git a/lib/apartment/elevators/host.rb b/lib/apartment/elevators/host.rb index c8cbd2f8..c62d47e2 100644 --- a/lib/apartment/elevators/host.rb +++ b/lib/apartment/elevators/host.rb @@ -12,14 +12,12 @@ module Elevators # www.a.b.c.d.com => a.b.c.d.com # class Host < Generic + attr_writer ignored_first_subdomains + def self.ignored_first_subdomains @ignored_first_subdomains ||= [] end - def self.ignored_first_subdomains=(arg) - @ignored_first_subdomains = arg - end - def parse_tenant_name(request) return nil if request.host.blank? parts = request.host.split('.') @@ -27,4 +25,4 @@ def parse_tenant_name(request) end end end -end \ No newline at end of file +end diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index b522bfef..8380f758 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -7,14 +7,12 @@ module Elevators # Assumes that tenant name should match subdomain # class Subdomain < Generic + attr_writer :excluded_subdomains + def self.excluded_subdomains @excluded_subdomains ||= [] end - def self.excluded_subdomains=(arg) - @excluded_subdomains = arg - end - def parse_tenant_name(request) request_subdomain = subdomain(request.host) From 2bc9f84bc3106371278aeba716efb6b7d745615e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:31:05 +0800 Subject: [PATCH 019/282] WIP - cleanup a few more rubocop --- .rubocop_todo.yml | 72 ------------------- lib/apartment.rb | 9 ++- lib/apartment/adapters/abstract_adapter.rb | 16 +++-- .../adapters/abstract_jdbc_adapter.rb | 2 +- .../adapters/jdbc_postgresql_adapter.rb | 5 +- lib/apartment/adapters/postgresql_adapter.rb | 3 + lib/tasks/apartment.rake | 2 +- spec/adapters/postgresql_adapter_spec.rb | 5 +- spec/adapters/sqlite3_adapter_spec.rb | 26 +++++-- spec/dummy/config/boot.rb | 2 +- spec/examples/schema_adapter_examples.rb | 12 +++- .../apartment_rake_integration_spec.rb | 2 +- spec/support/apartment_helpers.rb | 4 +- spec/support/requirements.rb | 16 ++++- spec/tenant_spec.rb | 8 ++- 15 files changed, 86 insertions(+), 98 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index f0c67aff..de6dcb74 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -621,81 +621,9 @@ Style/Proc: - 'spec/unit/elevators/host_spec.rb' - 'spec/unit/elevators/subdomain_spec.rb' -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: compact, exploded -Style/RaiseArgs: - Exclude: - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/RandomWithOffset: - Exclude: - - 'spec/integration/apartment_rake_integration_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/RedundantBegin: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, AllowInnerSlashes. -# SupportedStyles: slashes, percent_r, mixed -Style/RegexpLiteral: - Exclude: - - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'spec/examples/schema_adapter_examples.rb' - -# Offense count: 9 -# Cop supports --auto-correct. -Style/RescueModifier: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'spec/adapters/sqlite3_adapter_spec.rb' - - 'spec/examples/schema_adapter_examples.rb' - - 'spec/support/apartment_helpers.rb' - - 'spec/support/requirements.rb' - - 'spec/tenant_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowAsExpressionSeparator. -Style/Semicolon: - Exclude: - - 'spec/adapters/postgresql_adapter_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: use_perl_names, use_english_names -Style/SpecialGlobalVars: - Exclude: - - 'spec/dummy/config/boot.rb' - # Offense count: 518 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. # SupportedStyles: single_quotes, double_quotes Style/StringLiterals: Enabled: false - -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: MinSize. -# SupportedStyles: percent, brackets -Style/SymbolArray: - EnforcedStyle: brackets - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: IgnoredMethods. -# IgnoredMethods: respond_to, define_method -Style/SymbolProc: - Exclude: - - 'lib/tasks/apartment.rake' diff --git a/lib/apartment.rb b/lib/apartment.rb index 594dc1bd..e3a6b0cf 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -10,8 +10,13 @@ class << self extend Forwardable - ACCESSOR_METHODS = [:use_schemas, :use_sql, :seed_after_create, :prepend_environment, :append_environment, :with_multi_server_setup] - WRITER_METHODS = [:tenant_names, :database_schema_file, :excluded_models, :default_schema, :persistent_schemas, :connection_class, :tld_length, :db_migrate_tenants, :seed_data_file, :parallel_migration_threads, :pg_excluded_names] + ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment + append_environment with_multi_server_setup] + + WRITER_METHODS = %i[tenant_names database_schema_file excluded_models + default_schema persistent_schemas connection_class + tld_length db_migrate_tenants seed_data_file + parallel_migration_threads pg_excluded_names] attr_accessor(*ACCESSOR_METHODS) attr_writer(*WRITER_METHODS) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 4ad8f870..ffac0c43 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -1,5 +1,6 @@ module Apartment module Adapters + # rubocop:disable Metrics/ClassLength class AbstractAdapter include ActiveSupport::Callbacks define_callbacks :create, :switch @@ -79,13 +80,15 @@ def switch!(tenant = nil) # @param {String?} tenant to connect to # def switch(tenant = nil) - begin - previous_tenant = current - switch!(tenant) - yield + previous_tenant = current + switch!(tenant) + yield - ensure - switch!(previous_tenant) rescue reset + ensure + begin + switch!(previous_tenant) + rescue StandardError => _e + reset end end @@ -265,5 +268,6 @@ def raise_connect_error!(tenant, exception) class SeparateDbConnectionHandler < ::ActiveRecord::Base end end + # rubocop:enable Metrics/ClassLength end end diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index be72414e..2d20af95 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -7,7 +7,7 @@ class AbstractJDBCAdapter < AbstractAdapter private def multi_tenantify_with_tenant_db_name(config, tenant) - config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}" + config[:url] = "#{config[:url].gsub(%r{(\S+)\/.+$}, '\1')}/#{environmentify(tenant)}" end def rescue_from diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 6b0f18cb..44726d2d 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -18,7 +18,7 @@ class JDBCPostgresqlAdapter < PostgresqlAdapter private def multi_tenantify_with_tenant_db_name(config, tenant) - config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}" + config[:url] = "#{config[:url].gsub(%r{(\S+)\/.+$}, '\1')}/#{environmentify(tenant)}" end def create_tenant_command(conn, tenant) @@ -37,8 +37,11 @@ class JDBCPostgresqlSchemaAdapter < PostgresqlSchemaAdapter # def connect_to_new(tenant = nil) return reset if tenant.nil? + # rubocop:disable Style/RaiseArgs raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.all_schemas.include? tenant.to_s + # rubocop:enable Style/RaiseArgs + @current = tenant.to_s Apartment.connection.schema_search_path = full_search_path diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 070415a0..c0606509 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -63,8 +63,11 @@ def drop_command(conn, tenant) # def connect_to_new(tenant = nil) return reset if tenant.nil? + # rubocop:disable Style/RaiseArgs raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.schema_exists?(tenant.to_s) + # rubocop:enable Style/RaiseArgs + @current = tenant.to_s Apartment.connection.schema_search_path = full_search_path diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index bccd9dd2..17032d33 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -126,7 +126,7 @@ apartment_namespace = namespace :apartment do end def tenants - ENV['DB'] ? ENV['DB'].split(',').map { |s| s.strip } : Apartment.tenant_names || [] + ENV['DB'] ? ENV['DB'].split(',').map(&:strip) : Apartment.tenant_names || [] end def warn_if_tenants_empty diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 16a85eca..9d5267a3 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -23,7 +23,10 @@ def tenant_names context "using schemas with SQL dump" do - before { Apartment.use_schemas = true; Apartment.use_sql = true } + before do + Apartment.use_schemas = true + Apartment.use_sql = true + end # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names diff --git a/spec/adapters/sqlite3_adapter_spec.rb b/spec/adapters/sqlite3_adapter_spec.rb index f6efa035..92246249 100644 --- a/spec/adapters/sqlite3_adapter_spec.rb +++ b/spec/adapters/sqlite3_adapter_spec.rb @@ -35,7 +35,13 @@ def tenant_names end end - after { subject.drop db_name rescue nil } + after do + begin + subject.drop db_name + rescue StandardError => _e + nil + end + end it "should create a new database" do subject.create db_name @@ -50,7 +56,13 @@ def tenant_names Apartment.configure { |config| config.prepend_environment = config.append_environment = false } end - after { subject.drop db_name rescue nil } + after do + begin + subject.drop db_name + rescue StandardError => _e + nil + end + end it "should create a new database" do subject.create db_name @@ -68,7 +80,13 @@ def tenant_names end end - after { subject.drop db_name rescue nil } + after do + begin + subject.drop db_name + rescue StandardError => _e + nil + end + end it "should create a new database" do subject.create db_name @@ -76,8 +94,6 @@ def tenant_names expect(File.exists?("#{default_dir}/#{db_name}_#{Rails.env}.sqlite3")).to eq true end end - end - end end diff --git a/spec/dummy/config/boot.rb b/spec/dummy/config/boot.rb index 490d7917..58dd2d36 100644 --- a/spec/dummy/config/boot.rb +++ b/spec/dummy/config/boot.rb @@ -8,4 +8,4 @@ Bundler.setup end -$:.unshift File.expand_path('../../../../lib', __FILE__) \ No newline at end of file +$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__) diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 606033b9..e70df5d8 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -1,5 +1,6 @@ require 'spec_helper' +# rubocop:disable Metrics/BlockLength shared_examples_for "a schema based apartment adapter" do include Apartment::Spec::AdapterRequirements @@ -40,7 +41,7 @@ it 'sets the search_path correctly' do Apartment::Tenant.init - expect(User.connection.schema_search_path).to match(%r|#{default_schema}|) + expect(User.connection.schema_search_path).to match(/|#{default_schema}|/) end end @@ -110,7 +111,13 @@ expect(tenant_names).not_to include(db.to_s) end - after { subject.drop(db) rescue nil } + after do + begin + subject.drop(db) + rescue StandardError => _e + nil + end + end end end @@ -232,3 +239,4 @@ end end end +# rubocop:enable Metrics/BlockLength diff --git a/spec/integration/apartment_rake_integration_spec.rb b/spec/integration/apartment_rake_integration_spec.rb index c8e822cf..d4da2d0a 100644 --- a/spec/integration/apartment_rake_integration_spec.rb +++ b/spec/integration/apartment_rake_integration_spec.rb @@ -31,7 +31,7 @@ after { Rake.application = nil } context "with x number of databases" do - let(:x) { 1 + rand(5) } # random number of dbs to create + let(:x) { rand(1..5) } # random number of dbs to create let(:db_names) { x.times.map { Apartment::Test.next_db } } let!(:company_count) { db_names.length } diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 9c4a43bf..47909943 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -16,7 +16,9 @@ def next_db end def drop_schema(schema) - ActiveRecord::Base.connection.execute("DROP SCHEMA IF EXISTS #{schema} CASCADE") rescue true + ActiveRecord::Base.connection.execute("DROP SCHEMA IF EXISTS #{schema} CASCADE") + rescue StandardError => _e + true end # Use this if you don't want to import schema.rb etc... but need the postgres schema to exist diff --git a/spec/support/requirements.rb b/spec/support/requirements.rb index dc856c9e..f507ab26 100644 --- a/spec/support/requirements.rb +++ b/spec/support/requirements.rb @@ -19,9 +19,19 @@ module AdapterRequirements # Reset before dropping (can't drop a db you're connected to) subject.reset - # sometimes we manually drop these schemas in testing, don't care if we can't drop, hence rescue - subject.drop(db1) rescue true - subject.drop(db2) rescue true + # sometimes we manually drop these schemas in testing, don't care if + # we can't drop, hence rescue + begin + subject.drop(db1) + rescue StandardError => _e + true + end + + begin + subject.drop(db2) + rescue StandardError => _e + true + end end end diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index 17dfe801..92cdc2a2 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -42,7 +42,13 @@ subject.reload!(config) end - after { subject.drop "db_with_prefix" rescue nil } + after do + begin + subject.drop "db_with_prefix" + rescue StandardError => _e + nil + end + end it "should create a new database" do subject.create "db_with_prefix" From f6ec07527bc3e9d47ceef66dd51e32655438cd86 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:44:07 +0800 Subject: [PATCH 020/282] WIP - fixed a couple more of rubocops --- .rubocop.yml | 4 ++ .rubocop_todo.yml | 45 ------------------- README.md | 2 +- .../adapters/jdbc_postgresql_adapter.rb | 6 ++- lib/apartment/adapters/mysql2_adapter.rb | 6 ++- lib/apartment/adapters/postgresql_adapter.rb | 12 +++-- lib/apartment/console.rb | 2 +- lib/apartment/elevators/host_hash.rb | 2 +- spec/support/apartment_helpers.rb | 2 + spec/unit/elevators/domain_spec.rb | 2 +- spec/unit/elevators/generic_spec.rb | 12 ++--- spec/unit/elevators/host_hash_spec.rb | 2 +- spec/unit/elevators/host_spec.rb | 2 +- spec/unit/elevators/subdomain_spec.rb | 2 +- 14 files changed, 36 insertions(+), 65 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 50fd0197..e98d38eb 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -7,3 +7,7 @@ inherit_gem: Style/WordArray: Exclude: - spec/schemas/**/*.rb + +Style/NumericLiterals: + Exclude: + - spec/schemas/**/*.rb diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index de6dcb74..1b12cea7 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -541,14 +541,6 @@ Style/MixinUsage: Exclude: - '.pryrc' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, Autocorrect. -# SupportedStyles: module_function, extend_self -Style/ModuleFunction: - Exclude: - - 'spec/support/apartment_helpers.rb' - # Offense count: 5 # Cop supports --auto-correct. Style/MultilineIfModifier: @@ -557,12 +549,6 @@ Style/MultilineIfModifier: - 'lib/apartment/elevators/host_hash.rb' - 'spec/support/requirements.rb' -# Offense count: 2 -Style/MultilineTernaryOperator: - Exclude: - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - # Offense count: 7 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. @@ -575,18 +561,6 @@ Style/MutableConstant: - 'lib/apartment/version.rb' - 'spec/dummy_engine/lib/dummy_engine/version.rb' -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: Strict. -Style/NumericLiterals: - MinDigits: 15 - -# Offense count: 2 -# Cop supports --auto-correct. -Style/ParallelAssignment: - Exclude: - - 'lib/apartment/adapters/postgresql_adapter.rb' - # Offense count: 29 # Cop supports --auto-correct. # Configuration parameters: PreferredDelimiters. @@ -602,25 +576,6 @@ Style/PercentLiteralDelimiters: - 'spec/unit/elevators/host_spec.rb' - 'spec/unit/elevators/subdomain_spec.rb' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: short, verbose -Style/PreferredHashMethods: - Exclude: - - 'lib/apartment/elevators/host_hash.rb' - -# Offense count: 13 -# Cop supports --auto-correct. -Style/Proc: - Exclude: - - 'lib/apartment/console.rb' - - 'spec/unit/elevators/domain_spec.rb' - - 'spec/unit/elevators/generic_spec.rb' - - 'spec/unit/elevators/host_hash_spec.rb' - - 'spec/unit/elevators/host_spec.rb' - - 'spec/unit/elevators/subdomain_spec.rb' - # Offense count: 518 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. diff --git a/README.md b/README.md index cb6c82b9..31e8ca13 100644 --- a/README.md +++ b/README.md @@ -229,7 +229,7 @@ A Generic Elevator exists that allows you to pass a `Proc` (or anything that res module MyApplication class Application < Rails::Application # Obviously not a contrived example - config.middleware.use Apartment::Elevators::Generic, Proc.new { |request| request.host.reverse } + config.middleware.use Apartment::Elevators::Generic, proc { |request| request.host.reverse } end end ``` diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 44726d2d..3574feb8 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -4,9 +4,11 @@ module Apartment module Tenant def self.jdbc_postgresql_adapter(config) - Apartment.use_schemas ? - Adapters::JDBCPostgresqlSchemaAdapter.new(config) : + if Apartment.use_schemas + Adapters::JDBCPostgresqlSchemaAdapter.new(config) + else Adapters::JDBCPostgresqlAdapter.new(config) + end end end diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index 780710d3..c3c05e9d 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -4,9 +4,11 @@ module Apartment module Tenant def self.mysql2_adapter(config) - Apartment.use_schemas ? - Adapters::Mysql2SchemaAdapter.new(config) : + if Apartment.use_schemas + Adapters::Mysql2SchemaAdapter.new(config) + else Adapters::Mysql2Adapter.new(config) + end end end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index c0606509..fc6b60b7 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -74,7 +74,7 @@ def connect_to_new(tenant = nil) # When the PostgreSQL version is < 9.3, # there is a issue for prepared statement with changing search_path. # https://www.postgresql.org/docs/9.3/static/sql-prepare.html - if postgresql_version < 90300 + if postgresql_version < 90_300 Apartment.connection.clear_cache! end @@ -179,7 +179,10 @@ def pg_dump_schema_migrations_data # Temporary set Postgresql related environment variables if there are in @config # def with_pg_env(&block) - pghost, pgport, pguser, pgpassword = ENV['PGHOST'], ENV['PGPORT'], ENV['PGUSER'], ENV['PGPASSWORD'] + pghost = ENV['PGHOST'] + pgport = ENV['PGPORT'] + pguser = ENV['PGUSER'] + pgpassword = ENV['PGPASSWORD'] ENV['PGHOST'] = @config[:host] if @config[:host] ENV['PGPORT'] = @config[:port].to_s if @config[:port] @@ -188,7 +191,10 @@ def with_pg_env(&block) block.call ensure - ENV['PGHOST'], ENV['PGPORT'], ENV['PGUSER'], ENV['PGPASSWORD'] = pghost, pgport, pguser, pgpassword + ENV['PGHOST'] = pghost + ENV['PGPORT'] = pgport + ENV['PGUSER'] = pguser + ENV['PGPASSWORD'] = pgpassword end # Remove "SET search_path ..." line from SQL dump and prepend search_path set to current tenant diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 66cefda2..8393be85 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -5,7 +5,7 @@ def reload!(print=true) puts "Reloading..." if print # This triggers the to_prepare callbacks - ActionDispatch::Callbacks.new(Proc.new{}).call({}) + ActionDispatch::Callbacks.new(proc{}).call({}) # Manually init Apartment again once classes are reloaded Apartment::Tenant.init true diff --git a/lib/apartment/elevators/host_hash.rb b/lib/apartment/elevators/host_hash.rb index 7a0454f1..e3e0e0c1 100644 --- a/lib/apartment/elevators/host_hash.rb +++ b/lib/apartment/elevators/host_hash.rb @@ -13,7 +13,7 @@ def initialize(app, hash = {}, processor = nil) def parse_tenant_name(request) raise TenantNotFound, - "Cannot find tenant for host #{request.host}" unless @hash.has_key?(request.host) + "Cannot find tenant for host #{request.host}" unless @hash.key?(request.host) @hash[request.host] end diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 47909943..dafbd9d2 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -1,7 +1,9 @@ module Apartment module Test + # rubocop:disable Style/ModuleFunction extend self + # rubocop:enable Style/ModuleFunction def reset Apartment.excluded_models = nil diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index 713cd88c..14090c41 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Domain do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do it "parses the host for a domain name" do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index bca84dc9..f12f8fb4 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -9,11 +9,11 @@ def parse_tenant_name(*) end end - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc) } describe "#call" do it "calls the processor if given" do - elevator = described_class.new(Proc.new{}, Proc.new {'tenant1'}) + elevator = described_class.new(proc{}, proc {'tenant1'}) expect(Apartment::Tenant).to receive(:switch).with('tenant1') @@ -27,7 +27,7 @@ def parse_tenant_name(*) end it "switches to the parsed db_name" do - elevator = MyElevator.new(Proc.new{}) + elevator = MyElevator.new(proc{}) expect(Apartment::Tenant).to receive(:switch).with('tenant2') @@ -35,15 +35,15 @@ def parse_tenant_name(*) end it "calls the block implementation of `switch`" do - elevator = MyElevator.new(Proc.new{}, Proc.new {'tenant2'}) + elevator = MyElevator.new(proc{}, proc {'tenant2'}) expect(Apartment::Tenant).to receive(:switch).with('tenant2').and_yield elevator.call('HTTP_HOST' => 'foo.bar.com') end it "does not call `switch` if no database given" do - app = Proc.new{} - elevator = MyElevator.new(app, Proc.new{}) + app = proc{} + elevator = MyElevator.new(app, proc{}) expect(Apartment::Tenant).not_to receive(:switch) expect(app).to receive :call diff --git a/spec/unit/elevators/host_hash_spec.rb b/spec/unit/elevators/host_hash_spec.rb index 039912ec..af1aa5be 100644 --- a/spec/unit/elevators/host_hash_spec.rb +++ b/spec/unit/elevators/host_hash_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::HostHash do - subject(:elevator) { Apartment::Elevators::HostHash.new(Proc.new{}, 'example.com' => 'example_tenant') } + subject(:elevator) { Apartment::Elevators::HostHash.new(proc{}, 'example.com' => 'example_tenant') } describe "#parse_tenant_name" do it "parses the host for a domain name" do diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index c8daaa37..b77fbc49 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Host do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index 71feb6c7..ac4e74f3 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -3,7 +3,7 @@ describe Apartment::Elevators::Subdomain do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do context "assuming one tld" do From 8d127c5e691d8dc7dc21eca7c7d1bfd9374d784b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:47:29 +0800 Subject: [PATCH 021/282] WIP - --- .rubocop.yml | 4 +++ .rubocop_todo.yml | 44 ----------------------- Appraisals | 2 -- lib/apartment.rb | 1 + lib/apartment/adapters/sqlite3_adapter.rb | 6 ++-- lib/apartment/elevators/host.rb | 1 + lib/apartment/elevators/host_hash.rb | 2 +- lib/apartment/elevators/subdomain.rb | 8 ++--- 8 files changed, 14 insertions(+), 54 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index e98d38eb..e8cc53e7 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -11,3 +11,7 @@ Style/WordArray: Style/NumericLiterals: Exclude: - spec/schemas/**/*.rb + +Layout/EmptyLineAfterMagicComment: + Exclude: + - spec/schemas/**/*.rb diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 1b12cea7..0ad25d20 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,50 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: with_first_argument, with_fixed_indentation -Layout/ArgumentAlignment: - Exclude: - - 'lib/apartment/adapters/sqlite3_adapter.rb' - - 'lib/apartment/elevators/host_hash.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. -# SupportedStylesAlignWith: start_of_line, def -Layout/DefEndAlignment: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Layout/ElseAlignment: - Exclude: - - 'lib/apartment/elevators/subdomain.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/EmptyLineAfterGuardClause: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/elevators/host.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -Layout/EmptyLineAfterMagicComment: - Exclude: - - 'spec/schemas/v1.rb' - - 'spec/schemas/v2.rb' - - 'spec/schemas/v3.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/EmptyLines: - Exclude: - - 'Appraisals' - # Offense count: 54 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/Appraisals b/Appraisals index f6904095..160e0ada 100644 --- a/Appraisals +++ b/Appraisals @@ -44,7 +44,6 @@ appraise "rails-5-2" do end end - appraise "rails-6-0" do gem "rails", "~> 6.0.0.rc1" platforms :ruby do @@ -57,7 +56,6 @@ appraise "rails-6-0" do end end - appraise "rails-master" do gem "rails", git: 'https://github.com/rails/rails.git' platforms :ruby do diff --git a/lib/apartment.rb b/lib/apartment.rb index e3a6b0cf..eddaa242 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -94,6 +94,7 @@ def reset def extract_tenant_config return {} unless @tenant_names + values = @tenant_names.respond_to?(:call) ? @tenant_names.call : @tenant_names unless values.is_a? Hash values = values.each_with_object({}) do |tenant, hash| diff --git a/lib/apartment/adapters/sqlite3_adapter.rb b/lib/apartment/adapters/sqlite3_adapter.rb index e16dd544..f4e169a6 100644 --- a/lib/apartment/adapters/sqlite3_adapter.rb +++ b/lib/apartment/adapters/sqlite3_adapter.rb @@ -17,7 +17,7 @@ def initialize(config) def drop(tenant) raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) File.delete(database_file(tenant)) end @@ -30,14 +30,14 @@ def current def connect_to_new(tenant) raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) super database_file(tenant) end def create_tenant(tenant) raise TenantExists, - "The tenant #{environmentify(tenant)} already exists." if File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} already exists." if File.exists?(database_file(tenant)) begin f = File.new(database_file(tenant), File::CREAT) diff --git a/lib/apartment/elevators/host.rb b/lib/apartment/elevators/host.rb index c62d47e2..3a9f8da6 100644 --- a/lib/apartment/elevators/host.rb +++ b/lib/apartment/elevators/host.rb @@ -20,6 +20,7 @@ def self.ignored_first_subdomains def parse_tenant_name(request) return nil if request.host.blank? + parts = request.host.split('.') self.class.ignored_first_subdomains.include?(parts[0]) ? parts.drop(1).join('.') : request.host end diff --git a/lib/apartment/elevators/host_hash.rb b/lib/apartment/elevators/host_hash.rb index e3e0e0c1..7838d671 100644 --- a/lib/apartment/elevators/host_hash.rb +++ b/lib/apartment/elevators/host_hash.rb @@ -13,7 +13,7 @@ def initialize(app, hash = {}, processor = nil) def parse_tenant_name(request) raise TenantNotFound, - "Cannot find tenant for host #{request.host}" unless @hash.key?(request.host) + "Cannot find tenant for host #{request.host}" unless @hash.key?(request.host) @hash[request.host] end diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index 8380f758..5716a168 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -19,10 +19,10 @@ def parse_tenant_name(request) # If the domain acquired is set to be excluded, set the tenant to whatever is currently # next in line in the schema search path. tenant = if self.class.excluded_subdomains.include?(request_subdomain) - nil - else - request_subdomain - end + nil + else + request_subdomain + end tenant.presence end From a22737d59de2a2ccd8e8f67a91df323822e87600 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:50:22 +0800 Subject: [PATCH 022/282] WIP - removed extra blank lines --- .rubocop_todo.yml | 36 ------------------- lib/apartment.rb | 1 - lib/apartment/adapters/abstract_adapter.rb | 2 -- .../adapters/abstract_jdbc_adapter.rb | 1 - lib/apartment/adapters/jdbc_mysql_adapter.rb | 1 - .../adapters/jdbc_postgresql_adapter.rb | 3 -- lib/apartment/adapters/mysql2_adapter.rb | 2 -- lib/apartment/adapters/postgresql_adapter.rb | 5 --- lib/apartment/elevators/domain.rb | 1 - lib/apartment/elevators/first_subdomain.rb | 1 - lib/apartment/elevators/generic.rb | 1 - lib/apartment/railtie.rb | 1 - lib/apartment/reloader.rb | 1 - lib/apartment/tasks/enhancements.rb | 4 --- .../apartment/install/install_generator.rb | 1 - 15 files changed, 61 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0ad25d20..0ff1652b 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -26,42 +26,6 @@ Bundler/OrderedGems: Layout/EmptyLinesAroundBlockBody: Enabled: false -# Offense count: 18 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines, beginning_only, ending_only -Layout/EmptyLinesAroundClassBody: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' - - 'lib/apartment/adapters/jdbc_mysql_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/elevators/domain.rb' - - 'lib/apartment/elevators/first_subdomain.rb' - - 'lib/apartment/elevators/generic.rb' - - 'lib/apartment/railtie.rb' - - 'lib/apartment/reloader.rb' - - 'lib/apartment/tasks/enhancements.rb' - - 'lib/generators/apartment/install/install_generator.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundExceptionHandlingKeywords: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Layout/EmptyLinesAroundMethodBody: - Exclude: - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/tasks/enhancements.rb' - # Offense count: 15 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/lib/apartment.rb b/lib/apartment.rb index eddaa242..91839452 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -7,7 +7,6 @@ module Apartment class << self - extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ffac0c43..ff72bf06 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -56,7 +56,6 @@ def drop(tenant) with_neutral_connection(tenant) do |conn| drop_command(conn, tenant) end - rescue *rescuable_exceptions => exception raise_drop_tenant_error!(tenant, exception) end @@ -83,7 +82,6 @@ def switch(tenant = nil) previous_tenant = current switch!(tenant) yield - ensure begin switch!(previous_tenant) diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index 2d20af95..0f7da013 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -3,7 +3,6 @@ module Apartment module Adapters class AbstractJDBCAdapter < AbstractAdapter - private def multi_tenantify_with_tenant_db_name(config, tenant) diff --git a/lib/apartment/adapters/jdbc_mysql_adapter.rb b/lib/apartment/adapters/jdbc_mysql_adapter.rb index 53fc7dea..49d04c94 100644 --- a/lib/apartment/adapters/jdbc_mysql_adapter.rb +++ b/lib/apartment/adapters/jdbc_mysql_adapter.rb @@ -10,7 +10,6 @@ def self.jdbc_mysql_adapter(config) module Adapters class JDBCMysqlAdapter < AbstractJDBCAdapter - def reset_on_connection_exception? true end diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 3574feb8..378f4a14 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -16,7 +16,6 @@ module Adapters # Default adapter when not using Postgresql Schemas class JDBCPostgresqlAdapter < PostgresqlAdapter - private def multi_tenantify_with_tenant_db_name(config, tenant) @@ -34,7 +33,6 @@ def rescue_from # Separate Adapter for Postgresql when using schemas class JDBCPostgresqlSchemaAdapter < PostgresqlSchemaAdapter - # Set schema search path to new schema # def connect_to_new(tenant = nil) @@ -46,7 +44,6 @@ def connect_to_new(tenant = nil) @current = tenant.to_s Apartment.connection.schema_search_path = full_search_path - rescue ActiveRecord::StatementInvalid, ActiveRecord::JDBCError raise TenantNotFound, "One of the following schema(s) is invalid: #{full_search_path}" end diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index c3c05e9d..33365cab 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -14,7 +14,6 @@ def self.mysql2_adapter(config) module Adapters class Mysql2Adapter < AbstractAdapter - def initialize(config) super @@ -50,7 +49,6 @@ def connect_to_new(tenant) return reset if tenant.nil? Apartment.connection.execute "use `#{environmentify(tenant)}`" - rescue ActiveRecord::StatementInvalid => exception Apartment::Tenant.reset raise_connect_error!(tenant, exception) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index fc6b60b7..aefde151 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -14,7 +14,6 @@ def self.postgresql_adapter(config) module Adapters # Default adapter when not using Postgresql Schemas class PostgresqlAdapter < AbstractAdapter - private def rescue_from @@ -24,7 +23,6 @@ def rescue_from # Separate Adapter for Postgresql when using schemas class PostgresqlSchemaAdapter < AbstractAdapter - def initialize(config) super @@ -77,7 +75,6 @@ def connect_to_new(tenant = nil) if postgresql_version < 90_300 Apartment.connection.clear_cache! end - rescue *rescuable_exceptions raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}" end @@ -107,7 +104,6 @@ def postgresql_version # Another Adapter for Postgresql when using schemas and SQL class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter - PSQL_DUMP_BLACKLISTED_STATEMENTS= [ /SET search_path/i, # overridden later /SET lock_timeout/i, # new in postgresql 9.3 @@ -156,7 +152,6 @@ def copy_schema_migrations # @return {String} raw SQL contaning only postgres schema dump # def pg_dump_schema - # Skip excluded tables? :/ # excluded_tables = # collect_table_names(Apartment.excluded_models) diff --git a/lib/apartment/elevators/domain.rb b/lib/apartment/elevators/domain.rb index 5b81bb8a..f52f4b40 100644 --- a/lib/apartment/elevators/domain.rb +++ b/lib/apartment/elevators/domain.rb @@ -11,7 +11,6 @@ module Elevators # # class Domain < Generic - def parse_tenant_name(request) return nil if request.host.blank? diff --git a/lib/apartment/elevators/first_subdomain.rb b/lib/apartment/elevators/first_subdomain.rb index 71d0d8d1..052d28c9 100644 --- a/lib/apartment/elevators/first_subdomain.rb +++ b/lib/apartment/elevators/first_subdomain.rb @@ -8,7 +8,6 @@ module Elevators # - example1.domain.com => example1 # - example2.something.domain.com => example2 class FirstSubdomain < Subdomain - def parse_tenant_name(request) super.split('.')[0] unless super.nil? end diff --git a/lib/apartment/elevators/generic.rb b/lib/apartment/elevators/generic.rb index 21349378..716db5dc 100644 --- a/lib/apartment/elevators/generic.rb +++ b/lib/apartment/elevators/generic.rb @@ -6,7 +6,6 @@ module Elevators # Provides a rack based tenant switching solution based on request # class Generic - def initialize(app, processor = nil) @app = app @processor = processor || method(:parse_tenant_name) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 6a18833f..beba954c 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -4,7 +4,6 @@ module Apartment class Railtie < Rails::Railtie - # # Set up our default config options # Do this before the app initializers run so we don't override custom settings diff --git a/lib/apartment/reloader.rb b/lib/apartment/reloader.rb index fd315371..164c838e 100644 --- a/lib/apartment/reloader.rb +++ b/lib/apartment/reloader.rb @@ -1,6 +1,5 @@ module Apartment class Reloader - # Middleware used in development to init Apartment for each request # Necessary due to code reload (annoying). When models are reloaded, they no longer have the proper table_name # That is prepended with the schema (if using postgresql schemas) diff --git a/lib/apartment/tasks/enhancements.rb b/lib/apartment/tasks/enhancements.rb index ce93e58a..dff7099b 100644 --- a/lib/apartment/tasks/enhancements.rb +++ b/lib/apartment/tasks/enhancements.rb @@ -3,7 +3,6 @@ module Apartment class RakeTaskEnhancer - module TASKS ENHANCE_BEFORE = %w(db:drop) ENHANCE_AFTER = %w(db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed) @@ -28,7 +27,6 @@ def enhance! task = Rake::Task[name] enhance_after_task(task) end - end def should_enhance? @@ -48,9 +46,7 @@ def enhance_after_task(task) def inserted_task_name(task) task.name.sub(/db:/, 'apartment:') end - end - end end diff --git a/lib/generators/apartment/install/install_generator.rb b/lib/generators/apartment/install/install_generator.rb index eb7cbe66..079a732b 100755 --- a/lib/generators/apartment/install/install_generator.rb +++ b/lib/generators/apartment/install/install_generator.rb @@ -5,6 +5,5 @@ class InstallGenerator < Rails::Generators::Base def copy_files template "apartment.rb", File.join("config", "initializers", "apartment.rb") end - end end From 7f68591d41114192f93e877c928714c96f6152bb Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 16:51:52 +0800 Subject: [PATCH 023/282] WIP - fixed EmptyLinesAroundBlockBody --- .rubocop_todo.yml | 7 ------- lib/generators/apartment/install/templates/apartment.rb | 1 - lib/tasks/apartment.rake | 1 - spec/adapters/jdbc_mysql_adapter_spec.rb | 1 - spec/adapters/jdbc_postgresql_adapter_spec.rb | 4 ---- spec/adapters/postgresql_adapter_spec.rb | 3 --- spec/dummy_engine/config/initializers/apartment.rb | 1 - .../generic_adapter_custom_configuration_example.rb | 4 ---- spec/examples/generic_adapter_examples.rb | 1 - spec/examples/schema_adapter_examples.rb | 5 ----- spec/integration/use_within_an_engine_spec.rb | 2 -- spec/schemas/v1.rb | 1 - spec/schemas/v2.rb | 2 -- spec/schemas/v3.rb | 2 -- spec/spec_helper.rb | 1 - spec/support/setup.rb | 1 - spec/tasks/apartment_rake_spec.rb | 7 ------- spec/tenant_spec.rb | 4 ---- spec/unit/config_spec.rb | 3 --- spec/unit/elevators/domain_spec.rb | 1 - spec/unit/elevators/generic_spec.rb | 1 - spec/unit/elevators/host_hash_spec.rb | 1 - spec/unit/elevators/host_spec.rb | 2 -- spec/unit/elevators/subdomain_spec.rb | 1 - spec/unit/migrator_spec.rb | 1 - spec/unit/reloader_spec.rb | 2 -- 26 files changed, 60 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0ff1652b..cdd3a8ae 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,13 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 54 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, no_empty_lines -Layout/EmptyLinesAroundBlockBody: - Enabled: false - # Offense count: 15 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/lib/generators/apartment/install/templates/apartment.rb b/lib/generators/apartment/install/templates/apartment.rb index 6c7c52fb..251033bf 100644 --- a/lib/generators/apartment/install/templates/apartment.rb +++ b/lib/generators/apartment/install/templates/apartment.rb @@ -12,7 +12,6 @@ # Apartment Configuration # Apartment.configure do |config| - # Add any models that you do not want to be multi-tenanted, but remain in the global (public) namespace. # A typical example would be a Customer or Tenant model that stores each Tenant's information. # diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 17032d33..7931160f 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -2,7 +2,6 @@ require 'apartment/migrator' require 'parallel' apartment_namespace = namespace :apartment do - desc "Create all tenants" task :create do tenants.each do |tenant| diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 1fee3e14..1fb5d433 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -4,7 +4,6 @@ require 'apartment/adapters/jdbc_mysql_adapter' describe Apartment::Adapters::JDBCMysqlAdapter, database: :mysql do - subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index 28cf135f..d595a7d9 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -4,11 +4,9 @@ require 'apartment/adapters/jdbc_postgresql_adapter' describe Apartment::Adapters::JDBCPostgresqlAdapter, database: :postgresql do - subject { Apartment::Tenant.jdbc_postgresql_adapter config.symbolize_keys } context "using schemas" do - before { Apartment.use_schemas = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test @@ -23,7 +21,6 @@ def tenant_names end context "using databases" do - before { Apartment.use_schemas = false } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test @@ -35,7 +32,6 @@ def tenant_names it_should_behave_like "a generic apartment adapter" it_should_behave_like "a connection based apartment adapter" - end end end diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 9d5267a3..7802a7bd 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -7,7 +7,6 @@ subject { Apartment::Tenant.postgresql_adapter config } context "using schemas with schema.rb" do - before { Apartment.use_schemas = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test @@ -22,7 +21,6 @@ def tenant_names end context "using schemas with SQL dump" do - before do Apartment.use_schemas = true Apartment.use_sql = true @@ -46,7 +44,6 @@ def tenant_names end context "using connections" do - before { Apartment.use_schemas = false } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test diff --git a/spec/dummy_engine/config/initializers/apartment.rb b/spec/dummy_engine/config/initializers/apartment.rb index 611f5322..13d1d152 100644 --- a/spec/dummy_engine/config/initializers/apartment.rb +++ b/spec/dummy_engine/config/initializers/apartment.rb @@ -8,7 +8,6 @@ # Apartment Configuration # Apartment.configure do |config| - # These models will not be multi-tenanted, # but remain in the global (public) namespace # diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index a9f053a3..0f64c64a 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -1,7 +1,6 @@ require 'spec_helper' shared_examples_for "a generic apartment adapter able to handle custom configuration" do - let(:custom_tenant_name) { 'test_tenantwwww' } let(:db) { |example| example.metadata[:database]} let(:custom_tenant_names) do @@ -20,7 +19,6 @@ end context "database key taken from specific config" do - let(:expected_args) { get_custom_db_conf } describe "#create" do @@ -45,13 +43,11 @@ end context "database key from tenant name" do - let(:expected_args) { get_custom_db_conf.tap {|args| args.delete(:database) } } describe "#switch!" do - it "should connect to new db" do expect(Apartment).to receive(:establish_connection) do |args| db_name = args.delete(:database) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 1ba59291..ead10013 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -31,7 +31,6 @@ # Creates happen already in our before_filter # describe "#create" do - it "should create the new databases" do expect(tenant_names).to include(db1) expect(tenant_names).to include(db2) diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index e70df5d8..26ba4a73 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -9,7 +9,6 @@ let(:public_schema) { default_tenant } describe "#init" do - before do Apartment.configure do |config| config.excluded_models = ["Company"] @@ -31,7 +30,6 @@ end context "with a default_schema", :default_schema => true do - it "should set the proper table_name on excluded_models" do Apartment::Tenant.init @@ -57,7 +55,6 @@ # Creates happen already in our before_filter # describe "#create" do - it "should load schema.rb to new schema" do connection.schema_search_path = schema1 expect(connection.tables).to include('companies') @@ -90,7 +87,6 @@ after { subject.drop(db) } end - end describe "#drop" do @@ -212,7 +208,6 @@ end context "persistent_schemas", :persistent_schemas => true do - before { subject.switch!(schema1) } it "maintains the persistent schemas in the schema_search_path" do diff --git a/spec/integration/use_within_an_engine_spec.rb b/spec/integration/use_within_an_engine_spec.rb index 21873df1..0e4cfa16 100644 --- a/spec/integration/use_within_an_engine_spec.rb +++ b/spec/integration/use_within_an_engine_spec.rb @@ -1,5 +1,4 @@ describe 'using apartment within an engine' do - before do engine_path = Pathname.new(File.expand_path('../../dummy_engine', __FILE__)) require engine_path.join('test/dummy/config/application') @@ -24,5 +23,4 @@ Rake::Task['db:migrate'].invoke end end - end diff --git a/spec/schemas/v1.rb b/spec/schemas/v1.rb index b5e6a796..e5f626c9 100644 --- a/spec/schemas/v1.rb +++ b/spec/schemas/v1.rb @@ -12,5 +12,4 @@ # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 0) do - end diff --git a/spec/schemas/v2.rb b/spec/schemas/v2.rb index c6eeaba1..7ace165b 100644 --- a/spec/schemas/v2.rb +++ b/spec/schemas/v2.rb @@ -12,7 +12,6 @@ # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20110613152810) do - create_table "companies", :force => true do |t| t.boolean "dummy" t.string "database" @@ -39,5 +38,4 @@ t.datetime "birthdate" t.string "sex" end - end diff --git a/spec/schemas/v3.rb b/spec/schemas/v3.rb index 4dbc011d..7d97bdeb 100644 --- a/spec/schemas/v3.rb +++ b/spec/schemas/v3.rb @@ -12,7 +12,6 @@ # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20111202022214) do - create_table "books", :force => true do |t| t.string "name" t.integer "pages" @@ -45,5 +44,4 @@ t.datetime "birthdate" t.string "sex" end - end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 74aa9c8d..9fa79b79 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -36,7 +36,6 @@ Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f } RSpec.configure do |config| - config.include RSpec::Integration::CapybaraSessions, type: :request config.include Apartment::Spec::Setup diff --git a/spec/support/setup.rb b/spec/support/setup.rb index d4a68512..b7168e4b 100644 --- a/spec/support/setup.rb +++ b/spec/support/setup.rb @@ -12,7 +12,6 @@ def self.included(base) # any before/after hooks defined in individual tests # Otherwise these actually get run after test defined hooks around(:each) do |example| - def config db = RSpec.current_example.metadata.fetch(:database, :postgresql) diff --git a/spec/tasks/apartment_rake_spec.rb b/spec/tasks/apartment_rake_spec.rb index 0514676d..73f0eded 100644 --- a/spec/tasks/apartment_rake_spec.rb +++ b/spec/tasks/apartment_rake_spec.rb @@ -4,7 +4,6 @@ require 'apartment/tenant' describe "apartment rake tasks" do - before do @rake = Rake::Application.new Rake.application = @rake @@ -30,7 +29,6 @@ let(:version) { '1234' } context 'database migration' do - let(:tenant_names) { 3.times.map { Apartment::Test.next_db } } let(:tenant_count) { tenant_names.length } @@ -50,7 +48,6 @@ end describe "apartment:migrate:up" do - context "without a version" do before do ENV['VERSION'] = nil @@ -64,7 +61,6 @@ end context "with version" do - before do ENV['VERSION'] = version end @@ -77,7 +73,6 @@ end describe "apartment:migrate:down" do - context "without a version" do before do ENV['VERSION'] = nil @@ -91,7 +86,6 @@ end context "with version" do - before do ENV['VERSION'] = version end @@ -124,6 +118,5 @@ @rake['apartment:drop'].invoke end end - end end diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index 92cdc2a2..1fdfd88b 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -2,7 +2,6 @@ describe Apartment::Tenant do context "using mysql", database: :mysql do - before { subject.reload!(config) } describe "#adapter" do @@ -110,11 +109,9 @@ end describe "#switch!" do - let(:x) { rand(3) } context "creating models" do - before { subject.create db2 } after { subject.drop db2 } @@ -134,7 +131,6 @@ end context "with excluded models" do - before do Apartment.configure do |config| config.excluded_models = ["Company"] diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index eea2e2fe..010316ee 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -1,9 +1,7 @@ require 'spec_helper' describe Apartment do - describe "#config" do - let(:excluded_models) { ["Company"] } let(:seed_data_file_path) { "#{Rails.root}/db/seeds/import.rb" } @@ -107,6 +105,5 @@ def tenant_names_from_array(names) end end end - end end diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index 14090c41..5970e2d4 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -2,7 +2,6 @@ require 'apartment/elevators/domain' describe Apartment::Elevators::Domain do - subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index f12f8fb4..727779bf 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -2,7 +2,6 @@ require 'apartment/elevators/generic' describe Apartment::Elevators::Generic do - class MyElevator < described_class def parse_tenant_name(*) 'tenant2' diff --git a/spec/unit/elevators/host_hash_spec.rb b/spec/unit/elevators/host_hash_spec.rb index af1aa5be..b47850cd 100644 --- a/spec/unit/elevators/host_hash_spec.rb +++ b/spec/unit/elevators/host_hash_spec.rb @@ -2,7 +2,6 @@ require 'apartment/elevators/host_hash' describe Apartment::Elevators::HostHash do - subject(:elevator) { Apartment::Elevators::HostHash.new(proc{}, 'example.com' => 'example_tenant') } describe "#parse_tenant_name" do diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index b77fbc49..6338ef32 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -2,11 +2,9 @@ require 'apartment/elevators/host' describe Apartment::Elevators::Host do - subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do - it "should return nil when no host" do request = ActionDispatch::Request.new('HTTP_HOST' => '') expect(elevator.parse_tenant_name(request)).to be_nil diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index ac4e74f3..87cbc904 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -2,7 +2,6 @@ require 'apartment/elevators/subdomain' describe Apartment::Elevators::Subdomain do - subject(:elevator) { described_class.new(proc) } describe "#parse_tenant_name" do diff --git a/spec/unit/migrator_spec.rb b/spec/unit/migrator_spec.rb index 0022be74..dadc1834 100644 --- a/spec/unit/migrator_spec.rb +++ b/spec/unit/migrator_spec.rb @@ -2,7 +2,6 @@ require 'apartment/migrator' describe Apartment::Migrator do - let(:tenant) { Apartment::Test.next_db } # Don't need a real switch here, just testing behaviour diff --git a/spec/unit/reloader_spec.rb b/spec/unit/reloader_spec.rb index 5034f7dc..16a5f00e 100644 --- a/spec/unit/reloader_spec.rb +++ b/spec/unit/reloader_spec.rb @@ -1,9 +1,7 @@ require 'spec_helper' describe Apartment::Reloader do - context "using postgresql schemas" do - before do Apartment.configure do |config| config.excluded_models = ["Company"] From e7cd59be0a57136bec46f4be20f1272e1a77480e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:00:37 +0800 Subject: [PATCH 024/282] WIP - Fixed EmptyLinesAroundModuleBody --- .rubocop_todo.yml | 20 ------------------- lib/apartment.rb | 1 - lib/apartment/adapters/jdbc_mysql_adapter.rb | 1 - .../adapters/jdbc_postgresql_adapter.rb | 2 -- lib/apartment/adapters/mysql2_adapter.rb | 1 - lib/apartment/adapters/postgis_adapter.rb | 1 - lib/apartment/adapters/postgresql_adapter.rb | 1 - lib/apartment/deprecation.rb | 1 - lib/apartment/migrator.rb | 1 - lib/apartment/tenant.rb | 1 - spec/support/apartment_helpers.rb | 2 -- spec/support/config.rb | 1 - spec/support/requirements.rb | 1 - spec/support/setup.rb | 1 - 14 files changed, 35 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index cdd3a8ae..34bd62d9 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,26 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 15 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: empty_lines, empty_lines_except_namespace, empty_lines_special, no_empty_lines -Layout/EmptyLinesAroundModuleBody: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/jdbc_mysql_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - - 'lib/apartment/adapters/postgis_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/deprecation.rb' - - 'lib/apartment/migrator.rb' - - 'lib/apartment/tenant.rb' - - 'spec/support/apartment_helpers.rb' - - 'spec/support/config.rb' - - 'spec/support/requirements.rb' - - 'spec/support/setup.rb' - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. diff --git a/lib/apartment.rb b/lib/apartment.rb index 91839452..e61d93b2 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -5,7 +5,6 @@ require 'apartment/tenant' module Apartment - class << self extend Forwardable diff --git a/lib/apartment/adapters/jdbc_mysql_adapter.rb b/lib/apartment/adapters/jdbc_mysql_adapter.rb index 49d04c94..46943176 100644 --- a/lib/apartment/adapters/jdbc_mysql_adapter.rb +++ b/lib/apartment/adapters/jdbc_mysql_adapter.rb @@ -1,7 +1,6 @@ require "apartment/adapters/abstract_jdbc_adapter" module Apartment - module Tenant def self.jdbc_mysql_adapter(config) Adapters::JDBCMysqlAdapter.new config diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 378f4a14..5ae8c868 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -2,7 +2,6 @@ module Apartment module Tenant - def self.jdbc_postgresql_adapter(config) if Apartment.use_schemas Adapters::JDBCPostgresqlSchemaAdapter.new(config) @@ -13,7 +12,6 @@ def self.jdbc_postgresql_adapter(config) end module Adapters - # Default adapter when not using Postgresql Schemas class JDBCPostgresqlAdapter < PostgresqlAdapter private diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index 33365cab..30fb2c48 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -2,7 +2,6 @@ module Apartment module Tenant - def self.mysql2_adapter(config) if Apartment.use_schemas Adapters::Mysql2SchemaAdapter.new(config) diff --git a/lib/apartment/adapters/postgis_adapter.rb b/lib/apartment/adapters/postgis_adapter.rb index 4f5e9176..f9491476 100644 --- a/lib/apartment/adapters/postgis_adapter.rb +++ b/lib/apartment/adapters/postgis_adapter.rb @@ -4,7 +4,6 @@ module Apartment module Tenant - def self.postgis_adapter(config) postgresql_adapter(config) end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index aefde151..b57ccf0f 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -2,7 +2,6 @@ module Apartment module Tenant - def self.postgresql_adapter(config) adapter = Adapters::PostgresqlAdapter adapter = Adapters::PostgresqlSchemaAdapter if Apartment.use_schemas diff --git a/lib/apartment/deprecation.rb b/lib/apartment/deprecation.rb index 0b225847..3355f802 100644 --- a/lib/apartment/deprecation.rb +++ b/lib/apartment/deprecation.rb @@ -2,7 +2,6 @@ module Apartment module Deprecation - def self.warn(message) ActiveSupport::Deprecation.warn message end diff --git a/lib/apartment/migrator.rb b/lib/apartment/migrator.rb index c99e9a3b..54deea9b 100644 --- a/lib/apartment/migrator.rb +++ b/lib/apartment/migrator.rb @@ -2,7 +2,6 @@ module Apartment module Migrator - extend self # Migrate to latest diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 83e3cdd5..6e1e713b 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -4,7 +4,6 @@ module Apartment # The main entry point to Apartment functions # module Tenant - extend self extend Forwardable diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index dafbd9d2..1802d49b 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -1,6 +1,5 @@ module Apartment module Test - # rubocop:disable Style/ModuleFunction extend self # rubocop:enable Style/ModuleFunction @@ -42,6 +41,5 @@ def migrate def rollback ActiveRecord::Migrator.rollback(Rails.root + ActiveRecord::Migrator.migrations_path) end - end end diff --git a/spec/support/config.rb b/spec/support/config.rb index 999279e5..a19e8e5b 100644 --- a/spec/support/config.rb +++ b/spec/support/config.rb @@ -2,7 +2,6 @@ module Apartment module Test - def self.config @config ||= YAML.load(ERB.new(IO.read('spec/config/database.yml')).result) end diff --git a/spec/support/requirements.rb b/spec/support/requirements.rb index f507ab26..4481fca7 100644 --- a/spec/support/requirements.rb +++ b/spec/support/requirements.rb @@ -1,6 +1,5 @@ module Apartment module Spec - # # Define the interface methods required to # use an adapter shared example diff --git a/spec/support/setup.rb b/spec/support/setup.rb index b7168e4b..e9630dd8 100644 --- a/spec/support/setup.rb +++ b/spec/support/setup.rb @@ -1,7 +1,6 @@ module Apartment module Spec module Setup - def self.included(base) base.instance_eval do let(:db1) { Apartment::Test.next_db } From ea4602748726a58960f7bc67aa075982e825dd70 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:02:52 +0800 Subject: [PATCH 025/282] WIP - ran more auto correct --- .rubocop_todo.yml | 86 ------------------- lib/apartment/adapters/abstract_adapter.rb | 4 +- lib/apartment/adapters/postgresql_adapter.rb | 4 +- lib/apartment/console.rb | 2 +- lib/tasks/apartment.rake | 2 +- spec/dummy/config.ru | 2 +- spec/dummy/config/environments/test.rb | 2 +- spec/dummy/script/rails | 4 +- .../config/initializers/apartment.rb | 2 +- spec/dummy_engine/test/dummy/config.ru | 2 +- ...ic_adapter_custom_configuration_example.rb | 6 +- spec/examples/generic_adapter_examples.rb | 8 +- spec/examples/schema_adapter_examples.rb | 2 +- .../apartment_rake_integration_spec.rb | 2 +- spec/tasks/apartment_rake_spec.rb | 4 +- spec/unit/reloader_spec.rb | 2 +- 16 files changed, 24 insertions(+), 110 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 34bd62d9..0e7836ed 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,92 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. -# SupportedStylesAlignWith: keyword, variable, start_of_line -Layout/EndAlignment: - Exclude: - - 'lib/apartment/elevators/subdomain.rb' - -# Offense count: 15 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment, AllowBeforeTrailingComments, ForceEqualSignAlignment. -Layout/ExtraSpacing: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/tasks/apartment.rake' - - 'spec/dummy/config.ru' - - 'spec/dummy/config/environments/test.rb' - - 'spec/dummy/script/rails' - - 'spec/dummy_engine/test/dummy/config.ru' - - 'spec/examples/generic_adapter_examples.rb' - - 'spec/examples/schema_adapter_examples.rb' - - 'spec/integration/apartment_rake_integration_spec.rb' - - 'spec/tasks/apartment_rake_spec.rb' - - 'spec/unit/reloader_spec.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. -# SupportedHashRocketStyles: key, separator, table -# SupportedColonStyles: key, separator, table -# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit -Layout/HashAlignment: - Exclude: - - 'spec/examples/generic_adapter_custom_configuration_example.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: normal, indented_internal_methods -Layout/IndentationConsistency: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: Width, IgnoredPatterns. -Layout/IndentationWidth: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/abstract_jdbc_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/elevators/subdomain.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowDoxygenCommentStyle. -Layout/LeadingCommentSpace: - Exclude: - - 'spec/dummy_engine/config/initializers/apartment.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, IndentationWidth. -# SupportedStyles: aligned, indented, indented_relative_to_receiver -Layout/MultilineMethodCallIndentation: - Exclude: - - 'spec/examples/generic_adapter_examples.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceAroundEqualsInParameterDefault: - Exclude: - - 'lib/apartment/console.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment. -Layout/SpaceAroundOperators: - Exclude: - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'spec/dummy/config/environments/test.rb' - # Offense count: 82 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ff72bf06..ad084b0f 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -175,7 +175,7 @@ def connect_to_new(tenant) query_cache_enabled = ActiveRecord::Base.connection.query_cache_enabled Apartment.establish_connection multi_tenantify(tenant) - Apartment.connection.active? # call active? to manually check if this connection is valid + Apartment.connection.active? # call active? to manually check if this connection is valid Apartment.connection.enable_query_cache! if query_cache_enabled rescue *rescuable_exceptions => exception @@ -186,7 +186,7 @@ def connect_to_new(tenant) # Import the database schema # def import_database_schema - ActiveRecord::Schema.verbose = false # do not log schema load output. + ActiveRecord::Schema.verbose = false # do not log schema load output. load_or_raise(Apartment.database_schema_file) if Apartment.database_schema_file end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index b57ccf0f..c584e00c 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -103,7 +103,7 @@ def postgresql_version # Another Adapter for Postgresql when using schemas and SQL class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter - PSQL_DUMP_BLACKLISTED_STATEMENTS= [ + PSQL_DUMP_BLACKLISTED_STATEMENTS = [ /SET search_path/i, # overridden later /SET lock_timeout/i, # new in postgresql 9.3 /SET row_security/i, # new in postgresql 9.5 @@ -173,7 +173,7 @@ def pg_dump_schema_migrations_data # Temporary set Postgresql related environment variables if there are in @config # def with_pg_env(&block) - pghost = ENV['PGHOST'] + pghost = ENV['PGHOST'] pgport = ENV['PGPORT'] pguser = ENV['PGUSER'] pgpassword = ENV['PGPASSWORD'] diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 8393be85..390b6ad7 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -2,7 +2,7 @@ # This is unfortunate, but I haven't figured out how to hook into the reload process *after* files are reloaded # reloads the environment -def reload!(print=true) +def reload!(print = true) puts "Reloading..." if print # This triggers the to_prepare callbacks ActionDispatch::Callbacks.new(proc{}).call({}) diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 7931160f..ff736393 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -106,7 +106,7 @@ apartment_namespace = namespace :apartment do end end - desc 'Rolls back the tenant one migration and re migrate up (options: STEP=x, VERSION=x).' + desc 'Rolls back the tenant one migration and re migrate up (options: STEP=x, VERSION=x).' task :redo do if ENV['VERSION'] apartment_namespace['migrate:down'].invoke diff --git a/spec/dummy/config.ru b/spec/dummy/config.ru index 1989ed8d..cbd74159 100644 --- a/spec/dummy/config.ru +++ b/spec/dummy/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) run Dummy::Application diff --git a/spec/dummy/config/environments/test.rb b/spec/dummy/config/environments/test.rb index 30879efd..e3634079 100644 --- a/spec/dummy/config/environments/test.rb +++ b/spec/dummy/config/environments/test.rb @@ -17,7 +17,7 @@ config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment - config.action_controller.allow_forgery_protection = false + config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the diff --git a/spec/dummy/script/rails b/spec/dummy/script/rails index f8da2cff..bd79dce5 100755 --- a/spec/dummy/script/rails +++ b/spec/dummy/script/rails @@ -1,6 +1,6 @@ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. -APP_PATH = File.expand_path('../../config/application', __FILE__) -require File.expand_path('../../config/boot', __FILE__) +APP_PATH = File.expand_path('../../config/application', __FILE__) +require File.expand_path('../../config/boot', __FILE__) require 'rails/commands' diff --git a/spec/dummy_engine/config/initializers/apartment.rb b/spec/dummy_engine/config/initializers/apartment.rb index 13d1d152..b94a7f1f 100644 --- a/spec/dummy_engine/config/initializers/apartment.rb +++ b/spec/dummy_engine/config/initializers/apartment.rb @@ -22,7 +22,7 @@ config.use_schemas = true # use raw SQL dumps for creating postgres schemas? (only appies with use_schemas set to true) - #config.use_sql = true + # config.use_sql = true # configure persistent schemas (E.g. hstore ) # config.persistent_schemas = %w{ hstore } diff --git a/spec/dummy_engine/test/dummy/config.ru b/spec/dummy_engine/test/dummy/config.ru index 5bc2a619..bd83b254 100644 --- a/spec/dummy_engine/test/dummy/config.ru +++ b/spec/dummy_engine/test/dummy/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) run Rails.application diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index 0f64c64a..05328b32 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -68,18 +68,18 @@ def specific_connection { postgresql: { - adapter: 'postgresql', + adapter: 'postgresql', database: 'override_database', password: 'override_password', username: 'overridepostgres' }, mysql: { - adapter: 'mysql2', + adapter: 'mysql2', database: 'override_database', username: 'root' }, sqlite: { - adapter: 'sqlite3', + adapter: 'sqlite3', database: 'override_database' } } diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index ead10013..9366cbe5 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -18,9 +18,9 @@ Apartment::Railtie.config.to_prepare_blocks.map(&:call) num_available_connections = Apartment.connection_class.connection_pool - .instance_variable_get(:@available) - .instance_variable_get(:@queue) - .size + .instance_variable_get(:@available) + .instance_variable_get(:@queue) + .size expect(num_available_connections).to eq(1) end @@ -45,7 +45,7 @@ it "should yield to block if passed and reset" do subject.drop(db2) # so we don't get errors on creation - @count = 0 # set our variable so its visible in and outside of blocks + @count = 0 # set our variable so its visible in and outside of blocks subject.create(db2) do @count = User.count diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 26ba4a73..ddd82c1a 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -63,7 +63,7 @@ it "should yield to block if passed and reset" do subject.drop(schema2) # so we don't get errors on creation - @count = 0 # set our variable so its visible in and outside of blocks + @count = 0 # set our variable so its visible in and outside of blocks subject.create(schema2) do @count = User.count diff --git a/spec/integration/apartment_rake_integration_spec.rb b/spec/integration/apartment_rake_integration_spec.rb index d4da2d0a..dc819d4e 100644 --- a/spec/integration/apartment_rake_integration_spec.rb +++ b/spec/integration/apartment_rake_integration_spec.rb @@ -31,7 +31,7 @@ after { Rake.application = nil } context "with x number of databases" do - let(:x) { rand(1..5) } # random number of dbs to create + let(:x) { rand(1..5) } # random number of dbs to create let(:db_names) { x.times.map { Apartment::Test.next_db } } let!(:company_count) { db_names.length } diff --git a/spec/tasks/apartment_rake_spec.rb b/spec/tasks/apartment_rake_spec.rb index 73f0eded..2d799b32 100644 --- a/spec/tasks/apartment_rake_spec.rb +++ b/spec/tasks/apartment_rake_spec.rb @@ -19,7 +19,7 @@ after do Rake.application = nil - ENV['VERSION'] = nil # linux users reported env variable carrying on between tests + ENV['VERSION'] = nil # linux users reported env variable carrying on between tests end after(:all) do @@ -38,7 +38,7 @@ describe "apartment:migrate" do before do - allow(ActiveRecord::Migrator).to receive(:migrate) # don't care about this + allow(ActiveRecord::Migrator).to receive(:migrate) # don't care about this end it "should migrate public and all multi-tenant dbs" do diff --git a/spec/unit/reloader_spec.rb b/spec/unit/reloader_spec.rb index 16a5f00e..52b1d80e 100644 --- a/spec/unit/reloader_spec.rb +++ b/spec/unit/reloader_spec.rb @@ -8,7 +8,7 @@ config.use_schemas = true end Apartment::Tenant.reload!(config) - Company.reset_table_name # ensure we're clean + Company.reset_table_name # ensure we're clean end subject { Apartment::Reloader.new(double("Rack::Application", :call => nil)) } From 9495f7964d88d380b2fbd6d16ca8dba828b3f1df Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:05:29 +0800 Subject: [PATCH 026/282] WIP - fixed SpaceBeforeBlockBraces --- .rubocop_todo.yml | 8 -------- lib/apartment/console.rb | 2 +- spec/unit/elevators/generic_spec.rb | 10 +++++----- spec/unit/elevators/host_hash_spec.rb | 2 +- 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0e7836ed..d23854bc 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,14 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 82 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceBeforeBlockBraces: - EnforcedStyleForEmptyBraces: no_space - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: AllowForAlignment. diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 390b6ad7..b84648ed 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -5,7 +5,7 @@ def reload!(print = true) puts "Reloading..." if print # This triggers the to_prepare callbacks - ActionDispatch::Callbacks.new(proc{}).call({}) + ActionDispatch::Callbacks.new(proc {}).call({}) # Manually init Apartment again once classes are reloaded Apartment::Tenant.init true diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index 727779bf..72cd26f0 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -12,7 +12,7 @@ def parse_tenant_name(*) describe "#call" do it "calls the processor if given" do - elevator = described_class.new(proc{}, proc {'tenant1'}) + elevator = described_class.new(proc {}, proc {'tenant1'}) expect(Apartment::Tenant).to receive(:switch).with('tenant1') @@ -26,7 +26,7 @@ def parse_tenant_name(*) end it "switches to the parsed db_name" do - elevator = MyElevator.new(proc{}) + elevator = MyElevator.new(proc {}) expect(Apartment::Tenant).to receive(:switch).with('tenant2') @@ -34,15 +34,15 @@ def parse_tenant_name(*) end it "calls the block implementation of `switch`" do - elevator = MyElevator.new(proc{}, proc {'tenant2'}) + elevator = MyElevator.new(proc {}, proc {'tenant2'}) expect(Apartment::Tenant).to receive(:switch).with('tenant2').and_yield elevator.call('HTTP_HOST' => 'foo.bar.com') end it "does not call `switch` if no database given" do - app = proc{} - elevator = MyElevator.new(app, proc{}) + app = proc {} + elevator = MyElevator.new(app, proc {}) expect(Apartment::Tenant).not_to receive(:switch) expect(app).to receive :call diff --git a/spec/unit/elevators/host_hash_spec.rb b/spec/unit/elevators/host_hash_spec.rb index b47850cd..8a8dc344 100644 --- a/spec/unit/elevators/host_hash_spec.rb +++ b/spec/unit/elevators/host_hash_spec.rb @@ -2,7 +2,7 @@ require 'apartment/elevators/host_hash' describe Apartment::Elevators::HostHash do - subject(:elevator) { Apartment::Elevators::HostHash.new(proc{}, 'example.com' => 'example_tenant') } + subject(:elevator) { Apartment::Elevators::HostHash.new(proc {}, 'example.com' => 'example_tenant') } describe "#parse_tenant_name" do it "parses the host for a domain name" do From 127883b16f23365f8ffaa517507b199cd22157f1 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:06:39 +0800 Subject: [PATCH 027/282] WIP - fixed spacing related issues --- .rubocop_todo.yml | 66 ------------------- lib/apartment.rb | 2 +- lib/apartment/adapters/abstract_adapter.rb | 6 +- lib/apartment/adapters/postgresql_adapter.rb | 4 +- lib/apartment/elevators/domain.rb | 2 +- lib/apartment/elevators/first_subdomain.rb | 2 +- lib/apartment/migrator.rb | 2 +- .../app/controllers/application_controller.rb | 2 +- spec/dummy/app/models/company.rb | 2 +- spec/dummy/app/models/user.rb | 2 +- spec/dummy/config/environments/development.rb | 1 - spec/dummy/db/seeds/import.rb | 2 +- .../config/initializers/cookies_serializer.rb | 2 +- ...ic_adapter_custom_configuration_example.rb | 4 +- spec/support/capybara_sessions.rb | 6 +- spec/support/config.rb | 2 +- spec/support/contexts.rb | 4 +- spec/unit/elevators/first_subdomain_spec.rb | 4 +- spec/unit/elevators/generic_spec.rb | 4 +- spec/unit/reloader_spec.rb | 2 +- 20 files changed, 26 insertions(+), 95 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index d23854bc..89f43dfb 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,72 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment. -Layout/SpaceBeforeFirstArg: - Exclude: - - 'lib/tasks/apartment.rake' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: require_no_space, require_space -Layout/SpaceInLambdaLiteral: - Exclude: - - 'lib/apartment/migrator.rb' - -# Offense count: 14 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideBlockBraces: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'spec/dummy/db/seeds/import.rb' - - 'spec/examples/generic_adapter_custom_configuration_example.rb' - - 'spec/support/contexts.rb' - - 'spec/unit/elevators/generic_spec.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: space, no_space -Layout/SpaceInsideStringInterpolation: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: final_newline, final_blank_line -Layout/TrailingEmptyLines: - Exclude: - - 'lib/apartment/elevators/first_subdomain.rb' - - 'lib/apartment/elevators/host.rb' - - 'spec/dummy/app/models/company.rb' - - 'spec/dummy/app/models/user.rb' - - 'spec/dummy/config/boot.rb' - - 'spec/dummy/config/environments/development.rb' - - 'spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb' - - 'spec/support/capybara_sessions.rb' - - 'spec/support/config.rb' - - 'spec/support/contexts.rb' - - 'spec/unit/elevators/first_subdomain_spec.rb' - - 'spec/unit/reloader_spec.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: AllowInHeredoc. -Layout/TrailingWhitespace: - Exclude: - - 'lib/apartment/elevators/domain.rb' - - 'spec/dummy/app/controllers/application_controller.rb' - - 'spec/support/capybara_sessions.rb' - - 'spec/unit/elevators/first_subdomain_spec.rb' - # Offense count: 7 # Cop supports --auto-correct. Lint/DeprecatedClassMethods: diff --git a/lib/apartment.rb b/lib/apartment.rb index e61d93b2..b48d45fb 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -87,7 +87,7 @@ def pg_excluded_names # Reset all the config for Apartment def reset - (ACCESSOR_METHODS + WRITER_METHODS).each {|method| remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") } + (ACCESSOR_METHODS + WRITER_METHODS).each { |method| remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") } end def extract_tenant_config diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ad084b0f..f3c9feb2 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -252,15 +252,15 @@ def reset_on_connection_exception? end def raise_drop_tenant_error!(tenant, exception) - raise TenantNotFound, "Error while dropping tenant #{environmentify(tenant)}: #{ exception.message }" + raise TenantNotFound, "Error while dropping tenant #{environmentify(tenant)}: #{exception.message}" end def raise_create_tenant_error!(tenant, exception) - raise TenantExists, "Error while creating tenant #{environmentify(tenant)}: #{ exception.message }" + raise TenantExists, "Error while creating tenant #{environmentify(tenant)}: #{exception.message}" end def raise_connect_error!(tenant, exception) - raise TenantNotFound, "Error while connecting to tenant #{environmentify(tenant)}: #{ exception.message }" + raise TenantNotFound, "Error while connecting to tenant #{environmentify(tenant)}: #{exception.message}" end class SeparateDbConnectionHandler < ::ActiveRecord::Base diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index c584e00c..5c51f70f 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -200,7 +200,7 @@ def patch_search_path(sql) swap_schema_qualifier(sql) .split("\n") - .select {|line| check_input_against_regexps(line, PSQL_DUMP_BLACKLISTED_STATEMENTS).empty?} + .select { |line| check_input_against_regexps(line, PSQL_DUMP_BLACKLISTED_STATEMENTS).empty? } .prepend(search_path) .join("\n") end @@ -218,7 +218,7 @@ def swap_schema_qualifier(sql) # Checks if any of regexps matches against input # def check_input_against_regexps(input, regexps) - regexps.select {|c| input.match c} + regexps.select { |c| input.match c } end # Collect table names from AR Models diff --git a/lib/apartment/elevators/domain.rb b/lib/apartment/elevators/domain.rb index f52f4b40..9c6862ad 100644 --- a/lib/apartment/elevators/domain.rb +++ b/lib/apartment/elevators/domain.rb @@ -8,7 +8,7 @@ module Elevators # eg. example.com => example # www.example.bc.ca => example # a.example.bc.ca => a - # + # # class Domain < Generic def parse_tenant_name(request) diff --git a/lib/apartment/elevators/first_subdomain.rb b/lib/apartment/elevators/first_subdomain.rb index 052d28c9..e53fa4b9 100644 --- a/lib/apartment/elevators/first_subdomain.rb +++ b/lib/apartment/elevators/first_subdomain.rb @@ -13,4 +13,4 @@ def parse_tenant_name(request) end end end -end \ No newline at end of file +end diff --git a/lib/apartment/migrator.rb b/lib/apartment/migrator.rb index 54deea9b..27f6714c 100644 --- a/lib/apartment/migrator.rb +++ b/lib/apartment/migrator.rb @@ -9,7 +9,7 @@ def migrate(database) Tenant.switch(database) do version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil - migration_scope_block = -> (migration) { ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) } + migration_scope_block = ->(migration) { ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) } if activerecord_below_5_2? ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, version, &migration_scope_block) diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb index 4c655b70..9ec13342 100644 --- a/spec/dummy/app/controllers/application_controller.rb +++ b/spec/dummy/app/controllers/application_controller.rb @@ -1,6 +1,6 @@ class ApplicationController < ActionController::Base protect_from_forgery - + def index end end diff --git a/spec/dummy/app/models/company.rb b/spec/dummy/app/models/company.rb index dd5bf8c7..f97ca639 100644 --- a/spec/dummy/app/models/company.rb +++ b/spec/dummy/app/models/company.rb @@ -1,3 +1,3 @@ class Company < ActiveRecord::Base # Dummy models -end \ No newline at end of file +end diff --git a/spec/dummy/app/models/user.rb b/spec/dummy/app/models/user.rb index 145f27f9..61e0ee5f 100644 --- a/spec/dummy/app/models/user.rb +++ b/spec/dummy/app/models/user.rb @@ -1,3 +1,3 @@ class User < ActiveRecord::Base # Dummy models -end \ No newline at end of file +end diff --git a/spec/dummy/config/environments/development.rb b/spec/dummy/config/environments/development.rb index c143a826..229d545c 100644 --- a/spec/dummy/config/environments/development.rb +++ b/spec/dummy/config/environments/development.rb @@ -25,4 +25,3 @@ # Only use best-standards-support built into browsers config.action_dispatch.best_standards_support = :builtin end - diff --git a/spec/dummy/db/seeds/import.rb b/spec/dummy/db/seeds/import.rb index 8265d6be..4e2eb81b 100644 --- a/spec/dummy/db/seeds/import.rb +++ b/spec/dummy/db/seeds/import.rb @@ -1,5 +1,5 @@ def create_users - 6.times {|x| User.where(name: "Different User #{x}").first_or_create! } + 6.times { |x| User.where(name: "Different User #{x}").first_or_create! } end create_users diff --git a/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb b/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb index 7a06a89f..7f70458d 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb @@ -1,3 +1,3 @@ # Be sure to restart your server when you modify this file. -Rails.application.config.action_dispatch.cookies_serializer = :json \ No newline at end of file +Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index 05328b32..27ca1c84 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -2,7 +2,7 @@ shared_examples_for "a generic apartment adapter able to handle custom configuration" do let(:custom_tenant_name) { 'test_tenantwwww' } - let(:db) { |example| example.metadata[:database]} + let(:db) { |example| example.metadata[:database] } let(:custom_tenant_names) do { custom_tenant_name => get_custom_db_conf @@ -44,7 +44,7 @@ context "database key from tenant name" do let(:expected_args) { - get_custom_db_conf.tap {|args| args.delete(:database) } + get_custom_db_conf.tap { |args| args.delete(:database) } } describe "#switch!" do diff --git a/spec/support/capybara_sessions.rb b/spec/support/capybara_sessions.rb index 727d6c07..f9aef29a 100644 --- a/spec/support/capybara_sessions.rb +++ b/spec/support/capybara_sessions.rb @@ -1,15 +1,13 @@ module RSpec module Integration module CapybaraSessions - def in_new_session(&block) yield new_session end - + def new_session Capybara::Session.new(Capybara.current_driver, Capybara.app) end - end end -end \ No newline at end of file +end diff --git a/spec/support/config.rb b/spec/support/config.rb index a19e8e5b..2111641a 100644 --- a/spec/support/config.rb +++ b/spec/support/config.rb @@ -6,4 +6,4 @@ def self.config @config ||= YAML.load(ERB.new(IO.read('spec/config/database.yml')).result) end end -end \ No newline at end of file +end diff --git a/spec/support/contexts.rb b/spec/support/contexts.rb index 844f4e0a..2e95ffe4 100644 --- a/spec/support/contexts.rb +++ b/spec/support/contexts.rb @@ -41,12 +41,12 @@ let(:persistent_schemas) { %w[hstore postgis] } before do - persistent_schemas.map {|schema| subject.create(schema) } + persistent_schemas.map { |schema| subject.create(schema) } Apartment.persistent_schemas = persistent_schemas end after do Apartment.persistent_schemas = [] - persistent_schemas.map {|schema| subject.drop(schema) } + persistent_schemas.map { |schema| subject.drop(schema) } end end diff --git a/spec/unit/elevators/first_subdomain_spec.rb b/spec/unit/elevators/first_subdomain_spec.rb index 899b7bba..837cb3b3 100644 --- a/spec/unit/elevators/first_subdomain_spec.rb +++ b/spec/unit/elevators/first_subdomain_spec.rb @@ -15,10 +15,10 @@ let(:subdomain) { "test1.test2" } it { is_expected.to eq("test1") } end - + context "no subdomain" do let(:subdomain) { nil } it { is_expected.to eq(nil) } end end -end \ No newline at end of file +end diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index 72cd26f0..9bbe1ad0 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -12,7 +12,7 @@ def parse_tenant_name(*) describe "#call" do it "calls the processor if given" do - elevator = described_class.new(proc {}, proc {'tenant1'}) + elevator = described_class.new(proc {}, proc { 'tenant1' }) expect(Apartment::Tenant).to receive(:switch).with('tenant1') @@ -34,7 +34,7 @@ def parse_tenant_name(*) end it "calls the block implementation of `switch`" do - elevator = MyElevator.new(proc {}, proc {'tenant2'}) + elevator = MyElevator.new(proc {}, proc { 'tenant2' }) expect(Apartment::Tenant).to receive(:switch).with('tenant2').and_yield elevator.call('HTTP_HOST' => 'foo.bar.com') diff --git a/spec/unit/reloader_spec.rb b/spec/unit/reloader_spec.rb index 52b1d80e..312aa129 100644 --- a/spec/unit/reloader_spec.rb +++ b/spec/unit/reloader_spec.rb @@ -19,4 +19,4 @@ expect(Company.table_name).to include('public.') end end -end \ No newline at end of file +end From edf9d242a0776c5d1eb73edca9f4dd5d580e8f92 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:16:25 +0800 Subject: [PATCH 028/282] WIP - ran some more auto correct --- .pryrc | 2 + .rubocop_todo.yml | 123 ------------------ Appraisals | 34 ++--- gemfiles/rails_4_2.gemfile | 22 ++-- gemfiles/rails_5_0.gemfile | 20 +-- gemfiles/rails_5_1.gemfile | 20 +-- gemfiles/rails_5_2.gemfile | 18 +-- gemfiles/rails_6_0.gemfile | 20 +-- gemfiles/rails_master.gemfile | 20 +-- lib/apartment.rb | 6 +- lib/apartment/adapters/abstract_adapter.rb | 16 ++- .../adapters/abstract_jdbc_adapter.rb | 2 + lib/apartment/adapters/jdbc_mysql_adapter.rb | 4 +- .../adapters/jdbc_postgresql_adapter.rb | 4 +- lib/apartment/adapters/mysql2_adapter.rb | 6 +- lib/apartment/adapters/postgis_adapter.rb | 4 +- lib/apartment/adapters/postgresql_adapter.rb | 12 +- lib/apartment/adapters/sqlite3_adapter.rb | 8 +- lib/apartment/console.rb | 4 +- lib/apartment/deprecation.rb | 2 + lib/apartment/elevators/domain.rb | 4 +- lib/apartment/elevators/first_subdomain.rb | 2 + lib/apartment/elevators/generic.rb | 4 +- lib/apartment/elevators/host.rb | 2 + lib/apartment/elevators/host_hash.rb | 2 + lib/apartment/elevators/subdomain.rb | 2 + lib/apartment/migrator.rb | 6 +- lib/apartment/railtie.rb | 4 + lib/apartment/reloader.rb | 2 + lib/apartment/tasks/enhancements.rb | 6 +- lib/apartment/tenant.rb | 2 + lib/apartment/version.rb | 4 +- .../apartment/install/install_generator.rb | 4 +- .../apartment/install/templates/apartment.rb | 4 +- lib/tasks/apartment.rake | 14 +- spec/adapters/jdbc_mysql_adapter_spec.rb | 8 +- spec/adapters/jdbc_postgresql_adapter_spec.rb | 18 +-- spec/adapters/mysql2_adapter_spec.rb | 26 ++-- spec/adapters/postgresql_adapter_spec.rb | 28 ++-- spec/adapters/sqlite3_adapter_spec.rb | 36 ++--- spec/apartment_spec.rb | 6 +- .../app/controllers/application_controller.rb | 2 + spec/dummy/app/helpers/application_helper.rb | 2 + spec/dummy/app/models/company.rb | 4 +- spec/dummy/app/models/user.rb | 4 +- spec/dummy/config.ru | 2 + spec/dummy/config/application.rb | 18 +-- spec/dummy/config/boot.rb | 2 + spec/dummy/config/environment.rb | 2 + spec/dummy/config/environments/development.rb | 2 + spec/dummy/config/environments/production.rb | 4 +- spec/dummy/config/environments/test.rb | 2 + spec/dummy/config/initializers/apartment.rb | 6 +- .../initializers/backtrace_silencers.rb | 1 + spec/dummy/config/initializers/inflections.rb | 1 + spec/dummy/config/initializers/mime_types.rb | 1 + .../dummy/config/initializers/secret_token.rb | 2 + .../config/initializers/session_store.rb | 4 +- spec/dummy/config/routes.rb | 4 +- spec/dummy/db/seeds/import.rb | 2 + spec/dummy/script/rails | 2 + .../config/initializers/apartment.rb | 4 +- spec/dummy_engine/lib/dummy_engine.rb | 4 +- spec/dummy_engine/lib/dummy_engine/engine.rb | 2 + spec/dummy_engine/lib/dummy_engine/version.rb | 4 +- spec/dummy_engine/test/dummy/config.ru | 2 + .../test/dummy/config/application.rb | 4 +- spec/dummy_engine/test/dummy/config/boot.rb | 2 + .../test/dummy/config/environment.rb | 2 + .../dummy/config/environments/development.rb | 2 + .../dummy/config/environments/production.rb | 2 + .../test/dummy/config/environments/test.rb | 2 + .../test/dummy/config/initializers/assets.rb | 2 + .../initializers/backtrace_silencers.rb | 1 + .../config/initializers/cookies_serializer.rb | 2 + .../initializers/filter_parameter_logging.rb | 2 + .../dummy/config/initializers/inflections.rb | 1 + .../dummy/config/initializers/mime_types.rb | 1 + .../config/initializers/session_store.rb | 2 + .../config/initializers/wrap_parameters.rb | 2 + spec/dummy_engine/test/dummy/config/routes.rb | 2 + spec/examples/connection_adapter_examples.rb | 18 +-- ...ic_adapter_custom_configuration_example.rb | 28 ++-- spec/examples/generic_adapter_examples.rb | 50 +++---- spec/examples/schema_adapter_examples.rb | 122 ++++++++--------- .../apartment_rake_integration_spec.rb | 36 ++--- spec/integration/query_caching_spec.rb | 12 +- spec/integration/use_within_an_engine_spec.rb | 2 + spec/schemas/v1.rb | 4 +- spec/schemas/v2.rb | 44 +++---- spec/schemas/v3.rb | 52 ++++---- spec/spec_helper.rb | 11 +- spec/support/apartment_helpers.rb | 4 +- spec/support/capybara_sessions.rb | 2 + spec/support/config.rb | 2 + spec/support/contexts.rb | 8 +- spec/support/requirements.rb | 4 +- spec/support/setup.rb | 2 + spec/tasks/apartment_rake_spec.rb | 42 +++--- spec/tenant_spec.rb | 52 ++++---- spec/unit/config_spec.rb | 48 +++---- spec/unit/elevators/domain_spec.rb | 14 +- spec/unit/elevators/first_subdomain_spec.rb | 22 ++-- spec/unit/elevators/generic_spec.rb | 14 +- spec/unit/elevators/host_hash_spec.rb | 14 +- spec/unit/elevators/host_spec.rb | 48 +++---- spec/unit/elevators/subdomain_spec.rb | 44 ++++--- spec/unit/migrator_spec.rb | 2 + spec/unit/reloader_spec.rb | 10 +- 109 files changed, 718 insertions(+), 636 deletions(-) diff --git a/.pryrc b/.pryrc index 22e16cde..6d4a3df8 100644 --- a/.pryrc +++ b/.pryrc @@ -1,3 +1,5 @@ +# frozen_string_literal: true + if defined?(Rails) && Rails.env extend Rails::ConsoleMethods end diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 89f43dfb..f397e797 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -19,32 +19,6 @@ Bundler/OrderedGems: - 'gemfiles/rails_6_0.gemfile' - 'gemfiles/rails_master.gemfile' -# Offense count: 7 -# Cop supports --auto-correct. -Lint/DeprecatedClassMethods: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/sqlite3_adapter.rb' - - 'spec/adapters/sqlite3_adapter_spec.rb' - -# Offense count: 3 -Lint/ParenthesesAsGroupedExpression: - Exclude: - - 'spec/adapters/sqlite3_adapter_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Lint/RedundantStringCoercion: - Exclude: - - 'spec/examples/schema_adapter_examples.rb' - -# Offense count: 2 -# Configuration parameters: AllowComments. -Lint/SuppressedException: - Exclude: - - 'lib/apartment/railtie.rb' - - 'spec/spec_helper.rb' - # Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. @@ -81,26 +55,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 1 -Naming/AccessorMethodName: - Exclude: - - 'spec/examples/generic_adapter_custom_configuration_example.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: PreferredName. -Naming/RescuedExceptionsVariableName: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/mysql2_adapter.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Rails/ApplicationRecord: - Exclude: - - 'spec/dummy/app/models/company.rb' - - 'spec/dummy/app/models/user.rb' - # Offense count: 2 # Cop supports --auto-correct. # Configuration parameters: Whitelist. @@ -109,15 +63,6 @@ Rails/DynamicFindBy: Exclude: - 'spec/integration/query_caching_spec.rb' -# Offense count: 3 -# Configuration parameters: EnforcedStyle. -# SupportedStyles: slashes, arguments -Rails/FilePath: - Exclude: - - 'lib/apartment.rb' - - 'spec/tenant_spec.rb' - - 'spec/unit/config_spec.rb' - # Offense count: 1 # Configuration parameters: Include. # Include: app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb @@ -176,14 +121,6 @@ Style/EmptyMethod: Exclude: - 'spec/dummy/app/controllers/application_controller.rb' -# Offense count: 3 -# Cop supports --auto-correct. -Style/Encoding: - Exclude: - - 'spec/schemas/v1.rb' - - 'spec/schemas/v2.rb' - - 'spec/schemas/v3.rb' - # Offense count: 14 # Cop supports --auto-correct. Style/ExpandPathArguments: @@ -214,13 +151,6 @@ Style/FormatString: Style/FormatStringToken: EnforcedStyle: unannotated -# Offense count: 107 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: always, never -Style/FrozenStringLiteralComment: - Enabled: false - # Offense count: 2 # Configuration parameters: MinBodyLength. Style/GuardClause: @@ -228,25 +158,6 @@ Style/GuardClause: - 'lib/apartment/adapters/abstract_adapter.rb' - 'lib/tasks/apartment.rake' -# Offense count: 33 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. -# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys -Style/HashSyntax: - Exclude: - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'spec/dummy/config/initializers/session_store.rb' - - 'spec/dummy/config/routes.rb' - - 'spec/examples/schema_adapter_examples.rb' - - 'spec/integration/apartment_rake_integration_spec.rb' - - 'spec/schemas/v1.rb' - - 'spec/schemas/v2.rb' - - 'spec/schemas/v3.rb' - - 'spec/support/contexts.rb' - - 'spec/tenant_spec.rb' - - 'spec/unit/elevators/first_subdomain_spec.rb' - - 'spec/unit/reloader_spec.rb' - # Offense count: 6 # Cop supports --auto-correct. Style/IfUnlessModifier: @@ -257,18 +168,6 @@ Style/IfUnlessModifier: - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - 'lib/apartment/adapters/postgresql_adapter.rb' -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: line_count_dependent, lambda, literal -Style/Lambda: - Exclude: - - 'lib/generators/apartment/install/templates/apartment.rb' - - 'spec/dummy/config/initializers/apartment.rb' - - 'spec/integration/apartment_rake_integration_spec.rb' - - 'spec/integration/query_caching_spec.rb' - - 'spec/unit/config_spec.rb' - # Offense count: 1 Style/MixinUsage: Exclude: @@ -293,25 +192,3 @@ Style/MutableConstant: - 'lib/apartment/tasks/enhancements.rb' - 'lib/apartment/version.rb' - 'spec/dummy_engine/lib/dummy_engine/version.rb' - -# Offense count: 29 -# Cop supports --auto-correct. -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/tasks/enhancements.rb' - - 'spec/dummy/config/application.rb' - - 'spec/dummy_engine/config/initializers/apartment.rb' - - 'spec/examples/schema_adapter_examples.rb' - - 'spec/integration/apartment_rake_integration_spec.rb' - - 'spec/support/requirements.rb' - - 'spec/unit/elevators/host_spec.rb' - - 'spec/unit/elevators/subdomain_spec.rb' - -# Offense count: 518 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Enabled: false diff --git a/Appraisals b/Appraisals index 160e0ada..9a5ad27a 100644 --- a/Appraisals +++ b/Appraisals @@ -1,8 +1,10 @@ -appraise "rails-4-2" do - gem "rails", "~> 4.2.0" +# frozen_string_literal: true + +appraise 'rails-4-2' do + gem 'rails', '~> 4.2.0' platforms :ruby do - gem "pg", "< 1.0.0" - gem "mysql2", "~> 0.4.0" + gem 'pg', '< 1.0.0' + gem 'mysql2', '~> 0.4.0' end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 1.3' @@ -11,10 +13,10 @@ appraise "rails-4-2" do end end -appraise "rails-5-0" do - gem "rails", "~> 5.0.0" +appraise 'rails-5-0' do + gem 'rails', '~> 5.0.0' platforms :ruby do - gem "pg", "< 1.0.0" + gem 'pg', '< 1.0.0' end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 50.0' @@ -23,10 +25,10 @@ appraise "rails-5-0" do end end -appraise "rails-5-1" do - gem "rails", "~> 5.1.0" +appraise 'rails-5-1' do + gem 'rails', '~> 5.1.0' platforms :ruby do - gem "pg", "< 1.0.0" + gem 'pg', '< 1.0.0' end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 51.0' @@ -35,8 +37,8 @@ appraise "rails-5-1" do end end -appraise "rails-5-2" do - gem "rails", "~> 5.2.0" +appraise 'rails-5-2' do + gem 'rails', '~> 5.2.0' platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 52.0' gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' @@ -44,8 +46,8 @@ appraise "rails-5-2" do end end -appraise "rails-6-0" do - gem "rails", "~> 6.0.0.rc1" +appraise 'rails-6-0' do + gem 'rails', '~> 6.0.0.rc1' platforms :ruby do gem 'sqlite3', '~> 1.4' end @@ -56,8 +58,8 @@ appraise "rails-6-0" do end end -appraise "rails-master" do - gem "rails", git: 'https://github.com/rails/rails.git' +appraise 'rails-master' do + gem 'rails', git: 'https://github.com/rails/rails.git' platforms :ruby do gem 'sqlite3', '~> 1.4' end diff --git a/gemfiles/rails_4_2.gemfile b/gemfiles/rails_4_2.gemfile index ef31a500..acec9a0d 100644 --- a/gemfiles/rails_4_2.gemfile +++ b/gemfiles/rails_4_2.gemfile @@ -1,23 +1,25 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", "~> 4.2.0" +gem 'rails', '~> 4.2.0' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :ruby do - gem "pg", "< 1.0.0" - gem "mysql2", "~> 0.4.0" + gem 'pg', '< 1.0.0' + gem 'mysql2', '~> 0.4.0' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 1.3" - gem "activerecord-jdbcpostgresql-adapter", "~> 1.3" - gem "activerecord-jdbcmysql-adapter", "~> 1.3" + gem 'activerecord-jdbc-adapter', '~> 1.3' + gem 'activerecord-jdbcpostgresql-adapter', '~> 1.3' + gem 'activerecord-jdbcmysql-adapter', '~> 1.3' end -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails_5_0.gemfile b/gemfiles/rails_5_0.gemfile index 07d99a14..c1188bc2 100644 --- a/gemfiles/rails_5_0.gemfile +++ b/gemfiles/rails_5_0.gemfile @@ -1,22 +1,24 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", "~> 5.0.0" +gem 'rails', '~> 5.0.0' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :ruby do - gem "pg", "< 1.0.0" + gem 'pg', '< 1.0.0' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 50.0" - gem "activerecord-jdbcpostgresql-adapter", "~> 50.0" - gem "activerecord-jdbcmysql-adapter", "~> 50.0" + gem 'activerecord-jdbc-adapter', '~> 50.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 50.0' + gem 'activerecord-jdbcmysql-adapter', '~> 50.0' end -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails_5_1.gemfile b/gemfiles/rails_5_1.gemfile index 28353198..3e738bf1 100644 --- a/gemfiles/rails_5_1.gemfile +++ b/gemfiles/rails_5_1.gemfile @@ -1,22 +1,24 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", "~> 5.1.0" +gem 'rails', '~> 5.1.0' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :ruby do - gem "pg", "< 1.0.0" + gem 'pg', '< 1.0.0' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 51.0" - gem "activerecord-jdbcpostgresql-adapter", "~> 51.0" - gem "activerecord-jdbcmysql-adapter", "~> 51.0" + gem 'activerecord-jdbc-adapter', '~> 51.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 51.0' + gem 'activerecord-jdbcmysql-adapter', '~> 51.0' end -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails_5_2.gemfile b/gemfiles/rails_5_2.gemfile index 5a18c669..57d1aac4 100644 --- a/gemfiles/rails_5_2.gemfile +++ b/gemfiles/rails_5_2.gemfile @@ -1,18 +1,20 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", "~> 5.2.0" +gem 'rails', '~> 5.2.0' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 52.0" - gem "activerecord-jdbcpostgresql-adapter", "~> 52.0" - gem "activerecord-jdbcmysql-adapter", "~> 52.0" + gem 'activerecord-jdbc-adapter', '~> 52.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' + gem 'activerecord-jdbcmysql-adapter', '~> 52.0' end -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails_6_0.gemfile b/gemfiles/rails_6_0.gemfile index 20ed8a37..58cb5b6e 100644 --- a/gemfiles/rails_6_0.gemfile +++ b/gemfiles/rails_6_0.gemfile @@ -1,22 +1,24 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", "~> 6.0.0.rc1" +gem 'rails', '~> 6.0.0.rc1' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :ruby do - gem "sqlite3", "~> 1.4" + gem 'sqlite3', '~> 1.4' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 60.0.rc1" - gem "activerecord-jdbcpostgresql-adapter", "~> 60.0.rc1" - gem "activerecord-jdbcmysql-adapter", "~> 60.0.rc1" + gem 'activerecord-jdbc-adapter', '~> 60.0.rc1' + gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0.rc1' + gem 'activerecord-jdbcmysql-adapter', '~> 60.0.rc1' end -gemspec path: "../" +gemspec path: '../' diff --git a/gemfiles/rails_master.gemfile b/gemfiles/rails_master.gemfile index edc30465..a2eed35f 100644 --- a/gemfiles/rails_master.gemfile +++ b/gemfiles/rails_master.gemfile @@ -1,22 +1,24 @@ +# frozen_string_literal: true + # This file was generated by Appraisal -source "http://rubygems.org" +source 'http://rubygems.org' -gem "rails", git: "https://github.com/rails/rails.git" +gem 'rails', git: 'https://github.com/rails/rails.git' group :local do - gem "pry" - gem "guard-rspec", "~> 4.2" + gem 'pry' + gem 'guard-rspec', '~> 4.2' end platforms :ruby do - gem "sqlite3", "~> 1.4" + gem 'sqlite3', '~> 1.4' end platforms :jruby do - gem "activerecord-jdbc-adapter", "~> 52.0" - gem "activerecord-jdbcpostgresql-adapter", "~> 52.0" - gem "activerecord-jdbcmysql-adapter", "~> 52.0" + gem 'activerecord-jdbc-adapter', '~> 52.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' + gem 'activerecord-jdbcmysql-adapter', '~> 52.0' end -gemspec path: "../" +gemspec path: '../' diff --git a/lib/apartment.rb b/lib/apartment.rb index b48d45fb..0b5f774e 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/railtie' if defined?(Rails) require 'active_support/core_ext/object/blank' require 'forwardable' @@ -52,7 +54,7 @@ def excluded_models end def default_schema - @default_schema || "public" # TODO 'public' is postgres specific + @default_schema || 'public' # TODO 'public' is postgres specific end def parallel_migration_threads @@ -78,7 +80,7 @@ def database_schema_file def seed_data_file return @seed_data_file if defined?(@seed_data_file) - @seed_data_file = "#{Rails.root}/db/seeds.rb" + @seed_data_file = Rails.root.join('db', 'seeds.rb') end def pg_excluded_names diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index f3c9feb2..fe23552f 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment module Adapters # rubocop:disable Metrics/ClassLength @@ -56,8 +58,8 @@ def drop(tenant) with_neutral_connection(tenant) do |conn| drop_command(conn, tenant) end - rescue *rescuable_exceptions => exception - raise_drop_tenant_error!(tenant, exception) + rescue *rescuable_exceptions => e + raise_drop_tenant_error!(tenant, e) end # Switch to a new tenant @@ -159,8 +161,8 @@ def create_tenant(tenant) with_neutral_connection(tenant) do |conn| create_tenant_command(conn, tenant) end - rescue *rescuable_exceptions => exception - raise_create_tenant_error!(tenant, exception) + rescue *rescuable_exceptions => e + raise_create_tenant_error!(tenant, e) end def create_tenant_command(conn, tenant) @@ -178,9 +180,9 @@ def connect_to_new(tenant) Apartment.connection.active? # call active? to manually check if this connection is valid Apartment.connection.enable_query_cache! if query_cache_enabled - rescue *rescuable_exceptions => exception + rescue *rescuable_exceptions => e Apartment::Tenant.reset if reset_on_connection_exception? - raise_connect_error!(tenant, exception) + raise_connect_error!(tenant, e) end # Import the database schema @@ -210,7 +212,7 @@ def multi_tenantify_with_tenant_db_name(config, tenant) # Load a file or raise error if it doesn't exists # def load_or_raise(file) - if File.exists?(file) + if File.exist?(file) load(file) else raise FileNotFound, "#{file} doesn't exist yet" diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index 0f7da013..d37aa79d 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/adapters/abstract_adapter' module Apartment diff --git a/lib/apartment/adapters/jdbc_mysql_adapter.rb b/lib/apartment/adapters/jdbc_mysql_adapter.rb index 46943176..90c1bfeb 100644 --- a/lib/apartment/adapters/jdbc_mysql_adapter.rb +++ b/lib/apartment/adapters/jdbc_mysql_adapter.rb @@ -1,4 +1,6 @@ -require "apartment/adapters/abstract_jdbc_adapter" +# frozen_string_literal: true + +require 'apartment/adapters/abstract_jdbc_adapter' module Apartment module Tenant diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 5ae8c868..4353cfbf 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/adapters/postgresql_adapter' module Apartment @@ -21,7 +23,7 @@ def multi_tenantify_with_tenant_db_name(config, tenant) end def create_tenant_command(conn, tenant) - conn.create_database(environmentify(tenant), :thisisahack => '') + conn.create_database(environmentify(tenant), thisisahack: '') end def rescue_from diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index 30fb2c48..d35427ff 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/adapters/abstract_adapter' module Apartment @@ -48,9 +50,9 @@ def connect_to_new(tenant) return reset if tenant.nil? Apartment.connection.execute "use `#{environmentify(tenant)}`" - rescue ActiveRecord::StatementInvalid => exception + rescue ActiveRecord::StatementInvalid => e Apartment::Tenant.reset - raise_connect_error!(tenant, exception) + raise_connect_error!(tenant, e) end def process_excluded_model(model) diff --git a/lib/apartment/adapters/postgis_adapter.rb b/lib/apartment/adapters/postgis_adapter.rb index f9491476..bcf67be1 100644 --- a/lib/apartment/adapters/postgis_adapter.rb +++ b/lib/apartment/adapters/postgis_adapter.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # handle postgis adapter as if it were postgresql, # only override the adapter_method used for initialization -require "apartment/adapters/postgresql_adapter" +require 'apartment/adapters/postgresql_adapter' module Apartment module Tenant diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 5c51f70f..73a1643e 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/adapters/abstract_adapter' module Apartment @@ -53,7 +55,7 @@ def process_excluded_model(excluded_model) end def drop_command(conn, tenant) - conn.execute(%{DROP SCHEMA "#{tenant}" CASCADE}) + conn.execute(%(DROP SCHEMA "#{tenant}" CASCADE)) end # Set schema search path to new schema @@ -81,13 +83,13 @@ def connect_to_new(tenant = nil) private def create_tenant_command(conn, tenant) - conn.execute(%{CREATE SCHEMA "#{tenant}"}) + conn.execute(%(CREATE SCHEMA "#{tenant}")) end # Generate the final search path to set including persistent_schemas # def full_search_path - persistent_schemas.map(&:inspect).join(", ") + persistent_schemas.map(&:inspect).join(', ') end def persistent_schemas @@ -127,7 +129,7 @@ def import_database_schema # and it mut be reset # def preserving_search_path - search_path = Apartment.connection.execute("show search_path").first["search_path"] + search_path = Apartment.connection.execute('show search_path').first['search_path'] yield Apartment.connection.execute("set search_path = #{search_path}") end @@ -210,7 +212,7 @@ def swap_schema_qualifier(sql) if Apartment.pg_excluded_names.any? { |name| match.include? name } match else - match.gsub("#{default_tenant}.", %{"#{current}".}) + match.gsub("#{default_tenant}.", %("#{current}".)) end end end diff --git a/lib/apartment/adapters/sqlite3_adapter.rb b/lib/apartment/adapters/sqlite3_adapter.rb index f4e169a6..78f26adc 100644 --- a/lib/apartment/adapters/sqlite3_adapter.rb +++ b/lib/apartment/adapters/sqlite3_adapter.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/adapters/abstract_adapter' module Apartment @@ -17,7 +19,7 @@ def initialize(config) def drop(tenant) raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} cannot be found." unless File.exist?(database_file(tenant)) File.delete(database_file(tenant)) end @@ -30,14 +32,14 @@ def current def connect_to_new(tenant) raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} cannot be found." unless File.exist?(database_file(tenant)) super database_file(tenant) end def create_tenant(tenant) raise TenantExists, - "The tenant #{environmentify(tenant)} already exists." if File.exists?(database_file(tenant)) + "The tenant #{environmentify(tenant)} already exists." if File.exist?(database_file(tenant)) begin f = File.new(database_file(tenant), File::CREAT) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index b84648ed..ee1220a8 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + # A workaraound to get `reload!` to also call Apartment::Tenant.init # This is unfortunate, but I haven't figured out how to hook into the reload process *after* files are reloaded # reloads the environment def reload!(print = true) - puts "Reloading..." if print + puts 'Reloading...' if print # This triggers the to_prepare callbacks ActionDispatch::Callbacks.new(proc {}).call({}) # Manually init Apartment again once classes are reloaded diff --git a/lib/apartment/deprecation.rb b/lib/apartment/deprecation.rb index 3355f802..db73dd5d 100644 --- a/lib/apartment/deprecation.rb +++ b/lib/apartment/deprecation.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'active_support/deprecation' module Apartment diff --git a/lib/apartment/elevators/domain.rb b/lib/apartment/elevators/domain.rb index 9c6862ad..8915289a 100644 --- a/lib/apartment/elevators/domain.rb +++ b/lib/apartment/elevators/domain.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/elevators/generic' module Apartment @@ -14,7 +16,7 @@ class Domain < Generic def parse_tenant_name(request) return nil if request.host.blank? - request.host.match(/(www\.)?(?[^.]*)/)["sld"] + request.host.match(/(www\.)?(?[^.]*)/)['sld'] end end end diff --git a/lib/apartment/elevators/first_subdomain.rb b/lib/apartment/elevators/first_subdomain.rb index e53fa4b9..20ef3e68 100644 --- a/lib/apartment/elevators/first_subdomain.rb +++ b/lib/apartment/elevators/first_subdomain.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/elevators/subdomain' module Apartment diff --git a/lib/apartment/elevators/generic.rb b/lib/apartment/elevators/generic.rb index 716db5dc..8d321aaa 100644 --- a/lib/apartment/elevators/generic.rb +++ b/lib/apartment/elevators/generic.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rack/request' require 'apartment/tenant' @@ -24,7 +26,7 @@ def call(env) end def parse_tenant_name(request) - raise "Override" + raise 'Override' end end end diff --git a/lib/apartment/elevators/host.rb b/lib/apartment/elevators/host.rb index 3a9f8da6..283ad316 100644 --- a/lib/apartment/elevators/host.rb +++ b/lib/apartment/elevators/host.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/elevators/generic' module Apartment diff --git a/lib/apartment/elevators/host_hash.rb b/lib/apartment/elevators/host_hash.rb index 7838d671..306f0319 100644 --- a/lib/apartment/elevators/host_hash.rb +++ b/lib/apartment/elevators/host_hash.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/elevators/generic' module Apartment diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index 5716a168..60e9d022 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/elevators/generic' require 'public_suffix' diff --git a/lib/apartment/migrator.rb b/lib/apartment/migrator.rb index 27f6714c..089109df 100644 --- a/lib/apartment/migrator.rb +++ b/lib/apartment/migrator.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'apartment/tenant' module Apartment @@ -7,9 +9,9 @@ module Migrator # Migrate to latest def migrate(database) Tenant.switch(database) do - version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil + version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil - migration_scope_block = ->(migration) { ENV["SCOPE"].blank? || (ENV["SCOPE"] == migration.scope) } + migration_scope_block = ->(migration) { ENV['SCOPE'].blank? || (ENV['SCOPE'] == migration.scope) } if activerecord_below_5_2? ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, version, &migration_scope_block) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index beba954c..43bc54a5 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rails' require 'apartment/tenant' require 'apartment/reloader' @@ -32,10 +34,12 @@ class Railtie < Rails::Railtie Apartment.connection_class.connection_pool.with_connection do Apartment::Tenant.init end + # rubocop:disable Lint/SuppressedException rescue ::ActiveRecord::NoDatabaseError # Since `db:create` and other tasks invoke this block from Rails 5.2.0, # we need to swallow the error to execute `db:create` properly. end + # rubocop:enable Lint/SuppressedException end # diff --git a/lib/apartment/reloader.rb b/lib/apartment/reloader.rb index 164c838e..cd8b6861 100644 --- a/lib/apartment/reloader.rb +++ b/lib/apartment/reloader.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment class Reloader # Middleware used in development to init Apartment for each request diff --git a/lib/apartment/tasks/enhancements.rb b/lib/apartment/tasks/enhancements.rb index dff7099b..95e32ab7 100644 --- a/lib/apartment/tasks/enhancements.rb +++ b/lib/apartment/tasks/enhancements.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + # Require this file to append Apartment rake tasks to ActiveRecord db rake tasks # Enabled by default in the initializer module Apartment class RakeTaskEnhancer module TASKS - ENHANCE_BEFORE = %w(db:drop) - ENHANCE_AFTER = %w(db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed) + ENHANCE_BEFORE = %w[db:drop] + ENHANCE_AFTER = %w[db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed] freeze end diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 6e1e713b..93e755a0 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'forwardable' module Apartment diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 25f180b1..8f84b610 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment - VERSION = "2.3.0" + VERSION = '2.3.0' end diff --git a/lib/generators/apartment/install/install_generator.rb b/lib/generators/apartment/install/install_generator.rb index 079a732b..509cf2e9 100755 --- a/lib/generators/apartment/install/install_generator.rb +++ b/lib/generators/apartment/install/install_generator.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + module Apartment class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) def copy_files - template "apartment.rb", File.join("config", "initializers", "apartment.rb") + template 'apartment.rb', File.join('config', 'initializers', 'apartment.rb') end end end diff --git a/lib/generators/apartment/install/templates/apartment.rb b/lib/generators/apartment/install/templates/apartment.rb index 251033bf..2a774737 100644 --- a/lib/generators/apartment/install/templates/apartment.rb +++ b/lib/generators/apartment/install/templates/apartment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # You can have Apartment route to the appropriate Tenant by adding some Rack middleware. # Apartment can support many different "Elevators" that can take care of this routing to your data. # Require whichever Elevator you're using below or none if you have a custom one. @@ -47,7 +49,7 @@ # end # end # - config.tenant_names = lambda { ToDo_Tenant_Or_User_Model.pluck :database } + config.tenant_names = -> { ToDo_Tenant_Or_User_Model.pluck :database } # PostgreSQL: # Specifies whether to use PostgreSQL schemas or create a new database per Tenant. diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index ff736393..10c4613a 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'apartment/migrator' require 'parallel' apartment_namespace = namespace :apartment do - desc "Create all tenants" + desc 'Create all tenants' task :create do tenants.each do |tenant| begin @@ -14,7 +16,7 @@ apartment_namespace = namespace :apartment do end end - desc "Drop all tenants" + desc 'Drop all tenants' task :drop do tenants.each do |tenant| begin @@ -26,7 +28,7 @@ apartment_namespace = namespace :apartment do end end - desc "Migrate all tenants" + desc 'Migrate all tenants' task :migrate do warn_if_tenants_empty each_tenant do |tenant| @@ -39,7 +41,7 @@ apartment_namespace = namespace :apartment do end end - desc "Seed all tenants" + desc 'Seed all tenants' task :seed do warn_if_tenants_empty @@ -55,7 +57,7 @@ apartment_namespace = namespace :apartment do end end - desc "Rolls the migration back to the previous version (specify steps w/ STEP=n) across all tenants." + desc 'Rolls the migration back to the previous version (specify steps w/ STEP=n) across all tenants.' task :rollback do warn_if_tenants_empty @@ -129,7 +131,7 @@ apartment_namespace = namespace :apartment do end def warn_if_tenants_empty - if tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != "true" + if tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' puts <<-WARNING [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 1fb5d433..4833f93d 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + if defined?(JRUBY_VERSION) require 'spec_helper' @@ -7,12 +9,12 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute("SELECT schema_name FROM information_schema.schemata").collect { |row| row['schema_name'] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row['schema_name'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a connection based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a connection based apartment adapter' end end diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index d595a7d9..49dfaf1a 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + if defined?(JRUBY_VERSION) require 'spec_helper' @@ -6,32 +8,32 @@ describe Apartment::Adapters::JDBCPostgresqlAdapter, database: :postgresql do subject { Apartment::Tenant.jdbc_postgresql_adapter config.symbolize_keys } - context "using schemas" do + context 'using schemas' do before { Apartment.use_schemas = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names - ActiveRecord::Base.connection.execute("SELECT nspname FROM pg_namespace;").collect { |row| row['nspname'] } + ActiveRecord::Base.connection.execute('SELECT nspname FROM pg_namespace;').collect { |row| row['nspname'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.schema_search_path.gsub('"', '') } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a schema based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a schema based apartment adapter' end - context "using databases" do + context 'using databases' do before { Apartment.use_schemas = false } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names - connection.execute("select datname from pg_database;").collect { |row| row['datname'] } + connection.execute('select datname from pg_database;').collect { |row| row['datname'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a connection based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a connection based apartment adapter' end end end diff --git a/spec/adapters/mysql2_adapter_spec.rb b/spec/adapters/mysql2_adapter_spec.rb index 831affed..29529514 100644 --- a/spec/adapters/mysql2_adapter_spec.rb +++ b/spec/adapters/mysql2_adapter_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/adapters/mysql2_adapter' @@ -7,28 +9,28 @@ subject(:adapter) { Apartment::Tenant.mysql2_adapter config } def tenant_names - ActiveRecord::Base.connection.execute("SELECT schema_name FROM information_schema.schemata").collect { |row| row[0] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row[0] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } - context "using - the equivalent of - schemas" do + context 'using - the equivalent of - schemas' do before { Apartment.use_schemas = true } - it_should_behave_like "a generic apartment adapter" + it_should_behave_like 'a generic apartment adapter' - describe "#default_tenant" do - it "is set to the original db from config" do + describe '#default_tenant' do + it 'is set to the original db from config' do expect(subject.default_tenant).to eq(config[:database]) end end - describe "#init" do + describe '#init' do include Apartment::Spec::AdapterRequirements before do Apartment.configure do |config| - config.excluded_models = ["Company"] + config.excluded_models = ['Company'] end end @@ -40,7 +42,7 @@ def tenant_names end end - it "should process model exclusions" do + it 'should process model exclusions' do Apartment::Tenant.init expect(Company.table_name).to eq("#{default_tenant}.companies") @@ -48,12 +50,12 @@ def tenant_names end end - context "using connections" do + context 'using connections' do before { Apartment.use_schemas = false } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a generic apartment adapter able to handle custom configuration" - it_should_behave_like "a connection based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a generic apartment adapter able to handle custom configuration' + it_should_behave_like 'a connection based apartment adapter' end end end diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 7802a7bd..d553ff8b 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/adapters/postgresql_adapter' @@ -6,21 +8,21 @@ subject { Apartment::Tenant.postgresql_adapter config } - context "using schemas with schema.rb" do + context 'using schemas with schema.rb' do before { Apartment.use_schemas = true } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names - ActiveRecord::Base.connection.execute("SELECT nspname FROM pg_namespace;").collect { |row| row['nspname'] } + ActiveRecord::Base.connection.execute('SELECT nspname FROM pg_namespace;').collect { |row| row['nspname'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.schema_search_path.gsub('"', '') } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a schema based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a schema based apartment adapter' end - context "using schemas with SQL dump" do + context 'using schemas with SQL dump' do before do Apartment.use_schemas = true Apartment.use_sql = true @@ -28,13 +30,13 @@ def tenant_names # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names - ActiveRecord::Base.connection.execute("SELECT nspname FROM pg_namespace;").collect { |row| row['nspname'] } + ActiveRecord::Base.connection.execute('SELECT nspname FROM pg_namespace;').collect { |row| row['nspname'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.schema_search_path.gsub('"', '') } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a schema based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a schema based apartment adapter' it 'allows for dashes in the schema name' do expect { Apartment::Tenant.create('has-dashes') }.to_not raise_error @@ -43,19 +45,19 @@ def tenant_names after { Apartment::Tenant.drop('has-dashes') if Apartment.connection.schema_exists? 'has-dashes' } end - context "using connections" do + context 'using connections' do before { Apartment.use_schemas = false } # Not sure why, but somehow using let(:tenant_names) memoizes for the whole example group, not just each test def tenant_names - connection.execute("select datname from pg_database;").collect { |row| row['datname'] } + connection.execute('select datname from pg_database;').collect { |row| row['datname'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a generic apartment adapter able to handle custom configuration" - it_should_behave_like "a connection based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a generic apartment adapter able to handle custom configuration' + it_should_behave_like 'a connection based apartment adapter' end end end diff --git a/spec/adapters/sqlite3_adapter_spec.rb b/spec/adapters/sqlite3_adapter_spec.rb index 92246249..40388acd 100644 --- a/spec/adapters/sqlite3_adapter_spec.rb +++ b/spec/adapters/sqlite3_adapter_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/adapters/sqlite3_adapter' @@ -6,9 +8,9 @@ subject { Apartment::Tenant.sqlite3_adapter config } - context "using connections" do + context 'using connections' do def tenant_names - db_dir = File.expand_path("../../dummy/db", __FILE__) + db_dir = File.expand_path('../../dummy/db', __FILE__) Dir.glob("#{db_dir}/*.sqlite3").map { |file| File.basename(file, '.sqlite3') } end @@ -16,18 +18,18 @@ def tenant_names subject.switch { File.basename(Apartment::Test.config['connections']['sqlite']['database'], '.sqlite3') } end - it_should_behave_like "a generic apartment adapter" - it_should_behave_like "a connection based apartment adapter" + it_should_behave_like 'a generic apartment adapter' + it_should_behave_like 'a connection based apartment adapter' after(:all) do File.delete(Apartment::Test.config['connections']['sqlite']['database']) end end - context "with prepend and append" do + context 'with prepend and append' do let(:default_dir) { File.expand_path(File.dirname(config[:database])) } - describe "#prepend" do - let (:db_name) { "db_with_prefix" } + describe '#prepend' do + let(:db_name) { 'db_with_prefix' } before do Apartment.configure do |config| config.prepend_environment = true @@ -43,15 +45,15 @@ def tenant_names end end - it "should create a new database" do + it 'should create a new database' do subject.create db_name - expect(File.exists?("#{default_dir}/#{Rails.env}_#{db_name}.sqlite3")).to eq true + expect(File.exist?("#{default_dir}/#{Rails.env}_#{db_name}.sqlite3")).to eq true end end - describe "#neither" do - let (:db_name) { "db_without_prefix_suffix" } + describe '#neither' do + let(:db_name) { 'db_without_prefix_suffix' } before do Apartment.configure { |config| config.prepend_environment = config.append_environment = false } end @@ -64,15 +66,15 @@ def tenant_names end end - it "should create a new database" do + it 'should create a new database' do subject.create db_name - expect(File.exists?("#{default_dir}/#{db_name}.sqlite3")).to eq true + expect(File.exist?("#{default_dir}/#{db_name}.sqlite3")).to eq true end end - describe "#append" do - let (:db_name) { "db_with_suffix" } + describe '#append' do + let(:db_name) { 'db_with_suffix' } before do Apartment.configure do |config| config.prepend_environment = false @@ -88,10 +90,10 @@ def tenant_names end end - it "should create a new database" do + it 'should create a new database' do subject.create db_name - expect(File.exists?("#{default_dir}/#{db_name}_#{Rails.env}.sqlite3")).to eq true + expect(File.exist?("#{default_dir}/#{db_name}_#{Rails.env}.sqlite3")).to eq true end end end diff --git a/spec/apartment_spec.rb b/spec/apartment_spec.rb index b00e0b2d..f90a09f2 100644 --- a/spec/apartment_spec.rb +++ b/spec/apartment_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' describe Apartment do - it "should be valid" do + it 'should be valid' do expect(Apartment).to be_a(Module) end - it "should be a valid app" do + it 'should be a valid app' do expect(::Rails.application).to be_a(Dummy::Application) end end diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb index 9ec13342..bfa2456c 100644 --- a/spec/dummy/app/controllers/application_controller.rb +++ b/spec/dummy/app/controllers/application_controller.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + class ApplicationController < ActionController::Base protect_from_forgery diff --git a/spec/dummy/app/helpers/application_helper.rb b/spec/dummy/app/helpers/application_helper.rb index de6be794..15b06f0f 100644 --- a/spec/dummy/app/helpers/application_helper.rb +++ b/spec/dummy/app/helpers/application_helper.rb @@ -1,2 +1,4 @@ +# frozen_string_literal: true + module ApplicationHelper end diff --git a/spec/dummy/app/models/company.rb b/spec/dummy/app/models/company.rb index f97ca639..96986b7d 100644 --- a/spec/dummy/app/models/company.rb +++ b/spec/dummy/app/models/company.rb @@ -1,3 +1,5 @@ -class Company < ActiveRecord::Base +# frozen_string_literal: true + +class Company < ApplicationRecord # Dummy models end diff --git a/spec/dummy/app/models/user.rb b/spec/dummy/app/models/user.rb index 61e0ee5f..463ce352 100644 --- a/spec/dummy/app/models/user.rb +++ b/spec/dummy/app/models/user.rb @@ -1,3 +1,5 @@ -class User < ActiveRecord::Base +# frozen_string_literal: true + +class User < ApplicationRecord # Dummy models end diff --git a/spec/dummy/config.ru b/spec/dummy/config.ru index cbd74159..989f7c64 100644 --- a/spec/dummy/config.ru +++ b/spec/dummy/config.ru @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) diff --git a/spec/dummy/config/application.rb b/spec/dummy/config/application.rb index e8f51ed9..c633c115 100644 --- a/spec/dummy/config/application.rb +++ b/spec/dummy/config/application.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require File.expand_path('../boot', __FILE__) -require "active_model/railtie" -require "active_record/railtie" -require "action_controller/railtie" -require "action_view/railtie" -require "action_mailer/railtie" +require 'active_model/railtie' +require 'active_record/railtie' +require 'action_controller/railtie' +require 'action_view/railtie' +require 'action_mailer/railtie' Bundler.require -require "apartment" +require 'apartment' module Dummy class Application < Rails::Application @@ -20,7 +22,7 @@ class Application < Rails::Application config.middleware.use Apartment::Elevators::Subdomain # Custom directories with classes and modules you want to be autoloadable. - config.autoload_paths += %W(#{config.root}/lib) + config.autoload_paths += %W[#{config.root}/lib] # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named. @@ -41,7 +43,7 @@ class Application < Rails::Application # config.action_view.javascript_expansions[:defaults] = %w(jquery rails) # Configure the default encoding used in templates for Ruby 1.9. - config.encoding = "utf-8" + config.encoding = 'utf-8' # Configure sensitive parameters which will be filtered from the log file. config.filter_parameters += [:password] diff --git a/spec/dummy/config/boot.rb b/spec/dummy/config/boot.rb index 58dd2d36..1f976a16 100644 --- a/spec/dummy/config/boot.rb +++ b/spec/dummy/config/boot.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'rubygems' gemfile = File.expand_path('../../../../Gemfile', __FILE__) diff --git a/spec/dummy/config/environment.rb b/spec/dummy/config/environment.rb index 3da5eb91..1a1e336f 100644 --- a/spec/dummy/config/environment.rb +++ b/spec/dummy/config/environment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Load the rails application require File.expand_path('../application', __FILE__) diff --git a/spec/dummy/config/environments/development.rb b/spec/dummy/config/environments/development.rb index 229d545c..77567be6 100644 --- a/spec/dummy/config/environments/development.rb +++ b/spec/dummy/config/environments/development.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb diff --git a/spec/dummy/config/environments/production.rb b/spec/dummy/config/environments/production.rb index a71b06c4..1d9b71e1 100644 --- a/spec/dummy/config/environments/production.rb +++ b/spec/dummy/config/environments/production.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb @@ -12,7 +14,7 @@ config.action_controller.perform_caching = true # Specifies the header that your server uses for sending files - config.action_dispatch.x_sendfile_header = "X-Sendfile" + config.action_dispatch.x_sendfile_header = 'X-Sendfile' # For nginx: # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' diff --git a/spec/dummy/config/environments/test.rb b/spec/dummy/config/environments/test.rb index e3634079..3044c445 100644 --- a/spec/dummy/config/environments/test.rb +++ b/spec/dummy/config/environments/test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Dummy::Application.configure do # Settings specified here will take precedence over those in config/application.rb diff --git a/spec/dummy/config/initializers/apartment.rb b/spec/dummy/config/initializers/apartment.rb index d7d0fcfc..7db9fd26 100644 --- a/spec/dummy/config/initializers/apartment.rb +++ b/spec/dummy/config/initializers/apartment.rb @@ -1,4 +1,6 @@ +# frozen_string_literal: true + Apartment.configure do |config| - config.excluded_models = ["Company"] - config.tenant_names = lambda { Company.pluck(:database) } + config.excluded_models = ['Company'] + config.tenant_names = -> { Company.pluck(:database) } end diff --git a/spec/dummy/config/initializers/backtrace_silencers.rb b/spec/dummy/config/initializers/backtrace_silencers.rb index 59385cdf..d0f0d3b5 100644 --- a/spec/dummy/config/initializers/backtrace_silencers.rb +++ b/spec/dummy/config/initializers/backtrace_silencers.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. diff --git a/spec/dummy/config/initializers/inflections.rb b/spec/dummy/config/initializers/inflections.rb index 9e8b0131..8138cabc 100644 --- a/spec/dummy/config/initializers/inflections.rb +++ b/spec/dummy/config/initializers/inflections.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format diff --git a/spec/dummy/config/initializers/mime_types.rb b/spec/dummy/config/initializers/mime_types.rb index 72aca7e4..f75864f9 100644 --- a/spec/dummy/config/initializers/mime_types.rb +++ b/spec/dummy/config/initializers/mime_types.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: diff --git a/spec/dummy/config/initializers/secret_token.rb b/spec/dummy/config/initializers/secret_token.rb index 1c651c86..2c7f52bd 100644 --- a/spec/dummy/config/initializers/secret_token.rb +++ b/spec/dummy/config/initializers/secret_token.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. # Your secret key for verifying the integrity of signed cookies. diff --git a/spec/dummy/config/initializers/session_store.rb b/spec/dummy/config/initializers/session_store.rb index aa2f5129..66099cf5 100644 --- a/spec/dummy/config/initializers/session_store.rb +++ b/spec/dummy/config/initializers/session_store.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. -Dummy::Application.config.session_store :cookie_store, :key => '_dummy_session' +Dummy::Application.config.session_store :cookie_store, key: '_dummy_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information diff --git a/spec/dummy/config/routes.rb b/spec/dummy/config/routes.rb index 99d3e5c1..d0be0e6d 100644 --- a/spec/dummy/config/routes.rb +++ b/spec/dummy/config/routes.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Dummy::Application.routes.draw do - root :to => 'application#index' + root to: 'application#index' end diff --git a/spec/dummy/db/seeds/import.rb b/spec/dummy/db/seeds/import.rb index 4e2eb81b..10b479b9 100644 --- a/spec/dummy/db/seeds/import.rb +++ b/spec/dummy/db/seeds/import.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + def create_users 6.times { |x| User.where(name: "Different User #{x}").first_or_create! } end diff --git a/spec/dummy/script/rails b/spec/dummy/script/rails index bd79dce5..1a08aed0 100755 --- a/spec/dummy/script/rails +++ b/spec/dummy/script/rails @@ -1,4 +1,6 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. APP_PATH = File.expand_path('../../config/application', __FILE__) diff --git a/spec/dummy_engine/config/initializers/apartment.rb b/spec/dummy_engine/config/initializers/apartment.rb index b94a7f1f..466f3d87 100644 --- a/spec/dummy_engine/config/initializers/apartment.rb +++ b/spec/dummy_engine/config/initializers/apartment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Require whichever elevator you're using below here... # # require 'apartment/elevators/generic' @@ -16,7 +18,7 @@ # # config.excluded_models = %w{Tenant} # - config.excluded_models = %w{} + config.excluded_models = %w[] # use postgres schemas? config.use_schemas = true diff --git a/spec/dummy_engine/lib/dummy_engine.rb b/spec/dummy_engine/lib/dummy_engine.rb index b1a14145..8f9c8111 100644 --- a/spec/dummy_engine/lib/dummy_engine.rb +++ b/spec/dummy_engine/lib/dummy_engine.rb @@ -1,4 +1,6 @@ -require "dummy_engine/engine" +# frozen_string_literal: true + +require 'dummy_engine/engine' module DummyEngine end diff --git a/spec/dummy_engine/lib/dummy_engine/engine.rb b/spec/dummy_engine/lib/dummy_engine/engine.rb index cc8821c3..d308ec0d 100644 --- a/spec/dummy_engine/lib/dummy_engine/engine.rb +++ b/spec/dummy_engine/lib/dummy_engine/engine.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module DummyEngine class Engine < ::Rails::Engine end diff --git a/spec/dummy_engine/lib/dummy_engine/version.rb b/spec/dummy_engine/lib/dummy_engine/version.rb index 82d2c8b8..76d025df 100644 --- a/spec/dummy_engine/lib/dummy_engine/version.rb +++ b/spec/dummy_engine/lib/dummy_engine/version.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module DummyEngine - VERSION = "0.0.1" + VERSION = '0.0.1' end diff --git a/spec/dummy_engine/test/dummy/config.ru b/spec/dummy_engine/test/dummy/config.ru index bd83b254..61c04e13 100644 --- a/spec/dummy_engine/test/dummy/config.ru +++ b/spec/dummy_engine/test/dummy/config.ru @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # This file is used by Rack-based servers to start the application. require ::File.expand_path('../config/environment', __FILE__) diff --git a/spec/dummy_engine/test/dummy/config/application.rb b/spec/dummy_engine/test/dummy/config/application.rb index 5ef001e9..2562455c 100644 --- a/spec/dummy_engine/test/dummy/config/application.rb +++ b/spec/dummy_engine/test/dummy/config/application.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) -require "dummy_engine" +require 'dummy_engine' module Dummy class Application < Rails::Application diff --git a/spec/dummy_engine/test/dummy/config/boot.rb b/spec/dummy_engine/test/dummy/config/boot.rb index 6266cfc5..18536532 100644 --- a/spec/dummy_engine/test/dummy/config/boot.rb +++ b/spec/dummy_engine/test/dummy/config/boot.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) diff --git a/spec/dummy_engine/test/dummy/config/environment.rb b/spec/dummy_engine/test/dummy/config/environment.rb index ee8d90dc..3fa66218 100644 --- a/spec/dummy_engine/test/dummy/config/environment.rb +++ b/spec/dummy_engine/test/dummy/config/environment.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Load the Rails application. require File.expand_path('../application', __FILE__) diff --git a/spec/dummy_engine/test/dummy/config/environments/development.rb b/spec/dummy_engine/test/dummy/config/environments/development.rb index ddf0e90c..8296624e 100644 --- a/spec/dummy_engine/test/dummy/config/environments/development.rb +++ b/spec/dummy_engine/test/dummy/config/environments/development.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. diff --git a/spec/dummy_engine/test/dummy/config/environments/production.rb b/spec/dummy_engine/test/dummy/config/environments/production.rb index b93a877c..1bd152f1 100644 --- a/spec/dummy_engine/test/dummy/config/environments/production.rb +++ b/spec/dummy_engine/test/dummy/config/environments/production.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. diff --git a/spec/dummy_engine/test/dummy/config/environments/test.rb b/spec/dummy_engine/test/dummy/config/environments/test.rb index 053f5b66..bd942389 100644 --- a/spec/dummy_engine/test/dummy/config/environments/test.rb +++ b/spec/dummy_engine/test/dummy/config/environments/test.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. diff --git a/spec/dummy_engine/test/dummy/config/initializers/assets.rb b/spec/dummy_engine/test/dummy/config/initializers/assets.rb index d2f4ec33..761905a7 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/assets.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/assets.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. diff --git a/spec/dummy_engine/test/dummy/config/initializers/backtrace_silencers.rb b/spec/dummy_engine/test/dummy/config/initializers/backtrace_silencers.rb index 59385cdf..d0f0d3b5 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/backtrace_silencers.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/backtrace_silencers.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. diff --git a/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb b/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb index 7f70458d..0a23b25e 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/spec/dummy_engine/test/dummy/config/initializers/filter_parameter_logging.rb b/spec/dummy_engine/test/dummy/config/initializers/filter_parameter_logging.rb index 4a994e1e..7a4f47b4 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/filter_parameter_logging.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/filter_parameter_logging.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. diff --git a/spec/dummy_engine/test/dummy/config/initializers/inflections.rb b/spec/dummy_engine/test/dummy/config/initializers/inflections.rb index ac033bf9..aa7435fb 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/inflections.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/inflections.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections diff --git a/spec/dummy_engine/test/dummy/config/initializers/mime_types.rb b/spec/dummy_engine/test/dummy/config/initializers/mime_types.rb index dc189968..6e1d16f0 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/mime_types.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/mime_types.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: diff --git a/spec/dummy_engine/test/dummy/config/initializers/session_store.rb b/spec/dummy_engine/test/dummy/config/initializers/session_store.rb index e766b67b..969d977f 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/session_store.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/session_store.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_dummy_session' diff --git a/spec/dummy_engine/test/dummy/config/initializers/wrap_parameters.rb b/spec/dummy_engine/test/dummy/config/initializers/wrap_parameters.rb index 33725e95..246168a4 100644 --- a/spec/dummy_engine/test/dummy/config/initializers/wrap_parameters.rb +++ b/spec/dummy_engine/test/dummy/config/initializers/wrap_parameters.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which diff --git a/spec/dummy_engine/test/dummy/config/routes.rb b/spec/dummy_engine/test/dummy/config/routes.rb index 3f66539d..189947fc 100644 --- a/spec/dummy_engine/test/dummy/config/routes.rb +++ b/spec/dummy_engine/test/dummy/config/routes.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". diff --git a/spec/examples/connection_adapter_examples.rb b/spec/examples/connection_adapter_examples.rb index b335e182..033ded4f 100644 --- a/spec/examples/connection_adapter_examples.rb +++ b/spec/examples/connection_adapter_examples.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' -shared_examples_for "a connection based apartment adapter" do +shared_examples_for 'a connection based apartment adapter' do include Apartment::Spec::AdapterRequirements let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } - describe "#init" do + describe '#init' do after do # Apartment::Tenant.init creates per model connection. # Remove the connection after testing not to unintentionally keep the connection across tests. @@ -14,9 +16,9 @@ end end - it "should process model exclusions" do + it 'should process model exclusions' do Apartment.configure do |config| - config.excluded_models = ["Company"] + config.excluded_models = ['Company'] end Apartment::Tenant.init @@ -24,16 +26,16 @@ end end - describe "#drop" do - it "should raise an error for unknown database" do + describe '#drop' do + it 'should raise an error for unknown database' do expect { subject.drop 'unknown_database' }.to raise_error(Apartment::TenantNotFound) end end - describe "#switch!" do - it "should raise an error if database is invalid" do + describe '#switch!' do + it 'should raise an error if database is invalid' do expect { subject.switch! 'unknown_database' }.to raise_error(Apartment::TenantNotFound) diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index 27ca1c84..a5fece4c 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' -shared_examples_for "a generic apartment adapter able to handle custom configuration" do +shared_examples_for 'a generic apartment adapter able to handle custom configuration' do let(:custom_tenant_name) { 'test_tenantwwww' } let(:db) { |example| example.metadata[:database] } let(:custom_tenant_names) do { - custom_tenant_name => get_custom_db_conf + custom_tenant_name => custom_db_conf } end @@ -18,11 +20,11 @@ Apartment.with_multi_server_setup = false end - context "database key taken from specific config" do - let(:expected_args) { get_custom_db_conf } + context 'database key taken from specific config' do + let(:expected_args) { custom_db_conf } - describe "#create" do - it "should establish_connection with the separate connection with expected args" do + describe '#create' do + it 'should establish_connection with the separate connection with expected args' do expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to receive(:establish_connection).with(expected_args).and_call_original # because we dont have another server to connect to it errors @@ -31,8 +33,8 @@ end end - describe "#drop" do - it "should establish_connection with the separate connection with expected args" do + describe '#drop' do + it 'should establish_connection with the separate connection with expected args' do expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to receive(:establish_connection).with(expected_args).and_call_original # because we dont have another server to connect to it errors @@ -42,13 +44,13 @@ end end - context "database key from tenant name" do + context 'database key from tenant name' do let(:expected_args) { - get_custom_db_conf.tap { |args| args.delete(:database) } + custom_db_conf.tap { |args| args.delete(:database) } } - describe "#switch!" do - it "should connect to new db" do + describe '#switch!' do + it 'should connect to new db' do expect(Apartment).to receive(:establish_connection) do |args| db_name = args.delete(:database) @@ -85,7 +87,7 @@ def specific_connection } end - def get_custom_db_conf + def custom_db_conf specific_connection[db.to_sym].with_indifferent_access end end diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 9366cbe5..6da9bd56 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + require 'spec_helper' -shared_examples_for "a generic apartment adapter" do +shared_examples_for 'a generic apartment adapter' do include Apartment::Spec::AdapterRequirements before { @@ -8,8 +10,8 @@ Apartment.append_environment = false } - describe "#init" do - it "should not retain a connection after railtie" do + describe '#init' do + it 'should not retain a connection after railtie' do # this test should work on rails >= 4, the connection pool code is # completely different for 3.2 so we'd have to have a messy conditional.. unless Rails::VERSION::MAJOR < 4 @@ -30,19 +32,19 @@ # # Creates happen already in our before_filter # - describe "#create" do - it "should create the new databases" do + describe '#create' do + it 'should create the new databases' do expect(tenant_names).to include(db1) expect(tenant_names).to include(db2) end - it "should load schema.rb to new schema" do + it 'should load schema.rb to new schema' do subject.switch(db1) do expect(connection.tables).to include('companies') end end - it "should yield to block if passed and reset" do + it 'should yield to block if passed and reset' do subject.drop(db2) # so we don't get errors on creation @count = 0 # set our variable so its visible in and outside of blocks @@ -58,7 +60,7 @@ subject.switch(db2) { expect(User.count).to eq(@count + 1) } end - it "should raise error when the schema.rb is missing unless Apartment.use_sql is set to true" do + it 'should raise error when the schema.rb is missing unless Apartment.use_sql is set to true' do next if Apartment.use_sql subject.drop(db1) @@ -75,33 +77,33 @@ end end - describe "#drop" do - it "should remove the db" do + describe '#drop' do + it 'should remove the db' do subject.drop db1 expect(tenant_names).not_to include(db1) end end - describe "#switch!" do - it "should connect to new db" do + describe '#switch!' do + it 'should connect to new db' do subject.switch!(db1) expect(subject.current).to eq(db1) end - it "should reset connection if database is nil" do + it 'should reset connection if database is nil' do subject.switch! expect(subject.current).to eq(default_tenant) end - it "should raise an error if database is invalid" do + it 'should raise an error if database is invalid' do expect { subject.switch! 'unknown_database' }.to raise_error(Apartment::ApartmentError) end end - describe "#switch" do - it "connects and resets the tenant" do + describe '#switch' do + it 'connects and resets the tenant' do subject.switch(db1) do expect(subject.current).to eq(db1) end @@ -110,7 +112,7 @@ # We're often finding when using Apartment in tests, the `current` (ie the previously connect to db) # gets dropped, but switch will try to return to that db in a test. We should just reset if it doesn't exist - it "should not throw exception if current is no longer accessible" do + it 'should not throw exception if current is no longer accessible' do subject.switch!(db2) expect { @@ -119,23 +121,23 @@ end end - describe "#reset" do - it "should reset connection" do + describe '#reset' do + it 'should reset connection' do subject.switch!(db1) subject.reset expect(subject.current).to eq(default_tenant) end end - describe "#current" do - it "should return the current db name" do + describe '#current' do + it 'should return the current db name' do subject.switch!(db1) expect(subject.current).to eq(db1) end end - describe "#each" do - it "iterates over each tenant by default" do + describe '#each' do + it 'iterates over each tenant by default' do result = [] Apartment.tenant_names = [db2, db1] @@ -147,7 +149,7 @@ expect(result).to eq([db2, db1]) end - it "iterates over the given tenants" do + it 'iterates over the given tenants' do result = [] Apartment.tenant_names = [db2] diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index ddd82c1a..c96f7038 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' # rubocop:disable Metrics/BlockLength -shared_examples_for "a schema based apartment adapter" do +shared_examples_for 'a schema based apartment adapter' do include Apartment::Spec::AdapterRequirements let(:schema1) { db1 } let(:schema2) { db2 } let(:public_schema) { default_tenant } - describe "#init" do + describe '#init' do before do Apartment.configure do |config| - config.excluded_models = ["Company"] + config.excluded_models = ['Company'] end end @@ -23,14 +25,14 @@ end end - it "should process model exclusions" do + it 'should process model exclusions' do Apartment::Tenant.init - expect(Company.table_name).to eq("public.companies") + expect(Company.table_name).to eq('public.companies') end - context "with a default_schema", :default_schema => true do - it "should set the proper table_name on excluded_models" do + context 'with a default_schema', default_schema: true do + it 'should set the proper table_name on excluded_models' do Apartment::Tenant.init expect(Company.table_name).to eq("#{default_schema}.companies") @@ -43,10 +45,10 @@ end end - context "persistent_schemas", :persistent_schemas => true do - it "sets the persistent schemas in the schema_search_path" do + context 'persistent_schemas', persistent_schemas: true do + it 'sets the persistent schemas in the schema_search_path' do Apartment::Tenant.init - expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %{"#{schema}"} }.join(', ') + expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %("#{schema}") }.join(', ') end end end @@ -54,31 +56,31 @@ # # Creates happen already in our before_filter # - describe "#create" do - it "should load schema.rb to new schema" do + describe '#create' do + it 'should load schema.rb to new schema' do connection.schema_search_path = schema1 expect(connection.tables).to include('companies') end - it "should yield to block if passed and reset" do + it 'should yield to block if passed and reset' do subject.drop(schema2) # so we don't get errors on creation @count = 0 # set our variable so its visible in and outside of blocks subject.create(schema2) do @count = User.count - expect(connection.schema_search_path).to start_with %{"#{schema2}"} + expect(connection.schema_search_path).to start_with %("#{schema2}") User.create end - expect(connection.schema_search_path).not_to start_with %{"#{schema2}"} + expect(connection.schema_search_path).not_to start_with %("#{schema2}") subject.switch(schema2) { expect(User.count).to eq(@count + 1) } end - context "numeric database names" do + context 'numeric database names' do let(:db) { 1234 } - it "should allow them" do + it 'should allow them' do expect { subject.create(db) }.to_not raise_error @@ -89,17 +91,17 @@ end end - describe "#drop" do - it "should raise an error for unknown database" do + describe '#drop' do + it 'should raise an error for unknown database' do expect { - subject.drop "unknown_database" + subject.drop 'unknown_database' }.to raise_error(Apartment::TenantNotFound) end - context "numeric database names" do + context 'numeric database names' do let(:db) { 1234 } - it "should be able to drop them" do + it 'should be able to drop them' do subject.create(db) expect { subject.drop(db) @@ -117,117 +119,117 @@ end end - describe "#switch" do - it "connects and resets" do + describe '#switch' do + it 'connects and resets' do subject.switch(schema1) do - expect(connection.schema_search_path).to start_with %{"#{schema1}"} + expect(connection.schema_search_path).to start_with %("#{schema1}") end - expect(connection.schema_search_path).to start_with %{"#{public_schema}"} + expect(connection.schema_search_path).to start_with %("#{public_schema}") end end - describe "#reset" do - it "should reset connection" do + describe '#reset' do + it 'should reset connection' do subject.switch!(schema1) subject.reset - expect(connection.schema_search_path).to start_with %{"#{public_schema}"} + expect(connection.schema_search_path).to start_with %("#{public_schema}") end - context "with default_schema", :default_schema => true do - it "should reset to the default schema" do + context 'with default_schema', default_schema: true do + it 'should reset to the default schema' do subject.switch!(schema1) subject.reset - expect(connection.schema_search_path).to start_with %{"#{default_schema}"} + expect(connection.schema_search_path).to start_with %("#{default_schema}") end end - context "persistent_schemas", :persistent_schemas => true do + context 'persistent_schemas', persistent_schemas: true do before do subject.switch!(schema1) subject.reset end - it "maintains the persistent schemas in the schema_search_path" do - expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %{"#{schema}"} }.join(', ') + it 'maintains the persistent schemas in the schema_search_path' do + expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %("#{schema}") }.join(', ') end - context "with default_schema", :default_schema => true do - it "prioritizes the switched schema to front of schema_search_path" do + context 'with default_schema', default_schema: true do + it 'prioritizes the switched schema to front of schema_search_path' do subject.reset # need to re-call this as the default_schema wasn't set at the time that the above reset ran - expect(connection.schema_search_path).to start_with %{"#{default_schema}"} + expect(connection.schema_search_path).to start_with %("#{default_schema}") end end end end - describe "#switch!" do - it "should connect to new schema" do + describe '#switch!' do + it 'should connect to new schema' do subject.switch!(schema1) - expect(connection.schema_search_path).to start_with %{"#{schema1}"} + expect(connection.schema_search_path).to start_with %("#{schema1}") end - it "should reset connection if database is nil" do + it 'should reset connection if database is nil' do subject.switch! - expect(connection.schema_search_path).to eq(%{"#{public_schema}"}) + expect(connection.schema_search_path).to eq(%("#{public_schema}")) end - it "should raise an error if schema is invalid" do + it 'should raise an error if schema is invalid' do expect { subject.switch! 'unknown_schema' }.to raise_error(Apartment::TenantNotFound) end - context "numeric databases" do + context 'numeric databases' do let(:db) { 1234 } - it "should connect to them" do + it 'should connect to them' do subject.create(db) expect { subject.switch!(db) }.to_not raise_error - expect(connection.schema_search_path).to start_with %{"#{db.to_s}"} + expect(connection.schema_search_path).to start_with %("#{db}") end after { subject.drop(db) } end - describe "with default_schema specified", :default_schema => true do + describe 'with default_schema specified', default_schema: true do before do subject.switch!(schema1) end - it "should switch out the default schema rather than public" do + it 'should switch out the default schema rather than public' do expect(connection.schema_search_path).not_to include default_schema end - it "should still switch to the switched schema" do - expect(connection.schema_search_path).to start_with %{"#{schema1}"} + it 'should still switch to the switched schema' do + expect(connection.schema_search_path).to start_with %("#{schema1}") end end - context "persistent_schemas", :persistent_schemas => true do + context 'persistent_schemas', persistent_schemas: true do before { subject.switch!(schema1) } - it "maintains the persistent schemas in the schema_search_path" do - expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %{"#{schema}"} }.join(', ') + it 'maintains the persistent schemas in the schema_search_path' do + expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %("#{schema}") }.join(', ') end - it "prioritizes the switched schema to front of schema_search_path" do - expect(connection.schema_search_path).to start_with %{"#{schema1}"} + it 'prioritizes the switched schema to front of schema_search_path' do + expect(connection.schema_search_path).to start_with %("#{schema1}") end end end - describe "#current" do - it "should return the current schema name" do + describe '#current' do + it 'should return the current schema name' do subject.switch!(schema1) expect(subject.current).to eq(schema1) end - context "persistent_schemas", :persistent_schemas => true do - it "should exlude persistent_schemas" do + context 'persistent_schemas', persistent_schemas: true do + it 'should exlude persistent_schemas' do subject.switch!(schema1) expect(subject.current).to eq(schema1) end diff --git a/spec/integration/apartment_rake_integration_spec.rb b/spec/integration/apartment_rake_integration_spec.rb index dc819d4e..fbfd0474 100644 --- a/spec/integration/apartment_rake_integration_spec.rb +++ b/spec/integration/apartment_rake_integration_spec.rb @@ -3,7 +3,7 @@ require 'spec_helper' require 'rake' -describe "apartment rake tasks", database: :postgresql do +describe 'apartment rake tasks', database: :postgresql do before do @rake = Rake::Application.new Rake.application = @rake @@ -19,8 +19,8 @@ Apartment.configure do |config| config.use_schemas = true - config.excluded_models = ["Company"] - config.tenant_names = lambda { Company.pluck(:database) } + config.excluded_models = ['Company'] + config.tenant_names = -> { Company.pluck(:database) } end Apartment::Tenant.reload!(config) @@ -30,7 +30,7 @@ after { Rake.application = nil } - context "with x number of databases" do + context 'with x number of databases' do let(:x) { rand(1..5) } # random number of dbs to create let(:db_names) { x.times.map { Apartment::Test.next_db } } let!(:company_count) { db_names.length } @@ -38,7 +38,7 @@ before do db_names.collect do |db_name| Apartment::Tenant.create(db_name) - Company.create :database => db_name + Company.create database: db_name end end @@ -47,22 +47,22 @@ Company.delete_all end - context "with ActiveRecord below 5.2.0" do + context 'with ActiveRecord below 5.2.0' do before do - allow(ActiveRecord::Migrator).to receive(:migrations_paths) { %w(spec/dummy/db/migrate) } + allow(ActiveRecord::Migrator).to receive(:migrations_paths) { %w[spec/dummy/db/migrate] } allow(Apartment::Migrator).to receive(:activerecord_below_5_2?) { true } end - describe "#migrate" do - it "should migrate all databases" do + describe '#migrate' do + it 'should migrate all databases' do expect(ActiveRecord::Migrator).to receive(:migrate).exactly(company_count).times @rake['apartment:migrate'].invoke end end - describe "#rollback" do - it "should rollback all dbs" do + describe '#rollback' do + it 'should rollback all dbs' do expect(ActiveRecord::Migrator).to receive(:rollback).exactly(company_count).times @rake['apartment:rollback'].invoke @@ -70,15 +70,15 @@ end end - context "with ActiveRecord above or equal to 5.2.0" do + context 'with ActiveRecord above or equal to 5.2.0' do let(:migration_context_double) { double(:migration_context) } before do allow(Apartment::Migrator).to receive(:activerecord_below_5_2?) { false } end - describe "#migrate" do - it "should migrate all databases" do + describe '#migrate' do + it 'should migrate all databases' do allow(ActiveRecord::Base.connection).to receive(:migration_context) { migration_context_double } expect(migration_context_double).to receive(:migrate).exactly(company_count).times @@ -86,8 +86,8 @@ end end - describe "#rollback" do - it "should rollback all dbs" do + describe '#rollback' do + it 'should rollback all dbs' do allow(ActiveRecord::Base.connection).to receive(:migration_context) { migration_context_double } expect(migration_context_double).to receive(:rollback).exactly(company_count).times @@ -96,8 +96,8 @@ end end - describe "apartment:seed" do - it "should seed all databases" do + describe 'apartment:seed' do + it 'should seed all databases' do expect(Apartment::Tenant).to receive(:seed).exactly(company_count).times @rake['apartment:seed'].invoke diff --git a/spec/integration/query_caching_spec.rb b/spec/integration/query_caching_spec.rb index 10cbaa97..29a5fa8e 100644 --- a/spec/integration/query_caching_spec.rb +++ b/spec/integration/query_caching_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'query caching' do @@ -6,8 +8,8 @@ before do Apartment.configure do |config| - config.excluded_models = ["Company"] - config.tenant_names = lambda { Company.pluck(:database) } + config.excluded_models = ['Company'] + config.tenant_names = -> { Company.pluck(:database) } config.use_schemas = true end @@ -46,8 +48,8 @@ before do Apartment.configure do |config| - config.excluded_models = ["Company"] - config.tenant_names = lambda { Company.pluck(:database) } + config.excluded_models = ['Company'] + config.tenant_names = -> { Company.pluck(:database) } config.use_schemas = false end @@ -66,7 +68,7 @@ Company.delete_all end - it "configuration value is kept after switching databases" do + it 'configuration value is kept after switching databases' do ActiveRecord::Base.connection.enable_query_cache! Apartment::Tenant.switch! db_name diff --git a/spec/integration/use_within_an_engine_spec.rb b/spec/integration/use_within_an_engine_spec.rb index 0e4cfa16..d9592108 100644 --- a/spec/integration/use_within_an_engine_spec.rb +++ b/spec/integration/use_within_an_engine_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + describe 'using apartment within an engine' do before do engine_path = Pathname.new(File.expand_path('../../dummy_engine', __FILE__)) diff --git a/spec/schemas/v1.rb b/spec/schemas/v1.rb index e5f626c9..052f5663 100644 --- a/spec/schemas/v1.rb +++ b/spec/schemas/v1.rb @@ -1,4 +1,4 @@ -# encoding: UTF-8 +# frozen_string_literal: true # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. @@ -11,5 +11,5 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 0) do +ActiveRecord::Schema.define(version: 0) do end diff --git a/spec/schemas/v2.rb b/spec/schemas/v2.rb index 7ace165b..baf7b998 100644 --- a/spec/schemas/v2.rb +++ b/spec/schemas/v2.rb @@ -1,4 +1,4 @@ -# encoding: UTF-8 +# frozen_string_literal: true # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. @@ -11,31 +11,31 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20110613152810) do - create_table "companies", :force => true do |t| - t.boolean "dummy" - t.string "database" +ActiveRecord::Schema.define(version: 20110613152810) do + create_table 'companies', force: true do |t| + t.boolean 'dummy' + t.string 'database' end - create_table "delayed_jobs", :force => true do |t| - t.integer "priority", :default => 0 - t.integer "attempts", :default => 0 - t.text "handler" - t.text "last_error" - t.datetime "run_at" - t.datetime "locked_at" - t.datetime "failed_at" - t.string "locked_by" - t.datetime "created_at" - t.datetime "updated_at" - t.string "queue" + create_table 'delayed_jobs', force: true do |t| + t.integer 'priority', default: 0 + t.integer 'attempts', default: 0 + t.text 'handler' + t.text 'last_error' + t.datetime 'run_at' + t.datetime 'locked_at' + t.datetime 'failed_at' + t.string 'locked_by' + t.datetime 'created_at' + t.datetime 'updated_at' + t.string 'queue' end - add_index "delayed_jobs", ["priority", "run_at"], :name => "delayed_jobs_priority" + add_index 'delayed_jobs', ['priority', 'run_at'], name: 'delayed_jobs_priority' - create_table "users", :force => true do |t| - t.string "name" - t.datetime "birthdate" - t.string "sex" + create_table 'users', force: true do |t| + t.string 'name' + t.datetime 'birthdate' + t.string 'sex' end end diff --git a/spec/schemas/v3.rb b/spec/schemas/v3.rb index 7d97bdeb..2cd09a57 100644 --- a/spec/schemas/v3.rb +++ b/spec/schemas/v3.rb @@ -1,4 +1,4 @@ -# encoding: UTF-8 +# frozen_string_literal: true # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. @@ -11,37 +11,37 @@ # # It's strongly recommended to check this file into your version control system. -ActiveRecord::Schema.define(:version => 20111202022214) do - create_table "books", :force => true do |t| - t.string "name" - t.integer "pages" - t.datetime "published" +ActiveRecord::Schema.define(version: 20111202022214) do + create_table 'books', force: true do |t| + t.string 'name' + t.integer 'pages' + t.datetime 'published' end - create_table "companies", :force => true do |t| - t.boolean "dummy" - t.string "database" + create_table 'companies', force: true do |t| + t.boolean 'dummy' + t.string 'database' end - create_table "delayed_jobs", :force => true do |t| - t.integer "priority", :default => 0 - t.integer "attempts", :default => 0 - t.text "handler" - t.text "last_error" - t.datetime "run_at" - t.datetime "locked_at" - t.datetime "failed_at" - t.string "locked_by" - t.datetime "created_at" - t.datetime "updated_at" - t.string "queue" + create_table 'delayed_jobs', force: true do |t| + t.integer 'priority', default: 0 + t.integer 'attempts', default: 0 + t.text 'handler' + t.text 'last_error' + t.datetime 'run_at' + t.datetime 'locked_at' + t.datetime 'failed_at' + t.string 'locked_by' + t.datetime 'created_at' + t.datetime 'updated_at' + t.string 'queue' end - add_index "delayed_jobs", ["priority", "run_at"], :name => "delayed_jobs_priority" + add_index 'delayed_jobs', ['priority', 'run_at'], name: 'delayed_jobs_priority' - create_table "users", :force => true do |t| - t.string "name" - t.datetime "birthdate" - t.string "sex" + create_table 'users', force: true do |t| + t.string 'name' + t.datetime 'birthdate' + t.string 'sex' end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 9fa79b79..e16b2af8 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + $LOAD_PATH.unshift(File.dirname(__FILE__)) # Configure Rails Environment -ENV["RAILS_ENV"] = "test" +ENV['RAILS_ENV'] = 'test' -require File.expand_path("../dummy/config/environment.rb", __FILE__) +require File.expand_path('../dummy/config/environment.rb', __FILE__) # Loading dummy applications affects table_name of each excluded models # defined in `spec/dummy/config/initializers/apartment.rb`. @@ -16,7 +18,7 @@ klass.reset_table_name end -require "rspec/rails" +require 'rspec/rails' require 'capybara/rspec' require 'capybara/rails' @@ -24,11 +26,12 @@ require 'pry' silence_warnings { IRB = Pry } rescue LoadError + nil end ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true -ActionMailer::Base.default_url_options[:host] = "test.com" +ActionMailer::Base.default_url_options[:host] = 'test.com' Rails.backtrace_cleaner.remove_silencers! diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 1802d49b..485143ac 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment module Test # rubocop:disable Style/ModuleFunction @@ -13,7 +15,7 @@ def reset def next_db @x ||= 0 - "db%d" % @x += 1 + 'db%d' % @x += 1 end def drop_schema(schema) diff --git a/spec/support/capybara_sessions.rb b/spec/support/capybara_sessions.rb index f9aef29a..61c3d8f2 100644 --- a/spec/support/capybara_sessions.rb +++ b/spec/support/capybara_sessions.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module RSpec module Integration module CapybaraSessions diff --git a/spec/support/config.rb b/spec/support/config.rb index 2111641a..f4c46c7a 100644 --- a/spec/support/config.rb +++ b/spec/support/config.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'yaml' module Apartment diff --git a/spec/support/contexts.rb b/spec/support/contexts.rb index 2e95ffe4..9c63f0a1 100644 --- a/spec/support/contexts.rb +++ b/spec/support/contexts.rb @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # Some shared contexts for specs -shared_context "with default schema", :default_schema => true do +shared_context 'with default schema', default_schema: true do let(:default_schema) { Apartment::Test.next_db } before do @@ -16,7 +18,7 @@ end # Some default setup for elevator specs -shared_context "elevators", elevator: true do +shared_context 'elevators', elevator: true do let(:company1) { mock_model(Company, database: db1).as_null_object } let(:company2) { mock_model(Company, database: db2).as_null_object } @@ -37,7 +39,7 @@ end end -shared_context "persistent_schemas", :persistent_schemas => true do +shared_context 'persistent_schemas', persistent_schemas: true do let(:persistent_schemas) { %w[hstore postgis] } before do diff --git a/spec/support/requirements.rb b/spec/support/requirements.rb index 4481fca7..cbfbe5ea 100644 --- a/spec/support/requirements.rb +++ b/spec/support/requirements.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment module Spec # @@ -34,7 +36,7 @@ module AdapterRequirements end end - %w{subject tenant_names default_tenant}.each do |method| + %w[subject tenant_names default_tenant].each do |method| define_method method do raise "You must define a `#{method}` method in your host group" end unless defined?(method) diff --git a/spec/support/setup.rb b/spec/support/setup.rb index e9630dd8..ef650383 100644 --- a/spec/support/setup.rb +++ b/spec/support/setup.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + module Apartment module Spec module Setup diff --git a/spec/tasks/apartment_rake_spec.rb b/spec/tasks/apartment_rake_spec.rb index 2d799b32..451517b8 100644 --- a/spec/tasks/apartment_rake_spec.rb +++ b/spec/tasks/apartment_rake_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'spec_helper' require 'rake' require 'apartment/migrator' require 'apartment/tenant' -describe "apartment rake tasks" do +describe 'apartment rake tasks' do before do @rake = Rake::Application.new Rake.application = @rake @@ -36,84 +38,84 @@ allow(Apartment).to receive(:tenant_names).and_return tenant_names end - describe "apartment:migrate" do + describe 'apartment:migrate' do before do allow(ActiveRecord::Migrator).to receive(:migrate) # don't care about this end - it "should migrate public and all multi-tenant dbs" do + it 'should migrate public and all multi-tenant dbs' do expect(Apartment::Migrator).to receive(:migrate).exactly(tenant_count).times @rake['apartment:migrate'].invoke end end - describe "apartment:migrate:up" do - context "without a version" do + describe 'apartment:migrate:up' do + context 'without a version' do before do ENV['VERSION'] = nil end - it "requires a version to migrate to" do + it 'requires a version to migrate to' do expect { @rake['apartment:migrate:up'].invoke - }.to raise_error("VERSION is required") + }.to raise_error('VERSION is required') end end - context "with version" do + context 'with version' do before do ENV['VERSION'] = version end - it "migrates up to a specific version" do + it 'migrates up to a specific version' do expect(Apartment::Migrator).to receive(:run).with(:up, anything, version.to_i).exactly(tenant_count).times @rake['apartment:migrate:up'].invoke end end end - describe "apartment:migrate:down" do - context "without a version" do + describe 'apartment:migrate:down' do + context 'without a version' do before do ENV['VERSION'] = nil end - it "requires a version to migrate to" do + it 'requires a version to migrate to' do expect { @rake['apartment:migrate:down'].invoke - }.to raise_error("VERSION is required") + }.to raise_error('VERSION is required') end end - context "with version" do + context 'with version' do before do ENV['VERSION'] = version end - it "migrates up to a specific version" do + it 'migrates up to a specific version' do expect(Apartment::Migrator).to receive(:run).with(:down, anything, version.to_i).exactly(tenant_count).times @rake['apartment:migrate:down'].invoke end end end - describe "apartment:rollback" do + describe 'apartment:rollback' do let(:step) { '3' } - it "should rollback dbs" do + it 'should rollback dbs' do expect(Apartment::Migrator).to receive(:rollback).exactly(tenant_count).times @rake['apartment:rollback'].invoke end - it "should rollback dbs STEP amt" do + it 'should rollback dbs STEP amt' do expect(Apartment::Migrator).to receive(:rollback).with(anything, step.to_i).exactly(tenant_count).times ENV['STEP'] = step @rake['apartment:rollback'].invoke end end - describe "apartment:drop" do - it "should migrate public and all multi-tenant dbs" do + describe 'apartment:drop' do + it 'should migrate public and all multi-tenant dbs' do expect(Apartment::Tenant).to receive(:drop).exactly(tenant_count).times @rake['apartment:drop'].invoke end diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index 1fdfd88b..d98325ec 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' describe Apartment::Tenant do - context "using mysql", database: :mysql do + context 'using mysql', database: :mysql do before { subject.reload!(config) } - describe "#adapter" do - it "should load mysql adapter" do + describe '#adapter' do + it 'should load mysql adapter' do subject.adapter expect(Apartment::Adapters::Mysql2Adapter).to be_a(Class) end @@ -13,7 +15,7 @@ # TODO this doesn't belong here, but there aren't integration tests currently for mysql # where to put??? - describe "exception recovery", :type => :request do + describe 'exception recovery', type: :request do before do subject.create db1 end @@ -30,8 +32,8 @@ end # TODO re-organize these tests - context "with prefix and schemas" do - describe "#create" do + context 'with prefix and schemas' do + describe '#create' do before do Apartment.configure do |config| config.prepend_environment = true @@ -43,31 +45,31 @@ after do begin - subject.drop "db_with_prefix" + subject.drop 'db_with_prefix' rescue StandardError => _e nil end end - it "should create a new database" do - subject.create "db_with_prefix" + it 'should create a new database' do + subject.create 'db_with_prefix' end end end end - context "using postgresql", database: :postgresql do + context 'using postgresql', database: :postgresql do before do Apartment.use_schemas = true subject.reload!(config) end - describe "#adapter" do - it "should load postgresql adapter" do + describe '#adapter' do + it 'should load postgresql adapter' do expect(subject.adapter).to be_a(Apartment::Adapters::PostgresqlSchemaAdapter) end - it "raises exception with invalid adapter specified" do + it 'raises exception with invalid adapter specified' do subject.reload!(config.merge(adapter: 'unknown')) expect { @@ -75,7 +77,7 @@ }.to raise_error(RuntimeError) end - context "threadsafety" do + context 'threadsafety' do before { subject.create db1 } after { subject.drop db1 } @@ -89,7 +91,7 @@ end # TODO above spec are also with use_schemas=true - context "with schemas" do + context 'with schemas' do before do Apartment.configure do |config| config.excluded_models = [] @@ -101,21 +103,21 @@ after { subject.drop db1 } - describe "#create" do - it "should seed data" do + describe '#create' do + it 'should seed data' do subject.switch! db1 expect(User.count).to be > 0 end end - describe "#switch!" do + describe '#switch!' do let(:x) { rand(3) } - context "creating models" do + context 'creating models' do before { subject.create db2 } after { subject.drop db2 } - it "should create a model instance in the current schema" do + it 'should create a model instance in the current schema' do subject.switch! db2 db2_count = User.count + x.times { User.create } @@ -130,10 +132,10 @@ end end - context "with excluded models" do + context 'with excluded models' do before do Apartment.configure do |config| - config.excluded_models = ["Company"] + config.excluded_models = ['Company'] end subject.init end @@ -146,7 +148,7 @@ end end - it "should create excluded models in public schema" do + it 'should create excluded models in public schema' do subject.reset # ensure we're on public schema count = Company.count + x.times { Company.create } @@ -160,7 +162,7 @@ end end - context "seed paths" do + context 'seed paths' do before do Apartment.configure do |config| config.excluded_models = [] @@ -180,7 +182,7 @@ it 'should seed from custom path' do Apartment.configure do |config| - config.seed_data_file = "#{Rails.root}/db/seeds/import.rb" + config.seed_data_file = Rails.root.join('db', 'seeds', 'import.rb') end subject.create db1 subject.switch! db1 diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index 010316ee..cceaa7e4 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + require 'spec_helper' describe Apartment do - describe "#config" do - let(:excluded_models) { ["Company"] } - let(:seed_data_file_path) { "#{Rails.root}/db/seeds/import.rb" } + describe '#config' do + let(:excluded_models) { ['Company'] } + let(:seed_data_file_path) { Rails.root.join('db', 'seeds', 'import.rb') } def tenant_names_from_array(names) names.each_with_object({}) do |tenant, hash| @@ -11,21 +13,21 @@ def tenant_names_from_array(names) end.with_indifferent_access end - it "should yield the Apartment object" do + it 'should yield the Apartment object' do Apartment.configure do |config| config.excluded_models = [] expect(config).to eq(Apartment) end end - it "should set excluded models" do + it 'should set excluded models' do Apartment.configure do |config| config.excluded_models = excluded_models end expect(Apartment.excluded_models).to eq(excluded_models) end - it "should set use_schemas" do + it 'should set use_schemas' do Apartment.configure do |config| config.excluded_models = [] config.use_schemas = false @@ -33,14 +35,14 @@ def tenant_names_from_array(names) expect(Apartment.use_schemas).to be false end - it "should set seed_data_file" do + it 'should set seed_data_file' do Apartment.configure do |config| config.seed_data_file = seed_data_file_path end expect(Apartment.seed_data_file).to eq(seed_data_file_path) end - it "should set seed_after_create" do + it 'should set seed_after_create' do Apartment.configure do |config| config.excluded_models = [] config.seed_after_create = true @@ -48,7 +50,7 @@ def tenant_names_from_array(names) expect(Apartment.seed_after_create).to be true end - context "databases" do + context 'databases' do let(:users_conf_hash) { { port: 5444 } } before do @@ -57,50 +59,50 @@ def tenant_names_from_array(names) end end - context "tenant_names as string array" do + context 'tenant_names as string array' do let(:tenant_names) { %w[users companies] } - it "should return object if it doesnt respond_to call" do + it 'should return object if it doesnt respond_to call' do expect(Apartment.tenant_names).to eq(tenant_names_from_array(tenant_names).keys) end - it "should set tenants_with_config" do + it 'should set tenants_with_config' do expect(Apartment.tenants_with_config).to eq(tenant_names_from_array(tenant_names)) end end - context "tenant_names as proc returning an array" do - let(:tenant_names) { lambda { %w[users companies] } } + context 'tenant_names as proc returning an array' do + let(:tenant_names) { -> { %w[users companies] } } - it "should return object if it doesnt respond_to call" do + it 'should return object if it doesnt respond_to call' do expect(Apartment.tenant_names).to eq(tenant_names_from_array(tenant_names.call).keys) end - it "should set tenants_with_config" do + it 'should set tenants_with_config' do expect(Apartment.tenants_with_config).to eq(tenant_names_from_array(tenant_names.call)) end end - context "tenant_names as Hash" do + context 'tenant_names as Hash' do let(:tenant_names) { { users: users_conf_hash }.with_indifferent_access } - it "should return object if it doesnt respond_to call" do + it 'should return object if it doesnt respond_to call' do expect(Apartment.tenant_names).to eq(tenant_names.keys) end - it "should set tenants_with_config" do + it 'should set tenants_with_config' do expect(Apartment.tenants_with_config).to eq(tenant_names) end end - context "tenant_names as proc returning a Hash" do - let(:tenant_names) { lambda { { users: users_conf_hash }.with_indifferent_access } } + context 'tenant_names as proc returning a Hash' do + let(:tenant_names) { -> { { users: users_conf_hash }.with_indifferent_access } } - it "should return object if it doesnt respond_to call" do + it 'should return object if it doesnt respond_to call' do expect(Apartment.tenant_names).to eq(tenant_names.call.keys) end - it "should set tenants_with_config" do + it 'should set tenants_with_config' do expect(Apartment.tenants_with_config).to eq(tenant_names.call) end end diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index 5970e2d4..fc0ade75 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/domain' describe Apartment::Elevators::Domain do subject(:elevator) { described_class.new(proc) } - describe "#parse_tenant_name" do - it "parses the host for a domain name" do + describe '#parse_tenant_name' do + it 'parses the host for a domain name' do request = ActionDispatch::Request.new('HTTP_HOST' => 'example.com') expect(elevator.parse_tenant_name(request)).to eq('example') end - it "ignores a www prefix and domain suffix" do + it 'ignores a www prefix and domain suffix' do request = ActionDispatch::Request.new('HTTP_HOST' => 'www.example.bc.ca') expect(elevator.parse_tenant_name(request)).to eq('example') end - it "returns nil if there is no host" do + it 'returns nil if there is no host' do request = ActionDispatch::Request.new('HTTP_HOST' => '') expect(elevator.parse_tenant_name(request)).to be_nil end end - describe "#call" do - it "switches to the proper tenant" do + describe '#call' do + it 'switches to the proper tenant' do expect(Apartment::Tenant).to receive(:switch).with('example') elevator.call('HTTP_HOST' => 'www.example.com') diff --git a/spec/unit/elevators/first_subdomain_spec.rb b/spec/unit/elevators/first_subdomain_spec.rb index 837cb3b3..f608d834 100644 --- a/spec/unit/elevators/first_subdomain_spec.rb +++ b/spec/unit/elevators/first_subdomain_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/first_subdomain' describe Apartment::Elevators::FirstSubdomain do - describe "subdomain" do - subject { described_class.new("test").parse_tenant_name(request) } - let(:request) { double(:request, :host => "#{subdomain}.example.com") } + describe 'subdomain' do + subject { described_class.new('test').parse_tenant_name(request) } + let(:request) { double(:request, host: "#{subdomain}.example.com") } - context "one subdomain" do - let(:subdomain) { "test" } - it { is_expected.to eq("test") } + context 'one subdomain' do + let(:subdomain) { 'test' } + it { is_expected.to eq('test') } end - context "nested subdomains" do - let(:subdomain) { "test1.test2" } - it { is_expected.to eq("test1") } + context 'nested subdomains' do + let(:subdomain) { 'test1.test2' } + it { is_expected.to eq('test1') } end - context "no subdomain" do + context 'no subdomain' do let(:subdomain) { nil } it { is_expected.to eq(nil) } end diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index 9bbe1ad0..1b12044a 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/generic' @@ -10,8 +12,8 @@ def parse_tenant_name(*) subject(:elevator) { described_class.new(proc) } - describe "#call" do - it "calls the processor if given" do + describe '#call' do + it 'calls the processor if given' do elevator = described_class.new(proc {}, proc { 'tenant1' }) expect(Apartment::Tenant).to receive(:switch).with('tenant1') @@ -19,13 +21,13 @@ def parse_tenant_name(*) elevator.call('HTTP_HOST' => 'foo.bar.com') end - it "raises if parse_tenant_name not implemented" do + it 'raises if parse_tenant_name not implemented' do expect { elevator.call('HTTP_HOST' => 'foo.bar.com') }.to raise_error(RuntimeError) end - it "switches to the parsed db_name" do + it 'switches to the parsed db_name' do elevator = MyElevator.new(proc {}) expect(Apartment::Tenant).to receive(:switch).with('tenant2') @@ -33,14 +35,14 @@ def parse_tenant_name(*) elevator.call('HTTP_HOST' => 'foo.bar.com') end - it "calls the block implementation of `switch`" do + it 'calls the block implementation of `switch`' do elevator = MyElevator.new(proc {}, proc { 'tenant2' }) expect(Apartment::Tenant).to receive(:switch).with('tenant2').and_yield elevator.call('HTTP_HOST' => 'foo.bar.com') end - it "does not call `switch` if no database given" do + it 'does not call `switch` if no database given' do app = proc {} elevator = MyElevator.new(app, proc {}) diff --git a/spec/unit/elevators/host_hash_spec.rb b/spec/unit/elevators/host_hash_spec.rb index 8a8dc344..6fc2f72b 100644 --- a/spec/unit/elevators/host_hash_spec.rb +++ b/spec/unit/elevators/host_hash_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/host_hash' describe Apartment::Elevators::HostHash do subject(:elevator) { Apartment::Elevators::HostHash.new(proc {}, 'example.com' => 'example_tenant') } - describe "#parse_tenant_name" do - it "parses the host for a domain name" do + describe '#parse_tenant_name' do + it 'parses the host for a domain name' do request = ActionDispatch::Request.new('HTTP_HOST' => 'example.com') expect(elevator.parse_tenant_name(request)).to eq('example_tenant') end - it "raises TenantNotFound exception if there is no host" do + it 'raises TenantNotFound exception if there is no host' do request = ActionDispatch::Request.new('HTTP_HOST' => '') expect { elevator.parse_tenant_name(request) }.to raise_error(Apartment::TenantNotFound) end - it "raises TenantNotFound exception if there is no database associated to current host" do + it 'raises TenantNotFound exception if there is no database associated to current host' do request = ActionDispatch::Request.new('HTTP_HOST' => 'example2.com') expect { elevator.parse_tenant_name(request) }.to raise_error(Apartment::TenantNotFound) end end - describe "#call" do - it "switches to the proper tenant" do + describe '#call' do + it 'switches to the proper tenant' do expect(Apartment::Tenant).to receive(:switch).with('example_tenant') elevator.call('HTTP_HOST' => 'example.com') diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index 6338ef32..f480cbbb 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -1,85 +1,87 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/host' describe Apartment::Elevators::Host do subject(:elevator) { described_class.new(proc) } - describe "#parse_tenant_name" do - it "should return nil when no host" do + describe '#parse_tenant_name' do + it 'should return nil when no host' do request = ActionDispatch::Request.new('HTTP_HOST' => '') expect(elevator.parse_tenant_name(request)).to be_nil end - context "assuming no ignored_first_subdomains" do + context 'assuming no ignored_first_subdomains' do before { allow(described_class).to receive(:ignored_first_subdomains).and_return([]) } - context "with 3 parts" do - it "should return the whole host" do + context 'with 3 parts' do + it 'should return the whole host' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.bar.com') expect(elevator.parse_tenant_name(request)).to eq('foo.bar.com') end end - context "with 6 parts" do - it "should return the whole host" do + context 'with 6 parts' do + it 'should return the whole host' do request = ActionDispatch::Request.new('HTTP_HOST' => 'one.two.three.foo.bar.com') expect(elevator.parse_tenant_name(request)).to eq('one.two.three.foo.bar.com') end end end - context "assuming ignored_first_subdomains is set" do - before { allow(described_class).to receive(:ignored_first_subdomains).and_return(%w{www foo}) } + context 'assuming ignored_first_subdomains is set' do + before { allow(described_class).to receive(:ignored_first_subdomains).and_return(%w[www foo]) } - context "with 3 parts" do - it "should return host without www" do + context 'with 3 parts' do + it 'should return host without www' do request = ActionDispatch::Request.new('HTTP_HOST' => 'www.bar.com') expect(elevator.parse_tenant_name(request)).to eq('bar.com') end - it "should return host without foo" do + it 'should return host without foo' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.bar.com') expect(elevator.parse_tenant_name(request)).to eq('bar.com') end end - context "with 6 parts" do - it "should return host without www" do + context 'with 6 parts' do + it 'should return host without www' do request = ActionDispatch::Request.new('HTTP_HOST' => 'www.one.two.three.foo.bar.com') expect(elevator.parse_tenant_name(request)).to eq('one.two.three.foo.bar.com') end - it "should return host without www" do + it 'should return host without www' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.one.two.three.bar.com') expect(elevator.parse_tenant_name(request)).to eq('one.two.three.bar.com') end end end - context "assuming localhost" do - it "should return localhost" do + context 'assuming localhost' do + it 'should return localhost' do request = ActionDispatch::Request.new('HTTP_HOST' => 'localhost') expect(elevator.parse_tenant_name(request)).to eq('localhost') end end - context "assuming ip address" do - it "should return the ip address" do + context 'assuming ip address' do + it 'should return the ip address' do request = ActionDispatch::Request.new('HTTP_HOST' => '127.0.0.1') expect(elevator.parse_tenant_name(request)).to eq('127.0.0.1') end end end - describe "#call" do - it "switches to the proper tenant" do + describe '#call' do + it 'switches to the proper tenant' do allow(described_class).to receive(:ignored_first_subdomains).and_return([]) expect(Apartment::Tenant).to receive(:switch).with('foo.bar.com') elevator.call('HTTP_HOST' => 'foo.bar.com') end - it "ignores ignored_first_subdomains" do - allow(described_class).to receive(:ignored_first_subdomains).and_return(%w{foo}) + it 'ignores ignored_first_subdomains' do + allow(described_class).to receive(:ignored_first_subdomains).and_return(%w[foo]) expect(Apartment::Tenant).to receive(:switch).with('bar.com') elevator.call('HTTP_HOST' => 'foo.bar.com') end diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index 87cbc904..42d9c96a 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -1,69 +1,71 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/elevators/subdomain' describe Apartment::Elevators::Subdomain do subject(:elevator) { described_class.new(proc) } - describe "#parse_tenant_name" do - context "assuming one tld" do - it "should parse subdomain" do + describe '#parse_tenant_name' do + context 'assuming one tld' do + it 'should parse subdomain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.bar.com') expect(elevator.parse_tenant_name(request)).to eq('foo') end - it "should return nil when no subdomain" do + it 'should return nil when no subdomain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'bar.com') expect(elevator.parse_tenant_name(request)).to be_nil end end - context "assuming two tlds" do - it "should parse subdomain in the third level domain" do + context 'assuming two tlds' do + it 'should parse subdomain in the third level domain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.bar.co.uk') - expect(elevator.parse_tenant_name(request)).to eq("foo") + expect(elevator.parse_tenant_name(request)).to eq('foo') end - it "should return nil when no subdomain in the third level domain" do + it 'should return nil when no subdomain in the third level domain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'bar.co.uk') expect(elevator.parse_tenant_name(request)).to be_nil end end - context "assuming two subdomains" do - it "should parse two subdomains in the two level domain" do + context 'assuming two subdomains' do + it 'should parse two subdomains in the two level domain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.xyz.bar.com') - expect(elevator.parse_tenant_name(request)).to eq("foo") + expect(elevator.parse_tenant_name(request)).to eq('foo') end - it "should parse two subdomains in the third level domain" do + it 'should parse two subdomains in the third level domain' do request = ActionDispatch::Request.new('HTTP_HOST' => 'foo.xyz.bar.co.uk') - expect(elevator.parse_tenant_name(request)).to eq("foo") + expect(elevator.parse_tenant_name(request)).to eq('foo') end end - context "assuming localhost" do - it "should return nil for localhost" do + context 'assuming localhost' do + it 'should return nil for localhost' do request = ActionDispatch::Request.new('HTTP_HOST' => 'localhost') expect(elevator.parse_tenant_name(request)).to be_nil end end - context "assuming ip address" do - it "should return nil for an ip address" do + context 'assuming ip address' do + it 'should return nil for an ip address' do request = ActionDispatch::Request.new('HTTP_HOST' => '127.0.0.1') expect(elevator.parse_tenant_name(request)).to be_nil end end end - describe "#call" do - it "switches to the proper tenant" do + describe '#call' do + it 'switches to the proper tenant' do expect(Apartment::Tenant).to receive(:switch).with('tenant1') elevator.call('HTTP_HOST' => 'tenant1.example.com') end - it "ignores excluded subdomains" do - described_class.excluded_subdomains = %w{foo} + it 'ignores excluded subdomains' do + described_class.excluded_subdomains = %w[foo] expect(Apartment::Tenant).not_to receive(:switch) diff --git a/spec/unit/migrator_spec.rb b/spec/unit/migrator_spec.rb index dadc1834..8cbcb9e2 100644 --- a/spec/unit/migrator_spec.rb +++ b/spec/unit/migrator_spec.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + require 'spec_helper' require 'apartment/migrator' diff --git a/spec/unit/reloader_spec.rb b/spec/unit/reloader_spec.rb index 312aa129..54bd2ff7 100644 --- a/spec/unit/reloader_spec.rb +++ b/spec/unit/reloader_spec.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + require 'spec_helper' describe Apartment::Reloader do - context "using postgresql schemas" do + context 'using postgresql schemas' do before do Apartment.configure do |config| - config.excluded_models = ["Company"] + config.excluded_models = ['Company'] config.use_schemas = true end Apartment::Tenant.reload!(config) Company.reset_table_name # ensure we're clean end - subject { Apartment::Reloader.new(double("Rack::Application", :call => nil)) } + subject { Apartment::Reloader.new(double('Rack::Application', call: nil)) } - it "should initialize apartment when called" do + it 'should initialize apartment when called' do expect(Company.table_name).not_to include('public.') subject.call(double('env')) expect(Company.table_name).to include('public.') From bacd6188b67744d27f3461cb872e4c3e1ed7e223 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:18:20 +0800 Subject: [PATCH 029/282] WIP - fixed dynamic find by --- .rubocop_todo.yml | 8 -------- spec/integration/query_caching_spec.rb | 4 ++-- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index f397e797..ad509725 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -55,14 +55,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 2 -# Cop supports --auto-correct. -# Configuration parameters: Whitelist. -# Whitelist: find_by_sql -Rails/DynamicFindBy: - Exclude: - - 'spec/integration/query_caching_spec.rb' - # Offense count: 1 # Configuration parameters: Include. # Include: app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb diff --git a/spec/integration/query_caching_spec.rb b/spec/integration/query_caching_spec.rb index 29a5fa8e..6026e5a1 100644 --- a/spec/integration/query_caching_spec.rb +++ b/spec/integration/query_caching_spec.rb @@ -36,10 +36,10 @@ ActiveRecord::Base.connection.enable_query_cache! Apartment::Tenant.switch! db_names.first - expect(User.find_by_name(db_names.first).name).to eq(db_names.first) + expect(User.find_by(name: db_names.first).name).to eq(db_names.first) Apartment::Tenant.switch! db_names.last - expect(User.find_by_name(db_names.first)).to be_nil + expect(User.find_by(name: db_names.first)).to be_nil end end From d2e8248ff0c48f8065c2e6358994c7ca8d569509 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:20:27 +0800 Subject: [PATCH 030/282] WIP - fixed rails output and preferred alias method --- .rubocop_todo.yml | 17 ----------------- lib/apartment.rb | 4 ++-- lib/apartment/adapters/abstract_adapter.rb | 6 +++--- lib/apartment/console.rb | 3 +++ 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ad509725..b22db18e 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -55,29 +55,12 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 1 -# Configuration parameters: Include. -# Include: app/**/*.rb, config/**/*.rb, db/**/*.rb, lib/**/*.rb -Rails/Output: - Exclude: - - '**/rails_helper.rb' - - 'lib/apartment/console.rb' - # Offense count: 1 # Cop supports --auto-correct. Security/YAMLLoad: Exclude: - 'spec/support/config.rb' -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: prefer_alias, prefer_alias_method -Style/Alias: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/abstract_adapter.rb' - # Offense count: 16 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. diff --git a/lib/apartment.rb b/lib/apartment.rb index 0b5f774e..2f1eceb4 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -60,8 +60,8 @@ def default_schema def parallel_migration_threads @parallel_migration_threads || 0 end - alias :default_tenant :default_schema - alias :default_tenant= :default_schema= + alias default_tenant default_schema + alias default_tenant= default_schema= def persistent_schemas @persistent_schemas || [] diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index fe23552f..7598af1b 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -48,7 +48,7 @@ def current def default_tenant @default_tenant || Apartment.default_tenant end - alias :default_schema :default_tenant # TODO deprecate default_schema + alias default_schema default_tenant # TODO deprecate default_schema # Drop the tenant # @@ -121,7 +121,7 @@ def seed_data # Don't log the output of seeding the db silence_warnings { load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file end - alias_method :seed, :seed_data + alias seed seed_data # Prepend the environment if configured and the environment isn't already there # @@ -219,7 +219,7 @@ def load_or_raise(file) end end # Backward compatibility - alias_method :load_or_abort, :load_or_raise + alias load_or_abort load_or_raise # Exceptions to rescue from on db operations # diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index ee1220a8..d5a45d57 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -5,7 +5,10 @@ # reloads the environment def reload!(print = true) + # rubocop:disable Rails/Output puts 'Reloading...' if print + # rubocop:enable Rails/Output + # This triggers the to_prepare callbacks ActionDispatch::Callbacks.new(proc {}).call({}) # Manually init Apartment again once classes are reloaded From 7fc7d339ad3dac4524541d1c8454d7f3bc47965b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:23:39 +0800 Subject: [PATCH 031/282] WIP - sorted gemfiels --- .rubocop_todo.yml | 13 ------------- gemfiles/rails_4_2.gemfile | 6 +++--- gemfiles/rails_5_0.gemfile | 4 ++-- gemfiles/rails_5_1.gemfile | 4 ++-- gemfiles/rails_5_2.gemfile | 4 ++-- gemfiles/rails_6_0.gemfile | 4 ++-- gemfiles/rails_master.gemfile | 4 ++-- 7 files changed, 13 insertions(+), 26 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index b22db18e..b738842e 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -6,19 +6,6 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 13 -# Cop supports --auto-correct. -# Configuration parameters: TreatCommentsAsGroupSeparators, Include. -# Include: **/*.gemfile, **/Gemfile, **/gems.rb -Bundler/OrderedGems: - Exclude: - - 'gemfiles/rails_4_2.gemfile' - - 'gemfiles/rails_5_0.gemfile' - - 'gemfiles/rails_5_1.gemfile' - - 'gemfiles/rails_5_2.gemfile' - - 'gemfiles/rails_6_0.gemfile' - - 'gemfiles/rails_master.gemfile' - # Offense count: 3 # Cop supports --auto-correct. # Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. diff --git a/gemfiles/rails_4_2.gemfile b/gemfiles/rails_4_2.gemfile index acec9a0d..33048072 100644 --- a/gemfiles/rails_4_2.gemfile +++ b/gemfiles/rails_4_2.gemfile @@ -7,19 +7,19 @@ source 'http://rubygems.org' gem 'rails', '~> 4.2.0' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :ruby do - gem 'pg', '< 1.0.0' gem 'mysql2', '~> 0.4.0' + gem 'pg', '< 1.0.0' end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 1.3' - gem 'activerecord-jdbcpostgresql-adapter', '~> 1.3' gem 'activerecord-jdbcmysql-adapter', '~> 1.3' + gem 'activerecord-jdbcpostgresql-adapter', '~> 1.3' end gemspec path: '../' diff --git a/gemfiles/rails_5_0.gemfile b/gemfiles/rails_5_0.gemfile index c1188bc2..3d1c50a4 100644 --- a/gemfiles/rails_5_0.gemfile +++ b/gemfiles/rails_5_0.gemfile @@ -7,8 +7,8 @@ source 'http://rubygems.org' gem 'rails', '~> 5.0.0' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :ruby do @@ -17,8 +17,8 @@ end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 50.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 50.0' gem 'activerecord-jdbcmysql-adapter', '~> 50.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 50.0' end gemspec path: '../' diff --git a/gemfiles/rails_5_1.gemfile b/gemfiles/rails_5_1.gemfile index 3e738bf1..fd285b95 100644 --- a/gemfiles/rails_5_1.gemfile +++ b/gemfiles/rails_5_1.gemfile @@ -7,8 +7,8 @@ source 'http://rubygems.org' gem 'rails', '~> 5.1.0' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :ruby do @@ -17,8 +17,8 @@ end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 51.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 51.0' gem 'activerecord-jdbcmysql-adapter', '~> 51.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 51.0' end gemspec path: '../' diff --git a/gemfiles/rails_5_2.gemfile b/gemfiles/rails_5_2.gemfile index 57d1aac4..fb42246f 100644 --- a/gemfiles/rails_5_2.gemfile +++ b/gemfiles/rails_5_2.gemfile @@ -7,14 +7,14 @@ source 'http://rubygems.org' gem 'rails', '~> 5.2.0' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 52.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' gem 'activerecord-jdbcmysql-adapter', '~> 52.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' end gemspec path: '../' diff --git a/gemfiles/rails_6_0.gemfile b/gemfiles/rails_6_0.gemfile index 58cb5b6e..ec151217 100644 --- a/gemfiles/rails_6_0.gemfile +++ b/gemfiles/rails_6_0.gemfile @@ -7,8 +7,8 @@ source 'http://rubygems.org' gem 'rails', '~> 6.0.0.rc1' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :ruby do @@ -17,8 +17,8 @@ end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 60.0.rc1' - gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0.rc1' gem 'activerecord-jdbcmysql-adapter', '~> 60.0.rc1' + gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0.rc1' end gemspec path: '../' diff --git a/gemfiles/rails_master.gemfile b/gemfiles/rails_master.gemfile index a2eed35f..af85bb04 100644 --- a/gemfiles/rails_master.gemfile +++ b/gemfiles/rails_master.gemfile @@ -7,8 +7,8 @@ source 'http://rubygems.org' gem 'rails', git: 'https://github.com/rails/rails.git' group :local do - gem 'pry' gem 'guard-rspec', '~> 4.2' + gem 'pry' end platforms :ruby do @@ -17,8 +17,8 @@ end platforms :jruby do gem 'activerecord-jdbc-adapter', '~> 52.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' gem 'activerecord-jdbcmysql-adapter', '~> 52.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' end gemspec path: '../' From ea8f97cbf39ab4459a6aeb13f4693d02e2ccc732 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:25:32 +0800 Subject: [PATCH 032/282] WIP - fixed unused argument --- .rubocop_todo.yml | 9 --------- lib/apartment/adapters/abstract_adapter.rb | 2 +- lib/apartment/elevators/generic.rb | 2 +- spec/support/capybara_sessions.rb | 2 +- 4 files changed, 3 insertions(+), 12 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index b738842e..b0913ea8 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -6,15 +6,6 @@ # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. -Lint/UnusedMethodArgument: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/elevators/generic.rb' - - 'spec/support/capybara_sessions.rb' - # Offense count: 5 Metrics/AbcSize: Max: 33 diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 7598af1b..79e49c08 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -237,7 +237,7 @@ def db_connection_config(tenant) Apartment.db_config_for(tenant).clone end - def with_neutral_connection(tenant, &block) + def with_neutral_connection(tenant, &_block) if Apartment.with_multi_server_setup # neutral connection is necessary whenever you need to create/remove a database from a server. # example: when you use postgresql, you need to connect to the default postgresql database before you create your own. diff --git a/lib/apartment/elevators/generic.rb b/lib/apartment/elevators/generic.rb index 8d321aaa..a765486e 100644 --- a/lib/apartment/elevators/generic.rb +++ b/lib/apartment/elevators/generic.rb @@ -25,7 +25,7 @@ def call(env) end end - def parse_tenant_name(request) + def parse_tenant_name(_request) raise 'Override' end end diff --git a/spec/support/capybara_sessions.rb b/spec/support/capybara_sessions.rb index 61c3d8f2..def4985c 100644 --- a/spec/support/capybara_sessions.rb +++ b/spec/support/capybara_sessions.rb @@ -3,7 +3,7 @@ module RSpec module Integration module CapybaraSessions - def in_new_session(&block) + def in_new_session(&_block) yield new_session end From 6c7d1fecd7149acbb7f43ba72d9228d12f7df960 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:26:49 +0800 Subject: [PATCH 033/282] WIP - fixed yaml safe load --- .rubocop_todo.yml | 6 ------ spec/support/config.rb | 2 ++ 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index b0913ea8..ad620566 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,12 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 1 -# Cop supports --auto-correct. -Security/YAMLLoad: - Exclude: - - 'spec/support/config.rb' - # Offense count: 16 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. diff --git a/spec/support/config.rb b/spec/support/config.rb index f4c46c7a..ce91ad1a 100644 --- a/spec/support/config.rb +++ b/spec/support/config.rb @@ -5,7 +5,9 @@ module Apartment module Test def self.config + # rubocop:disable Security/YAMLLoad @config ||= YAML.load(ERB.new(IO.read('spec/config/database.yml')).result) + # rubocop:enable Security/YAMLLoad end end end From 6efd1e52ae95e715b94b63b9949d1fc74e60391a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:27:35 +0800 Subject: [PATCH 034/282] WIP - fixed block delimiters --- .rubocop_todo.yml | 17 ---------------- spec/examples/connection_adapter_examples.rb | 8 ++++---- ...ic_adapter_custom_configuration_example.rb | 4 ++-- spec/examples/generic_adapter_examples.rb | 16 +++++++-------- spec/examples/schema_adapter_examples.rb | 20 +++++++++---------- spec/tasks/apartment_rake_spec.rb | 8 ++++---- spec/tenant_spec.rb | 4 ++-- spec/unit/elevators/generic_spec.rb | 4 ++-- 8 files changed, 32 insertions(+), 49 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index ad620566..460928d9 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,23 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 16 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, IgnoredMethods, AllowBracesOnProceduralOneLiners. -# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces -# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object -# FunctionalMethods: let, let!, subject, watch -# IgnoredMethods: lambda, proc, it -Style/BlockDelimiters: - Exclude: - - 'spec/examples/connection_adapter_examples.rb' - - 'spec/examples/generic_adapter_custom_configuration_example.rb' - - 'spec/examples/generic_adapter_examples.rb' - - 'spec/examples/schema_adapter_examples.rb' - - 'spec/tasks/apartment_rake_spec.rb' - - 'spec/tenant_spec.rb' - - 'spec/unit/elevators/generic_spec.rb' - # Offense count: 5 # Cop supports --auto-correct. # Configuration parameters: Keywords. diff --git a/spec/examples/connection_adapter_examples.rb b/spec/examples/connection_adapter_examples.rb index 033ded4f..973ed1fa 100644 --- a/spec/examples/connection_adapter_examples.rb +++ b/spec/examples/connection_adapter_examples.rb @@ -28,17 +28,17 @@ describe '#drop' do it 'should raise an error for unknown database' do - expect { + expect do subject.drop 'unknown_database' - }.to raise_error(Apartment::TenantNotFound) + end.to raise_error(Apartment::TenantNotFound) end end describe '#switch!' do it 'should raise an error if database is invalid' do - expect { + expect do subject.switch! 'unknown_database' - }.to raise_error(Apartment::TenantNotFound) + end.to raise_error(Apartment::TenantNotFound) end end end diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index a5fece4c..07e2c719 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -45,9 +45,9 @@ end context 'database key from tenant name' do - let(:expected_args) { + let(:expected_args) do custom_db_conf.tap { |args| args.delete(:database) } - } + end describe '#switch!' do it 'should connect to new db' do diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 6da9bd56..252ac47c 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -5,10 +5,10 @@ shared_examples_for 'a generic apartment adapter' do include Apartment::Spec::AdapterRequirements - before { + before do Apartment.prepend_environment = false Apartment.append_environment = false - } + end describe '#init' do it 'should not retain a connection after railtie' do @@ -67,9 +67,9 @@ begin Dir.mktmpdir do |tmpdir| Apartment.database_schema_file = "#{tmpdir}/schema.rb" - expect { + expect do subject.create(db1) - }.to raise_error(Apartment::FileNotFound) + end.to raise_error(Apartment::FileNotFound) end ensure Apartment.remove_instance_variable(:@database_schema_file) @@ -96,9 +96,9 @@ end it 'should raise an error if database is invalid' do - expect { + expect do subject.switch! 'unknown_database' - }.to raise_error(Apartment::ApartmentError) + end.to raise_error(Apartment::ApartmentError) end end @@ -115,9 +115,9 @@ it 'should not throw exception if current is no longer accessible' do subject.switch!(db2) - expect { + expect do subject.switch(db1) { subject.drop(db2) } - }.to_not raise_error + end.to_not raise_error end end diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index c96f7038..d253ced9 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -81,9 +81,9 @@ context 'numeric database names' do let(:db) { 1234 } it 'should allow them' do - expect { + expect do subject.create(db) - }.to_not raise_error + end.to_not raise_error expect(tenant_names).to include(db.to_s) end @@ -93,9 +93,9 @@ describe '#drop' do it 'should raise an error for unknown database' do - expect { + expect do subject.drop 'unknown_database' - }.to raise_error(Apartment::TenantNotFound) + end.to raise_error(Apartment::TenantNotFound) end context 'numeric database names' do @@ -103,9 +103,9 @@ it 'should be able to drop them' do subject.create(db) - expect { + expect do subject.drop(db) - }.to_not raise_error + end.to_not raise_error expect(tenant_names).not_to include(db.to_s) end @@ -175,9 +175,9 @@ end it 'should raise an error if schema is invalid' do - expect { + expect do subject.switch! 'unknown_schema' - }.to raise_error(Apartment::TenantNotFound) + end.to raise_error(Apartment::TenantNotFound) end context 'numeric databases' do @@ -185,9 +185,9 @@ it 'should connect to them' do subject.create(db) - expect { + expect do subject.switch!(db) - }.to_not raise_error + end.to_not raise_error expect(connection.schema_search_path).to start_with %("#{db}") end diff --git a/spec/tasks/apartment_rake_spec.rb b/spec/tasks/apartment_rake_spec.rb index 451517b8..f71727a9 100644 --- a/spec/tasks/apartment_rake_spec.rb +++ b/spec/tasks/apartment_rake_spec.rb @@ -56,9 +56,9 @@ end it 'requires a version to migrate to' do - expect { + expect do @rake['apartment:migrate:up'].invoke - }.to raise_error('VERSION is required') + end.to raise_error('VERSION is required') end end @@ -81,9 +81,9 @@ end it 'requires a version to migrate to' do - expect { + expect do @rake['apartment:migrate:down'].invoke - }.to raise_error('VERSION is required') + end.to raise_error('VERSION is required') end end diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index d98325ec..f2b756b5 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -72,9 +72,9 @@ it 'raises exception with invalid adapter specified' do subject.reload!(config.merge(adapter: 'unknown')) - expect { + expect do Apartment::Tenant.adapter - }.to raise_error(RuntimeError) + end.to raise_error(RuntimeError) end context 'threadsafety' do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index 1b12044a..ae54fca1 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -22,9 +22,9 @@ def parse_tenant_name(*) end it 'raises if parse_tenant_name not implemented' do - expect { + expect do elevator.call('HTTP_HOST' => 'foo.bar.com') - }.to raise_error(RuntimeError) + end.to raise_error(RuntimeError) end it 'switches to the parsed db_name' do From edb6ced566fb5a779dc8866d39964c38193b2bfb Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:29:52 +0800 Subject: [PATCH 035/282] WIP - fixed keyword todo and empty method definition --- .rubocop_todo.yml | 18 ------------------ lib/apartment.rb | 2 +- lib/apartment/adapters/abstract_adapter.rb | 2 +- .../app/controllers/application_controller.rb | 3 +-- spec/tenant_spec.rb | 6 +++--- 5 files changed, 6 insertions(+), 25 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 460928d9..1dc2448e 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,24 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: Keywords. -# Keywords: TODO, FIXME, OPTIMIZE, HACK, REVIEW -Style/CommentAnnotation: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'spec/tenant_spec.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: compact, expanded -Style/EmptyMethod: - Exclude: - - 'spec/dummy/app/controllers/application_controller.rb' - # Offense count: 14 # Cop supports --auto-correct. Style/ExpandPathArguments: diff --git a/lib/apartment.rb b/lib/apartment.rb index 2f1eceb4..ac0e3320 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -54,7 +54,7 @@ def excluded_models end def default_schema - @default_schema || 'public' # TODO 'public' is postgres specific + @default_schema || 'public' # TODO: 'public' is postgres specific end def parallel_migration_threads diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 79e49c08..ced5c69b 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -48,7 +48,7 @@ def current def default_tenant @default_tenant || Apartment.default_tenant end - alias default_schema default_tenant # TODO deprecate default_schema + alias default_schema default_tenant # TODO: deprecate default_schema # Drop the tenant # diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb index bfa2456c..3615e013 100644 --- a/spec/dummy/app/controllers/application_controller.rb +++ b/spec/dummy/app/controllers/application_controller.rb @@ -3,6 +3,5 @@ class ApplicationController < ActionController::Base protect_from_forgery - def index - end + def index; end end diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index f2b756b5..aa32a0ff 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -13,7 +13,7 @@ end end - # TODO this doesn't belong here, but there aren't integration tests currently for mysql + # TODO: this doesn't belong here, but there aren't integration tests currently for mysql # where to put??? describe 'exception recovery', type: :request do before do @@ -31,7 +31,7 @@ # end end - # TODO re-organize these tests + # TODO: re-organize these tests context 'with prefix and schemas' do describe '#create' do before do @@ -90,7 +90,7 @@ end end - # TODO above spec are also with use_schemas=true + # TODO: above spec are also with use_schemas=true context 'with schemas' do before do Apartment.configure do |config| From e6f3e44836133a2f6557f0cf933f4c8243b567af Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:31:01 +0800 Subject: [PATCH 036/282] WIP - fixed expand path --- .rubocop_todo.yml | 16 ---------------- .../apartment/install/install_generator.rb | 2 +- spec/adapters/sqlite3_adapter_spec.rb | 2 +- spec/dummy/config/application.rb | 2 +- spec/dummy/config/boot.rb | 4 ++-- spec/dummy/config/environment.rb | 2 +- spec/dummy/script/rails | 4 ++-- .../test/dummy/config/application.rb | 2 +- spec/dummy_engine/test/dummy/config/boot.rb | 4 ++-- .../test/dummy/config/environment.rb | 2 +- spec/integration/use_within_an_engine_spec.rb | 2 +- spec/spec_helper.rb | 2 +- 12 files changed, 14 insertions(+), 30 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 1dc2448e..e1fcf700 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,22 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 14 -# Cop supports --auto-correct. -Style/ExpandPathArguments: - Exclude: - - 'lib/generators/apartment/install/install_generator.rb' - - 'spec/adapters/sqlite3_adapter_spec.rb' - - 'spec/dummy/config/application.rb' - - 'spec/dummy/config/boot.rb' - - 'spec/dummy/config/environment.rb' - - 'spec/dummy/script/rails' - - 'spec/dummy_engine/test/dummy/config/application.rb' - - 'spec/dummy_engine/test/dummy/config/boot.rb' - - 'spec/dummy_engine/test/dummy/config/environment.rb' - - 'spec/integration/use_within_an_engine_spec.rb' - - 'spec/spec_helper.rb' - # Offense count: 1 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/lib/generators/apartment/install/install_generator.rb b/lib/generators/apartment/install/install_generator.rb index 509cf2e9..9fe7152e 100755 --- a/lib/generators/apartment/install/install_generator.rb +++ b/lib/generators/apartment/install/install_generator.rb @@ -2,7 +2,7 @@ module Apartment class InstallGenerator < Rails::Generators::Base - source_root File.expand_path('../templates', __FILE__) + source_root File.expand_path('templates', __dir__) def copy_files template 'apartment.rb', File.join('config', 'initializers', 'apartment.rb') diff --git a/spec/adapters/sqlite3_adapter_spec.rb b/spec/adapters/sqlite3_adapter_spec.rb index 40388acd..252cdb66 100644 --- a/spec/adapters/sqlite3_adapter_spec.rb +++ b/spec/adapters/sqlite3_adapter_spec.rb @@ -10,7 +10,7 @@ context 'using connections' do def tenant_names - db_dir = File.expand_path('../../dummy/db', __FILE__) + db_dir = File.expand_path('../dummy/db', __dir__) Dir.glob("#{db_dir}/*.sqlite3").map { |file| File.basename(file, '.sqlite3') } end diff --git a/spec/dummy/config/application.rb b/spec/dummy/config/application.rb index c633c115..49b5d459 100644 --- a/spec/dummy/config/application.rb +++ b/spec/dummy/config/application.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require File.expand_path('../boot', __FILE__) +require File.expand_path('boot', __dir__) require 'active_model/railtie' require 'active_record/railtie' diff --git a/spec/dummy/config/boot.rb b/spec/dummy/config/boot.rb index 1f976a16..0c68bf2c 100644 --- a/spec/dummy/config/boot.rb +++ b/spec/dummy/config/boot.rb @@ -2,7 +2,7 @@ require 'rubygems' -gemfile = File.expand_path('../../../../Gemfile', __FILE__) +gemfile = File.expand_path('../../../Gemfile', __dir__) if File.exist?(gemfile) ENV['BUNDLE_GEMFILE'] = gemfile @@ -10,4 +10,4 @@ Bundler.setup end -$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__) +$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) diff --git a/spec/dummy/config/environment.rb b/spec/dummy/config/environment.rb index 1a1e336f..65c03fc7 100644 --- a/spec/dummy/config/environment.rb +++ b/spec/dummy/config/environment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Load the rails application -require File.expand_path('../application', __FILE__) +require File.expand_path('application', __dir__) # Initialize the rails application Dummy::Application.initialize! diff --git a/spec/dummy/script/rails b/spec/dummy/script/rails index 1a08aed0..e1068b28 100755 --- a/spec/dummy/script/rails +++ b/spec/dummy/script/rails @@ -3,6 +3,6 @@ # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. -APP_PATH = File.expand_path('../../config/application', __FILE__) -require File.expand_path('../../config/boot', __FILE__) +APP_PATH = File.expand_path('../config/application', __dir__) +require File.expand_path('../config/boot', __dir__) require 'rails/commands' diff --git a/spec/dummy_engine/test/dummy/config/application.rb b/spec/dummy_engine/test/dummy/config/application.rb index 2562455c..0984f6ce 100644 --- a/spec/dummy_engine/test/dummy/config/application.rb +++ b/spec/dummy_engine/test/dummy/config/application.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true -require File.expand_path('../boot', __FILE__) +require File.expand_path('boot', __dir__) require 'rails/all' diff --git a/spec/dummy_engine/test/dummy/config/boot.rb b/spec/dummy_engine/test/dummy/config/boot.rb index 18536532..6d2cba07 100644 --- a/spec/dummy_engine/test/dummy/config/boot.rb +++ b/spec/dummy_engine/test/dummy/config/boot.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__) +$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) diff --git a/spec/dummy_engine/test/dummy/config/environment.rb b/spec/dummy_engine/test/dummy/config/environment.rb index 3fa66218..32d57aa4 100644 --- a/spec/dummy_engine/test/dummy/config/environment.rb +++ b/spec/dummy_engine/test/dummy/config/environment.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true # Load the Rails application. -require File.expand_path('../application', __FILE__) +require File.expand_path('application', __dir__) # Initialize the Rails application. Rails.application.initialize! diff --git a/spec/integration/use_within_an_engine_spec.rb b/spec/integration/use_within_an_engine_spec.rb index d9592108..072efac6 100644 --- a/spec/integration/use_within_an_engine_spec.rb +++ b/spec/integration/use_within_an_engine_spec.rb @@ -2,7 +2,7 @@ describe 'using apartment within an engine' do before do - engine_path = Pathname.new(File.expand_path('../../dummy_engine', __FILE__)) + engine_path = Pathname.new(File.expand_path('../dummy_engine', __dir__)) require engine_path.join('test/dummy/config/application') @rake = Rake::Application.new Rake.application = @rake diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index e16b2af8..68b9c680 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -5,7 +5,7 @@ # Configure Rails Environment ENV['RAILS_ENV'] = 'test' -require File.expand_path('../dummy/config/environment.rb', __FILE__) +require File.expand_path('dummy/config/environment.rb', __dir__) # Loading dummy applications affects table_name of each excluded models # defined in `spec/dummy/config/initializers/apartment.rb`. From 8f55e25736f893cbea13a741c62d9e3d7983dc9f Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:35:07 +0800 Subject: [PATCH 037/282] WIP - fixed a couple more rules --- .rubocop_todo.yml | 21 --------------------- lib/apartment/adapters/abstract_adapter.rb | 10 +++------- lib/tasks/apartment.rake | 18 +++++++++--------- spec/support/apartment_helpers.rb | 2 +- 4 files changed, 13 insertions(+), 38 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index e1fcf700..b2abff96 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,27 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: format, sprintf, percent -Style/FormatString: - Exclude: - - 'spec/support/apartment_helpers.rb' - -# Offense count: 1 -# Configuration parameters: . -# SupportedStyles: annotated, template, unannotated -Style/FormatStringToken: - EnforcedStyle: unannotated - -# Offense count: 2 -# Configuration parameters: MinBodyLength. -Style/GuardClause: - Exclude: - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/tasks/apartment.rake' - # Offense count: 6 # Cop supports --auto-correct. Style/IfUnlessModifier: diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ced5c69b..ca686ff0 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -2,7 +2,6 @@ module Apartment module Adapters - # rubocop:disable Metrics/ClassLength class AbstractAdapter include ActiveSupport::Callbacks define_callbacks :create, :switch @@ -212,11 +211,9 @@ def multi_tenantify_with_tenant_db_name(config, tenant) # Load a file or raise error if it doesn't exists # def load_or_raise(file) - if File.exist?(file) - load(file) - else - raise FileNotFound, "#{file} doesn't exist yet" - end + raise FileNotFound, "#{file} doesn't exist yet" unless File.exist?(file) + + load(file) end # Backward compatibility alias load_or_abort load_or_raise @@ -268,6 +265,5 @@ def raise_connect_error!(tenant, exception) class SeparateDbConnectionHandler < ::ActiveRecord::Base end end - # rubocop:enable Metrics/ClassLength end end diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 10c4613a..437deda7 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -131,16 +131,16 @@ apartment_namespace = namespace :apartment do end def warn_if_tenants_empty - if tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' - puts <<-WARNING - [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: + return unless tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' - 1. You may not have created any, in which case you can ignore this message - 2. You've run `apartment:migrate` directly without loading the Rails environment - * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate` + puts <<-WARNING + [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: - Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. - WARNING - end + 1. You may not have created any, in which case you can ignore this message + 2. You've run `apartment:migrate` directly without loading the Rails environment + * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate` + + Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. + WARNING end end diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 485143ac..257185b9 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -15,7 +15,7 @@ def reset def next_db @x ||= 0 - 'db%d' % @x += 1 + format('db%d', @x += 1) end def drop_schema(schema) From 5b04164688066e68fb40e003f6edb538b38a3776 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:36:53 +0800 Subject: [PATCH 038/282] WIP - --- spec/support/apartment_helpers.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index 257185b9..d45ea1b3 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -15,7 +15,7 @@ def reset def next_db @x ||= 0 - format('db%d', @x += 1) + format('db%d', db_idx: @x += 1) end def drop_schema(schema) From 0dcea87fba9d5deb8b8126228005174698ffcf56 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:38:36 +0800 Subject: [PATCH 039/282] WIP - fixed if unless modifier --- .pryrc | 4 +--- .rubocop_todo.yml | 10 ---------- lib/apartment/adapters/abstract_adapter.rb | 4 +--- lib/apartment/adapters/postgresql_adapter.rb | 4 +--- 4 files changed, 3 insertions(+), 19 deletions(-) diff --git a/.pryrc b/.pryrc index 6d4a3df8..a6e67e41 100644 --- a/.pryrc +++ b/.pryrc @@ -1,5 +1,3 @@ # frozen_string_literal: true -if defined?(Rails) && Rails.env - extend Rails::ConsoleMethods -end +extend Rails::ConsoleMethods if defined?(Rails) && Rails.env diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index b2abff96..17d735d5 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -33,16 +33,6 @@ Metrics/LineLength: Metrics/MethodLength: Max: 24 -# Offense count: 6 -# Cop supports --auto-correct. -Style/IfUnlessModifier: - Exclude: - - '.pryrc' - - 'lib/apartment.rb' - - 'lib/apartment/adapters/abstract_adapter.rb' - - 'lib/apartment/adapters/jdbc_postgresql_adapter.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - # Offense count: 1 Style/MixinUsage: Exclude: diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ca686ff0..171a7ef4 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -198,9 +198,7 @@ def import_database_schema # if false, use the default db name from the db def multi_tenantify(tenant, with_database = true) db_connection_config(tenant).tap do |config| - if with_database - multi_tenantify_with_tenant_db_name(config, tenant) - end + multi_tenantify_with_tenant_db_name(config, tenant) if with_database end end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 73a1643e..88459afb 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -73,9 +73,7 @@ def connect_to_new(tenant = nil) # When the PostgreSQL version is < 9.3, # there is a issue for prepared statement with changing search_path. # https://www.postgresql.org/docs/9.3/static/sql-prepare.html - if postgresql_version < 90_300 - Apartment.connection.clear_cache! - end + Apartment.connection.clear_cache! if postgresql_version < 90_300 rescue *rescuable_exceptions raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}" end From 0af178428f95ffa20df518e50723eb5075391040 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:39:17 +0800 Subject: [PATCH 040/282] WIP - fixed multiline modifier --- .rubocop_todo.yml | 8 -------- lib/apartment/adapters/sqlite3_adapter.rb | 18 ++++++++++++------ lib/apartment/elevators/host_hash.rb | 6 ++++-- spec/support/requirements.rb | 4 +++- 4 files changed, 19 insertions(+), 17 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 17d735d5..919d6203 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -38,14 +38,6 @@ Style/MixinUsage: Exclude: - '.pryrc' -# Offense count: 5 -# Cop supports --auto-correct. -Style/MultilineIfModifier: - Exclude: - - 'lib/apartment/adapters/sqlite3_adapter.rb' - - 'lib/apartment/elevators/host_hash.rb' - - 'spec/support/requirements.rb' - # Offense count: 7 # Cop supports --auto-correct. # Configuration parameters: EnforcedStyle. diff --git a/lib/apartment/adapters/sqlite3_adapter.rb b/lib/apartment/adapters/sqlite3_adapter.rb index 78f26adc..44896ef4 100644 --- a/lib/apartment/adapters/sqlite3_adapter.rb +++ b/lib/apartment/adapters/sqlite3_adapter.rb @@ -18,8 +18,10 @@ def initialize(config) end def drop(tenant) - raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exist?(database_file(tenant)) + unless File.exist?(database_file(tenant)) + raise TenantNotFound, + "The tenant #{environmentify(tenant)} cannot be found." + end File.delete(database_file(tenant)) end @@ -31,15 +33,19 @@ def current protected def connect_to_new(tenant) - raise TenantNotFound, - "The tenant #{environmentify(tenant)} cannot be found." unless File.exist?(database_file(tenant)) + unless File.exist?(database_file(tenant)) + raise TenantNotFound, + "The tenant #{environmentify(tenant)} cannot be found." + end super database_file(tenant) end def create_tenant(tenant) - raise TenantExists, - "The tenant #{environmentify(tenant)} already exists." if File.exist?(database_file(tenant)) + if File.exist?(database_file(tenant)) + raise TenantExists, + "The tenant #{environmentify(tenant)} already exists." + end begin f = File.new(database_file(tenant), File::CREAT) diff --git a/lib/apartment/elevators/host_hash.rb b/lib/apartment/elevators/host_hash.rb index 306f0319..f68c10cb 100644 --- a/lib/apartment/elevators/host_hash.rb +++ b/lib/apartment/elevators/host_hash.rb @@ -14,8 +14,10 @@ def initialize(app, hash = {}, processor = nil) end def parse_tenant_name(request) - raise TenantNotFound, - "Cannot find tenant for host #{request.host}" unless @hash.key?(request.host) + unless @hash.key?(request.host) + raise TenantNotFound, + "Cannot find tenant for host #{request.host}" + end @hash[request.host] end diff --git a/spec/support/requirements.rb b/spec/support/requirements.rb index cbfbe5ea..0a5fdf7d 100644 --- a/spec/support/requirements.rb +++ b/spec/support/requirements.rb @@ -37,9 +37,11 @@ module AdapterRequirements end %w[subject tenant_names default_tenant].each do |method| + next if defined?(method) + define_method method do raise "You must define a `#{method}` method in your host group" - end unless defined?(method) + end end end end From af4dd0ca06b7bd0af7829acb9556615f5d05d3ea Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:40:20 +0800 Subject: [PATCH 041/282] WIP - fixed mutable constants --- .rubocop_todo.yml | 12 ------------ lib/apartment.rb | 4 ++-- lib/apartment/adapters/postgresql_adapter.rb | 2 +- lib/apartment/tasks/enhancements.rb | 4 ++-- 4 files changed, 5 insertions(+), 17 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 919d6203..805f9c54 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -37,15 +37,3 @@ Metrics/MethodLength: Style/MixinUsage: Exclude: - '.pryrc' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle. -# SupportedStyles: literals, strict -Style/MutableConstant: - Exclude: - - 'lib/apartment.rb' - - 'lib/apartment/adapters/postgresql_adapter.rb' - - 'lib/apartment/tasks/enhancements.rb' - - 'lib/apartment/version.rb' - - 'spec/dummy_engine/lib/dummy_engine/version.rb' diff --git a/lib/apartment.rb b/lib/apartment.rb index ac0e3320..b0d49758 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -11,12 +11,12 @@ class << self extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment - append_environment with_multi_server_setup] + append_environment with_multi_server_setup].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class tld_length db_migrate_tenants seed_data_file - parallel_migration_threads pg_excluded_names] + parallel_migration_threads pg_excluded_names].freeze attr_accessor(*ACCESSOR_METHODS) attr_writer(*WRITER_METHODS) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 88459afb..3e98b627 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -111,7 +111,7 @@ class PostgresqlSchemaFromSqlAdapter < PostgresqlSchemaAdapter /CREATE SCHEMA public/i, /COMMENT ON SCHEMA public/i - ] + ].freeze def import_database_schema preserving_search_path do diff --git a/lib/apartment/tasks/enhancements.rb b/lib/apartment/tasks/enhancements.rb index 95e32ab7..f9a13206 100644 --- a/lib/apartment/tasks/enhancements.rb +++ b/lib/apartment/tasks/enhancements.rb @@ -6,8 +6,8 @@ module Apartment class RakeTaskEnhancer module TASKS - ENHANCE_BEFORE = %w[db:drop] - ENHANCE_AFTER = %w[db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed] + ENHANCE_BEFORE = %w[db:drop].freeze + ENHANCE_AFTER = %w[db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed].freeze freeze end From 9adea7fe953345ec05b196ff93e2403d13dc2186 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 16 Feb 2020 17:42:12 +0800 Subject: [PATCH 042/282] WIP - fixed all immediatly fixable issues --- .pryrc | 2 ++ .rubocop_todo.yml | 5 ----- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/.pryrc b/.pryrc index a6e67e41..33d98970 100644 --- a/.pryrc +++ b/.pryrc @@ -1,3 +1,5 @@ # frozen_string_literal: true +# rubocop:disable Style/MixinUsage extend Rails::ConsoleMethods if defined?(Rails) && Rails.env +# rubocop:enable Style/MixinUsage diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 805f9c54..d61a071d 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -32,8 +32,3 @@ Metrics/LineLength: # Configuration parameters: CountComments, ExcludedMethods. Metrics/MethodLength: Max: 24 - -# Offense count: 1 -Style/MixinUsage: - Exclude: - - '.pryrc' From 1b1476ed0be49dcf8540936d933f2ec9f4f08977 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 12:51:59 +0800 Subject: [PATCH 043/282] WIP - added base application record class --- spec/dummy/app/models/application_record.rb | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 spec/dummy/app/models/application_record.rb diff --git a/spec/dummy/app/models/application_record.rb b/spec/dummy/app/models/application_record.rb new file mode 100644 index 00000000..ba931a20 --- /dev/null +++ b/spec/dummy/app/models/application_record.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +# NOTE: Dummy model base +class ApplicationRecord < ActiveRecord::Base +end From 6e89883cbeae47cb4c581a887e0feb38ffe937a0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 12:58:20 +0800 Subject: [PATCH 044/282] WIP - fixed ignored_first_subdomains --- lib/apartment/elevators/host.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/apartment/elevators/host.rb b/lib/apartment/elevators/host.rb index 283ad316..1984341e 100644 --- a/lib/apartment/elevators/host.rb +++ b/lib/apartment/elevators/host.rb @@ -14,12 +14,14 @@ module Elevators # www.a.b.c.d.com => a.b.c.d.com # class Host < Generic - attr_writer ignored_first_subdomains - def self.ignored_first_subdomains @ignored_first_subdomains ||= [] end + def self.ignored_first_subdomains=(arg) + @ignored_first_subdomains = arg + end + def parse_tenant_name(request) return nil if request.host.blank? From d2cf4b908081be488c5d4df73e8cf7d131c3c901 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 14:14:00 +0800 Subject: [PATCH 045/282] WIP - fixed failing specs after rubocop cleanup --- apartment.gemspec | 2 +- lib/apartment/elevators/subdomain.rb | 6 ++++-- spec/dummy/app/models/application_record.rb | 1 + spec/unit/elevators/domain_spec.rb | 2 +- spec/unit/elevators/generic_spec.rb | 2 +- spec/unit/elevators/host_spec.rb | 2 +- spec/unit/elevators/subdomain_spec.rb | 2 +- 7 files changed, 10 insertions(+), 7 deletions(-) diff --git a/apartment.gemspec b/apartment.gemspec index e00a1304..2a834523 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -42,6 +42,6 @@ Gem::Specification.new do |s| else s.add_development_dependency 'mysql2' s.add_development_dependency 'pg' - s.add_development_dependency 'sqlite3', '~> 1.3.6' + s.add_development_dependency 'sqlite3', '~> 1.4' end end diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index 60e9d022..2f4eb3bc 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -9,12 +9,14 @@ module Elevators # Assumes that tenant name should match subdomain # class Subdomain < Generic - attr_writer :excluded_subdomains - def self.excluded_subdomains @excluded_subdomains ||= [] end + def self.excluded_subdomains=(arg) + @excluded_subdomains = arg + end + def parse_tenant_name(request) request_subdomain = subdomain(request.host) diff --git a/spec/dummy/app/models/application_record.rb b/spec/dummy/app/models/application_record.rb index ba931a20..1d405ba4 100644 --- a/spec/dummy/app/models/application_record.rb +++ b/spec/dummy/app/models/application_record.rb @@ -2,4 +2,5 @@ # NOTE: Dummy model base class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true end diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index fc0ade75..9fd1159e 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/domain' describe Apartment::Elevators::Domain do - subject(:elevator) { described_class.new(proc) } + subject(:elevator) { described_class.new(Proc.new{}) } describe '#parse_tenant_name' do it 'parses the host for a domain name' do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index ae54fca1..b39d1598 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -10,7 +10,7 @@ def parse_tenant_name(*) end end - subject(:elevator) { described_class.new(proc) } + subject(:elevator) { described_class.new(Proc.new{}) } describe '#call' do it 'calls the processor if given' do diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index f480cbbb..9655611b 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/host' describe Apartment::Elevators::Host do - subject(:elevator) { described_class.new(proc) } + subject(:elevator) { described_class.new(Proc.new{}) } describe '#parse_tenant_name' do it 'should return nil when no host' do diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index 42d9c96a..ff5d5375 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/subdomain' describe Apartment::Elevators::Subdomain do - subject(:elevator) { described_class.new(proc) } + subject(:elevator) { described_class.new(Proc.new{}) } describe '#parse_tenant_name' do context 'assuming one tld' do From 7dd413b6c5dd3e09453605341d6a4dae44272a71 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 14:25:30 +0800 Subject: [PATCH 046/282] WIP - reverted sqlite3 as it is not an issue atm --- apartment.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apartment.gemspec b/apartment.gemspec index 2a834523..e00a1304 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -42,6 +42,6 @@ Gem::Specification.new do |s| else s.add_development_dependency 'mysql2' s.add_development_dependency 'pg' - s.add_development_dependency 'sqlite3', '~> 1.4' + s.add_development_dependency 'sqlite3', '~> 1.3.6' end end From daad79bfca897a0fb38957df5f0e1255acfaca0c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 14:36:47 +0800 Subject: [PATCH 047/282] WIP - cleaning up rubocop --- .rubocop_todo.yml | 2 +- lib/apartment/elevators/host.rb | 2 ++ lib/apartment/elevators/subdomain.rb | 2 ++ spec/unit/elevators/domain_spec.rb | 2 +- spec/unit/elevators/generic_spec.rb | 2 +- spec/unit/elevators/host_spec.rb | 2 +- spec/unit/elevators/subdomain_spec.rb | 2 +- 7 files changed, 9 insertions(+), 5 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index d61a071d..aaac295c 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -25,7 +25,7 @@ Metrics/ClassLength: # Cop supports --auto-correct. # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https -Metrics/LineLength: +Layout/LineLength: Max: 237 # Offense count: 4 diff --git a/lib/apartment/elevators/host.rb b/lib/apartment/elevators/host.rb index 1984341e..2db8dfd0 100644 --- a/lib/apartment/elevators/host.rb +++ b/lib/apartment/elevators/host.rb @@ -18,9 +18,11 @@ def self.ignored_first_subdomains @ignored_first_subdomains ||= [] end + # rubocop:disable Style/TrivialAccessors def self.ignored_first_subdomains=(arg) @ignored_first_subdomains = arg end + # rubocop:enable Style/TrivialAccessors def parse_tenant_name(request) return nil if request.host.blank? diff --git a/lib/apartment/elevators/subdomain.rb b/lib/apartment/elevators/subdomain.rb index 2f4eb3bc..38604d60 100644 --- a/lib/apartment/elevators/subdomain.rb +++ b/lib/apartment/elevators/subdomain.rb @@ -13,9 +13,11 @@ def self.excluded_subdomains @excluded_subdomains ||= [] end + # rubocop:disable Style/TrivialAccessors def self.excluded_subdomains=(arg) @excluded_subdomains = arg end + # rubocop:enable Style/TrivialAccessors def parse_tenant_name(request) request_subdomain = subdomain(request.host) diff --git a/spec/unit/elevators/domain_spec.rb b/spec/unit/elevators/domain_spec.rb index 9fd1159e..520b315c 100644 --- a/spec/unit/elevators/domain_spec.rb +++ b/spec/unit/elevators/domain_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/domain' describe Apartment::Elevators::Domain do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc {}) } describe '#parse_tenant_name' do it 'parses the host for a domain name' do diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index b39d1598..b282a5af 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -10,7 +10,7 @@ def parse_tenant_name(*) end end - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc {}) } describe '#call' do it 'calls the processor if given' do diff --git a/spec/unit/elevators/host_spec.rb b/spec/unit/elevators/host_spec.rb index 9655611b..e0cb9c3c 100644 --- a/spec/unit/elevators/host_spec.rb +++ b/spec/unit/elevators/host_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/host' describe Apartment::Elevators::Host do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc {}) } describe '#parse_tenant_name' do it 'should return nil when no host' do diff --git a/spec/unit/elevators/subdomain_spec.rb b/spec/unit/elevators/subdomain_spec.rb index ff5d5375..4c66ce67 100644 --- a/spec/unit/elevators/subdomain_spec.rb +++ b/spec/unit/elevators/subdomain_spec.rb @@ -4,7 +4,7 @@ require 'apartment/elevators/subdomain' describe Apartment::Elevators::Subdomain do - subject(:elevator) { described_class.new(Proc.new{}) } + subject(:elevator) { described_class.new(proc {}) } describe '#parse_tenant_name' do context 'assuming one tld' do From 4aa741b3e4f28cbd8fa3e4245542354ef91f65fe Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 14:45:10 +0800 Subject: [PATCH 048/282] WIP - --- .rubocop_todo.yml | 7 +------ lib/apartment/adapters/abstract_adapter.rb | 2 ++ lib/apartment/railtie.rb | 9 ++++++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index aaac295c..0f709629 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -16,16 +16,11 @@ Metrics/AbcSize: Metrics/BlockLength: Max: 176 -# Offense count: 1 -# Configuration parameters: CountComments. -Metrics/ClassLength: - Max: 155 - # Offense count: 18 # Cop supports --auto-correct. # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https -Layout/LineLength: +Metrics/LineLength: Max: 237 # Offense count: 4 diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 171a7ef4..3890d661 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -2,6 +2,7 @@ module Apartment module Adapters + # rubocop:disable Metrics/ClassLength class AbstractAdapter include ActiveSupport::Callbacks define_callbacks :create, :switch @@ -264,4 +265,5 @@ class SeparateDbConnectionHandler < ::ActiveRecord::Base end end end + # rubocop:enable Metrics/ClassLength end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 43bc54a5..b33cab2d 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -51,8 +51,10 @@ class Railtie < Rails::Railtie end # - # The following initializers are a workaround to the fact that I can't properly hook into the rails reloader - # Note this is technically valid for any environment where cache_classes is false, for us, it's just development + # The following initializers are a workaround to the fact that I can't + # properly hook into the rails reloader + # Note this is technically valid for any environment where cache_classes + # is false, for us, it's just development # if Rails.env.development? @@ -61,7 +63,8 @@ class Railtie < Rails::Railtie app.config.middleware.use Apartment::Reloader end - # Overrides reload! to also call Apartment::Tenant.init as well so that the reloaded classes have the proper table_names + # Overrides reload! to also call Apartment::Tenant.init as well so that the + # reloaded classes have the proper table_names console do require 'apartment/console' end From 68b6cbc4b0e2de0a2a000b05aecba274d620b3de Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 15:43:05 +0800 Subject: [PATCH 049/282] WIP - working on travis config --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 9c634d9a..bcecef19 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,11 @@ rvm: - 2.5.0 - 2.6.2 - ruby-head + +branches: + only: + - development + gemfile: - gemfiles/rails_4_2.gemfile - gemfiles/rails_5_0.gemfile From e6133862e0c58f7ec7b2ca163c9c6a6362dfa699 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 17 Feb 2020 15:45:29 +0800 Subject: [PATCH 050/282] WIP - including master in branches to test --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index bcecef19..3fe43feb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,6 +15,7 @@ rvm: branches: only: + - master - development gemfile: From 68901a8da1450fa9f0d27b393e325d261d47df47 Mon Sep 17 00:00:00 2001 From: jean-francois labbe Date: Tue, 11 Feb 2020 15:24:27 +0100 Subject: [PATCH 051/282] Fix mysql tests - use port configuration --- Rakefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Rakefile b/Rakefile index 8eaec6d0..956310f1 100644 --- a/Rakefile +++ b/Rakefile @@ -85,6 +85,7 @@ namespace :mysql do params << "-h #{my_config['host']}" if my_config['host'] params << "-u #{my_config['username']}" if my_config['username'] params << "-p#{my_config['password']}" if my_config['password'] + params << "--port #{my_config['port']}" if my_config['port'] %x{ mysqladmin #{params.join(' ')} create #{my_config['database']} } rescue "test db already exists" ActiveRecord::Base.establish_connection my_config migrate @@ -97,6 +98,7 @@ namespace :mysql do params << "-h #{my_config['host']}" if my_config['host'] params << "-u #{my_config['username']}" if my_config['username'] params << "-p#{my_config['password']}" if my_config['password'] + params << "--port #{my_config['port']}" if my_config['port'] %x{ mysqladmin #{params.join(' ')} drop #{my_config['database']} --force} end From 4eb1681658d9eed8f78dd04a4ce34d38211eb2d4 Mon Sep 17 00:00:00 2001 From: Arthur Dingemans Date: Fri, 13 Mar 2020 14:27:06 +0100 Subject: [PATCH 052/282] Don't crash when no database connection is present --- lib/apartment/railtie.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index b33cab2d..e082ab9e 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -35,9 +35,12 @@ class Railtie < Rails::Railtie Apartment::Tenant.init end # rubocop:disable Lint/SuppressedException - rescue ::ActiveRecord::NoDatabaseError + rescue ::ActiveRecord::NoDatabaseError, PG::ConnectionBad # Since `db:create` and other tasks invoke this block from Rails 5.2.0, # we need to swallow the error to execute `db:create` properly. + Rails.logger.warn do + 'Failed to initialize Apartment because a database connection could not be established.' + end end # rubocop:enable Lint/SuppressedException end From 40af1757f2c76054323576deee4dbbdcc992af43 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:47:30 +0800 Subject: [PATCH 053/282] Rescuing ActiveRecord::NoDatabaseError when dropping tenants --- lib/tasks/apartment.rake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 437deda7..d8353821 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -22,7 +22,7 @@ apartment_namespace = namespace :apartment do begin puts("Dropping #{tenant} tenant") Apartment::Tenant.drop(tenant) - rescue Apartment::TenantNotFound => e + rescue Apartment::TenantNotFound, ActiveRecord::NoDatabaseError => e puts e.message end end From 5910ffb5e622b10b3057239ebbe95e08f51c2662 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 22:34:37 +0800 Subject: [PATCH 054/282] Update 9.1.8 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3fe43feb..b472b921 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ language: ruby services: - docker rvm: - - jruby-9.1.17.0 + - jruby-9.1.8 - 2.1.9 - 2.2.9 - 2.3.6 From 37d2e88c8825e4a87e7ac90563d6228642adca02 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 22:38:25 +0800 Subject: [PATCH 055/282] Removed rubocop --- lib/apartment/railtie.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index e082ab9e..255f6273 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -34,7 +34,6 @@ class Railtie < Rails::Railtie Apartment.connection_class.connection_pool.with_connection do Apartment::Tenant.init end - # rubocop:disable Lint/SuppressedException rescue ::ActiveRecord::NoDatabaseError, PG::ConnectionBad # Since `db:create` and other tasks invoke this block from Rails 5.2.0, # we need to swallow the error to execute `db:create` properly. @@ -42,7 +41,6 @@ class Railtie < Rails::Railtie 'Failed to initialize Apartment because a database connection could not be established.' end end - # rubocop:enable Lint/SuppressedException end # From 1e29dd458d38cbfec9ecc08354d86156de8caa47 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 22:46:57 +0800 Subject: [PATCH 056/282] Upgrade jruby version --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index b472b921..d39c2375 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ language: ruby services: - docker rvm: - - jruby-9.1.8 + - jruby-9.2.11.0 - 2.1.9 - 2.2.9 - 2.3.6 From d0be966039053066e3f3a1b0f21ba73116edbabc Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:36:20 +0800 Subject: [PATCH 057/282] Skip init if we're running webpacker:compile --- lib/apartment/railtie.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 255f6273..647b221c 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -29,6 +29,7 @@ class Railtie < Rails::Railtie # config.to_prepare do next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } + next if ARGV.any? { |arg| arg == 'webpacker:compile' } begin Apartment.connection_class.connection_pool.with_connection do From aef24617d491495f88e4496b81d96f7fe05bbd44 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 20 Feb 2020 17:23:57 +0800 Subject: [PATCH 058/282] WIP - initial customization of the console --- lib/apartment/console.rb | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index d5a45d57..429183f1 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -15,3 +15,26 @@ def reload!(print = true) Apartment::Tenant.init true end + + +module Apartment + module CustomConsole + def st(schema_name = nil) + if schema_name.nil? + tenant_list.each { |t| puts t } + else + Apartment::Tenant.switch!(schema_name) if Apartment::Tenant.include? schema_name + end + end + + def tenant_list + tenant_list = ['public'] + Apartment::Tenant.each do |t| + tenant_list << t + end + tenant_list + end + end +end + +include Apartment::CustomConsole From 085e8e5f2f7893c3dcd9b22c7cb7ebab7c5e1bd4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:05:50 +0800 Subject: [PATCH 059/282] [Resolves #14] Adds custom console methods --- lib/apartment/console.rb | 31 ++++++++++++------------------- lib/apartment/custom_console.rb | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 19 deletions(-) create mode 100644 lib/apartment/custom_console.rb diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 429183f1..fed3d11e 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -16,25 +16,18 @@ def reload!(print = true) true end - -module Apartment - module CustomConsole - def st(schema_name = nil) - if schema_name.nil? - tenant_list.each { |t| puts t } - else - Apartment::Tenant.switch!(schema_name) if Apartment::Tenant.include? schema_name - end - end - - def tenant_list - tenant_list = ['public'] - Apartment::Tenant.each do |t| - tenant_list << t - end - tenant_list - end +def st(schema_name = nil) + if schema_name.nil? + tenant_list.each { |t| puts t } + else + Apartment::Tenant.switch!(schema_name) if tenant_list.include? schema_name end end -include Apartment::CustomConsole +def tenant_list + tenant_list = [Apartment.default_tenant] + Apartment::Tenant.each do |t| + tenant_list << t + end + tenant_list.uniq +end diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb new file mode 100644 index 00000000..65a9b484 --- /dev/null +++ b/lib/apartment/custom_console.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module Apartment + module CustomConsole + begin + require 'pry-rails' + rescue LoadError + puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' + end + + if Pry::Prompt.respond_to?(:add) + desc = "Includes the current Rails environment and project folder name.\n" \ + '[1] [project_name][Rails.env][Apartment::Tenant.current] pry(main)>' + + Pry::Prompt.add 'ros', desc, %w[> *] do |target_self, nest_level, pry, sep| + "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ + "#{pry.config.prompt_name}(#{Pry.view_clip(target_self)})" \ + "#{":#{nest_level}" unless nest_level.zero?}#{sep} " + end + + Pry.config.prompt = Pry::Prompt[:ros][:value] + end + end +end From 47031780ff398132edcb1ce77c5a11ce4164c50c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:08:58 +0800 Subject: [PATCH 060/282] Cleanup tenant list method --- lib/apartment/console.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index fed3d11e..c3c9b62f 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -26,8 +26,6 @@ def st(schema_name = nil) def tenant_list tenant_list = [Apartment.default_tenant] - Apartment::Tenant.each do |t| - tenant_list << t - end + tenant_list += Apartment.tenant_names tenant_list.uniq end From 1134b8d9abba2ce01975d2a787a4d232f9415aa0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:22:32 +0800 Subject: [PATCH 061/282] [#14] Updates the readme and disables rails/output rubocop warning --- README.md | 21 +++++++++++++++++++++ lib/apartment/custom_console.rb | 2 ++ 2 files changed, 23 insertions(+) diff --git a/README.md b/README.md index 31e8ca13..bfadee2a 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,27 @@ Apartment::Tenant.drop('tenant_name') When method is called, the schema is dropped and all data from itself will be lost. Be careful with this method. +### Custom Prompt + +#### Console methods + +`ros-apartment` console configures two helper methods: +1. `tenant_list` - list available tenants while using the console +2. `st(tenant_name:String)` - Switches the context to the tenant name passed, if +it exists. + +#### Custom printed prompt + +`ros-apartment` also has a custom prompt that gives a bit more information about +the context in which you're running. It shows the environment as well as the tenant +that is currently switched to. In order for you to enable this, you need to require +the custom console in your application. + +In `application.rb` add `require 'apartment/custom_console'`. +Please note that we rely on `pry-rails` to edit the prompt, thus your project needs +to install it as well. In order to do so, you need to add `gem 'pry-rails'` to your +project's gemfile. + ## Config The following config options should be set up in a Rails initializer such as: diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index 65a9b484..c3c49c5d 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -5,7 +5,9 @@ module CustomConsole begin require 'pry-rails' rescue LoadError + # rubocop:disable Rails/Output puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' + # rubocop:enable Rails/Output end if Pry::Prompt.respond_to?(:add) From 88fcae8d0439f61fc235b912e31c22897a2ac080 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 20:30:26 +0800 Subject: [PATCH 062/282] Address rubocop errors --- lib/apartment/console.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index c3c9b62f..a2ed609f 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -18,9 +18,15 @@ def reload!(print = true) def st(schema_name = nil) if schema_name.nil? + # rubocop:disable Rails/Output tenant_list.each { |t| puts t } + # rubocop:enable Rails/Output + elsif tenant_list.include? schema_name + Apartment::Tenant.switch!(schema_name) else - Apartment::Tenant.switch!(schema_name) if tenant_list.include? schema_name + # rubocop:disable Rails/Output + puts "Tenant #{schema_name} is not part of the tenant list" + # rubocop:enable Rails/Output end end From 0779d98ce9dc451e15dc8971cf2483420400a311 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 23 Mar 2020 08:33:30 +0800 Subject: [PATCH 063/282] Updated badges --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bfadee2a..4694ed26 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Apartment -[![Gem Version](https://badge.fury.io/rb/apartment.svg)](https://badge.fury.io/rb/apartment) -[![Code Climate](https://codeclimate.com/github/influitive/apartment/badges/gpa.svg)](https://codeclimate.com/github/influitive/apartment) -[![Build Status](https://travis-ci.org/influitive/apartment.svg?branch=development)](https://travis-ci.org/influitive/apartment) +[![Gem Version](https://badge.fury.io/rb/ros-apartment.svg)](https://badge.fury.io/rb/apartment) +[![Code Climate](https://api.codeclimate.com/v1/badges/b0dc327380bb8438f991/maintainability)](https://codeclimate.com/github/rails-on-services/apartment/maintainability) +[![Build Status](https://travis-ci.org/rails-on-services/apartment.svg?branch=development)](https://travis-ci.org/rails-on-services/apartment) *Multitenancy for Rails and ActiveRecord* From 841fbcad359d40879f7abd2de1e634f72e5a6ff1 Mon Sep 17 00:00:00 2001 From: jean-francois labbe Date: Thu, 13 Feb 2020 11:48:57 +0100 Subject: [PATCH 064/282] support rails 6.1, remove warnings --- lib/apartment.rb | 32 ++++++++++++++++++++-- lib/apartment/adapters/abstract_adapter.rb | 2 +- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index b0d49758..fa176d53 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,6 +6,26 @@ require 'active_record' require 'apartment/tenant' +if ActiveRecord.version.release >= Gem::Version.new("6.1") + module ActiveRecord + class SchemaMigration < ActiveRecord::Base # :nodoc: + class << self + def table_exists? + connection.table_exists?(table_name) + end + end + end + + class InternalMetadata < ActiveRecord::Base # :nodoc: + class << self + def table_exists? + connection.table_exists?(table_name) + end + end + end + end +end + module Apartment class << self extend Forwardable @@ -21,7 +41,15 @@ class << self attr_accessor(*ACCESSOR_METHODS) attr_writer(*WRITER_METHODS) - def_delegators :connection_class, :connection, :connection_config, :establish_connection + if ActiveRecord.version.release >= Gem::Version.new("6.1") + def_delegators :connection_class, :connection, :connection_db_config, :establish_connection + + def connection_config + connection_db_config.configuration_hash + end + else + def_delegators :connection_class, :connection, :connection_config, :establish_connection + end # configure apartment with available options def configure @@ -37,7 +65,7 @@ def tenants_with_config end def db_config_for(tenant) - (tenants_with_config[tenant] || connection_config).with_indifferent_access + (tenants_with_config[tenant] || connection_config) end # Whether or not db:migrate should also migrate tenants diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 3890d661..6df74679 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -230,7 +230,7 @@ def rescue_from end def db_connection_config(tenant) - Apartment.db_config_for(tenant).clone + Apartment.db_config_for(tenant).dup end def with_neutral_connection(tenant, &_block) From 54c9c726d1cb828ee8e1426ef4b7fe9ab39032f9 Mon Sep 17 00:00:00 2001 From: jean-francois labbe Date: Mon, 23 Mar 2020 10:51:21 +0100 Subject: [PATCH 065/282] fix rubocop --- lib/apartment.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index fa176d53..f57ac4bb 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,9 +6,9 @@ require 'active_record' require 'apartment/tenant' -if ActiveRecord.version.release >= Gem::Version.new("6.1") +if ActiveRecord.version.release >= Gem::Version.new('6.1') module ActiveRecord - class SchemaMigration < ActiveRecord::Base # :nodoc: + class SchemaMigration < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord class << self def table_exists? connection.table_exists?(table_name) @@ -16,7 +16,7 @@ def table_exists? end end - class InternalMetadata < ActiveRecord::Base # :nodoc: + class InternalMetadata < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord class << self def table_exists? connection.table_exists?(table_name) @@ -41,7 +41,7 @@ class << self attr_accessor(*ACCESSOR_METHODS) attr_writer(*WRITER_METHODS) - if ActiveRecord.version.release >= Gem::Version.new("6.1") + if ActiveRecord.version.release >= Gem::Version.new('6.1') def_delegators :connection_class, :connection, :connection_db_config, :establish_connection def connection_config From b3f2dc121a71855a6b98ef90cb8d076eeb5a5233 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 23 Mar 2020 08:51:09 +0800 Subject: [PATCH 066/282] Cleanup travis matrix --- .travis.yml | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index d39c2375..35f5b7cb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,10 +40,6 @@ jobs: allow_failures: - rvm: ruby-head - gemfile: gemfiles/rails_master.gemfile - - rvm: jruby-9.1.17.0 - gemfile: gemfiles/rails_5_0.gemfile - # Rails 5.2.4.1 is currently broken. Code has been fixed but no release - # for it yet - https://github.com/rails/rails/issues/38137 - rvm: 2.2.9 gemfile: gemfiles/rails_5_2.gemfile exclude: @@ -63,13 +59,5 @@ jobs: gemfile: gemfiles/rails_6_0.gemfile - rvm: 2.4.3 gemfile: gemfiles/rails_6_0.gemfile - - rvm: jruby-9.1.17.0 - gemfile: gemfiles/rails_5_1.gemfile - - rvm: jruby-9.1.17.0 - gemfile: gemfiles/rails_5_2.gemfile - - rvm: jruby-9.1.17.0 - gemfile: gemfiles/rails_6_0.gemfile - - rvm: jruby-9.1.17.0 - gemfile: gemfiles/rails_master.gemfile fast_finish: true cache: bundler From 2b870ce3249a93bbfeef381bfe6792b361e63b43 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 24 Mar 2020 08:46:53 +0800 Subject: [PATCH 067/282] JRuby does not guarantee rails 4 --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index 35f5b7cb..a70df83d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -42,6 +42,9 @@ jobs: - gemfile: gemfiles/rails_master.gemfile - rvm: 2.2.9 gemfile: gemfiles/rails_5_2.gemfile + # JRuby does not provide support for anything below rails 5 + - rvm: jruby-9.2.11.0 + gemfile: gemfiles/rails_4_2.gemfile exclude: - rvm: 2.1.9 gemfile: gemfiles/rails_5_0.gemfile From 7e5a2b2024ede46809bd2b6893f06ccda40c70c2 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 1 Apr 2020 15:18:04 +0800 Subject: [PATCH 068/282] Fix gemspec open versions and updated version --- apartment.gemspec | 12 ++++++------ lib/apartment/version.rb | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/apartment.gemspec b/apartment.gemspec index e00a1304..885fd18e 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -21,11 +21,11 @@ Gem::Specification.new do |s| # must be >= 3.1.2 due to bug in prepared_statements s.add_dependency 'activerecord', '>= 3.1.2', '< 6.1' - s.add_dependency 'parallel', '>= 0.7.1' - s.add_dependency 'public_suffix', '>= 2' - s.add_dependency 'rack', '>= 1.3.6' + s.add_dependency 'parallel', '< 2.0' + s.add_dependency 'public_suffix', '>= 2.0.5', '< 5.0' + s.add_dependency 'rack', '>= 1.3.6', '< 3.0' - s.add_development_dependency 'appraisal' + s.add_development_dependency 'appraisal', '~> 2.2' s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' s.add_development_dependency 'capybara', '~> 2.0' s.add_development_dependency 'rake', '~> 0.9' @@ -40,8 +40,8 @@ Gem::Specification.new do |s| s.add_development_dependency 'jdbc-postgres' s.add_development_dependency 'jruby-openssl' else - s.add_development_dependency 'mysql2' - s.add_development_dependency 'pg' + s.add_development_dependency 'mysql2', '~> 0.5' + s.add_development_dependency 'pg', '~> 1.2' s.add_development_dependency 'sqlite3', '~> 1.3.6' end end diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 8f84b610..e682d893 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.3.0' + VERSION = '2.4.0' end From fa0f0f0dae55884a04288cbd3fd73d597fc96e47 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 21:03:03 +0800 Subject: [PATCH 069/282] [#11] Remove old ruby and rails versions from the supported versions --- .travis.yml | 5 +---- Appraisals | 21 ++++----------------- apartment.gemspec | 2 +- gemfiles/rails_5_0.gemfile | 21 ++++++++++----------- gemfiles/rails_5_1.gemfile | 21 ++++++++++----------- gemfiles/rails_5_2.gemfile | 19 +++++++++---------- gemfiles/rails_6_0.gemfile | 21 ++++++++++----------- gemfiles/rails_master.gemfile | 21 ++++++++++----------- 8 files changed, 55 insertions(+), 76 deletions(-) diff --git a/.travis.yml b/.travis.yml index a70df83d..48273b26 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,9 +5,6 @@ services: - docker rvm: - jruby-9.2.11.0 - - 2.1.9 - - 2.2.9 - - 2.3.6 - 2.4.3 - 2.5.0 - 2.6.2 @@ -19,12 +16,12 @@ branches: - development gemfile: - - gemfiles/rails_4_2.gemfile - gemfiles/rails_5_0.gemfile - gemfiles/rails_5_1.gemfile - gemfiles/rails_5_2.gemfile - gemfiles/rails_6_0.gemfile - gemfiles/rails_master.gemfile + bundler_args: --without local before_install: - sudo /etc/init.d/mysql stop diff --git a/Appraisals b/Appraisals index 9a5ad27a..519e9767 100644 --- a/Appraisals +++ b/Appraisals @@ -1,18 +1,5 @@ # frozen_string_literal: true -appraise 'rails-4-2' do - gem 'rails', '~> 4.2.0' - platforms :ruby do - gem 'pg', '< 1.0.0' - gem 'mysql2', '~> 0.4.0' - end - platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 1.3' - gem 'activerecord-jdbcpostgresql-adapter', '~> 1.3' - gem 'activerecord-jdbcmysql-adapter', '~> 1.3' - end -end - appraise 'rails-5-0' do gem 'rails', '~> 5.0.0' platforms :ruby do @@ -47,14 +34,14 @@ appraise 'rails-5-2' do end appraise 'rails-6-0' do - gem 'rails', '~> 6.0.0.rc1' + gem 'rails', '~> 6.0.0' platforms :ruby do gem 'sqlite3', '~> 1.4' end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 60.0.rc1' - gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0.rc1' - gem 'activerecord-jdbcmysql-adapter', '~> 60.0.rc1' + gem 'activerecord-jdbc-adapter', '~> 60.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0' + gem 'activerecord-jdbcmysql-adapter', '~> 60.0' end end diff --git a/apartment.gemspec b/apartment.gemspec index 885fd18e..5f623e4e 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -20,7 +20,7 @@ Gem::Specification.new do |s| s.licenses = ['MIT'] # must be >= 3.1.2 due to bug in prepared_statements - s.add_dependency 'activerecord', '>= 3.1.2', '< 6.1' + s.add_dependency 'activerecord', '>= 5.0.0', '< 6.1' s.add_dependency 'parallel', '< 2.0' s.add_dependency 'public_suffix', '>= 2.0.5', '< 5.0' s.add_dependency 'rack', '>= 1.3.6', '< 3.0' diff --git a/gemfiles/rails_5_0.gemfile b/gemfiles/rails_5_0.gemfile index 3d1c50a4..a3d3a72c 100644 --- a/gemfiles/rails_5_0.gemfile +++ b/gemfiles/rails_5_0.gemfile @@ -1,24 +1,23 @@ -# frozen_string_literal: true - # This file was generated by Appraisal -source 'http://rubygems.org' +source "http://rubygems.org" -gem 'rails', '~> 5.0.0' +gem "rails", "~> 5.0.0" +gem "perx-rubocop", "~> 0.0.3" group :local do - gem 'guard-rspec', '~> 4.2' - gem 'pry' + gem "guard-rspec", "~> 4.2" + gem "pry" end platforms :ruby do - gem 'pg', '< 1.0.0' + gem "pg", "< 1.0.0" end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 50.0' - gem 'activerecord-jdbcmysql-adapter', '~> 50.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 50.0' + gem "activerecord-jdbc-adapter", "~> 50.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 50.0" + gem "activerecord-jdbcmysql-adapter", "~> 50.0" end -gemspec path: '../' +gemspec path: "../" diff --git a/gemfiles/rails_5_1.gemfile b/gemfiles/rails_5_1.gemfile index fd285b95..7c75050b 100644 --- a/gemfiles/rails_5_1.gemfile +++ b/gemfiles/rails_5_1.gemfile @@ -1,24 +1,23 @@ -# frozen_string_literal: true - # This file was generated by Appraisal -source 'http://rubygems.org' +source "http://rubygems.org" -gem 'rails', '~> 5.1.0' +gem "rails", "~> 5.1.0" +gem "perx-rubocop", "~> 0.0.3" group :local do - gem 'guard-rspec', '~> 4.2' - gem 'pry' + gem "guard-rspec", "~> 4.2" + gem "pry" end platforms :ruby do - gem 'pg', '< 1.0.0' + gem "pg", "< 1.0.0" end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 51.0' - gem 'activerecord-jdbcmysql-adapter', '~> 51.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 51.0' + gem "activerecord-jdbc-adapter", "~> 51.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 51.0" + gem "activerecord-jdbcmysql-adapter", "~> 51.0" end -gemspec path: '../' +gemspec path: "../" diff --git a/gemfiles/rails_5_2.gemfile b/gemfiles/rails_5_2.gemfile index fb42246f..09ae9502 100644 --- a/gemfiles/rails_5_2.gemfile +++ b/gemfiles/rails_5_2.gemfile @@ -1,20 +1,19 @@ -# frozen_string_literal: true - # This file was generated by Appraisal -source 'http://rubygems.org' +source "http://rubygems.org" -gem 'rails', '~> 5.2.0' +gem "rails", "~> 5.2.0" +gem "perx-rubocop", "~> 0.0.3" group :local do - gem 'guard-rspec', '~> 4.2' - gem 'pry' + gem "guard-rspec", "~> 4.2" + gem "pry" end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 52.0' - gem 'activerecord-jdbcmysql-adapter', '~> 52.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' + gem "activerecord-jdbc-adapter", "~> 52.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 52.0" + gem "activerecord-jdbcmysql-adapter", "~> 52.0" end -gemspec path: '../' +gemspec path: "../" diff --git a/gemfiles/rails_6_0.gemfile b/gemfiles/rails_6_0.gemfile index ec151217..5559b2e8 100644 --- a/gemfiles/rails_6_0.gemfile +++ b/gemfiles/rails_6_0.gemfile @@ -1,24 +1,23 @@ -# frozen_string_literal: true - # This file was generated by Appraisal -source 'http://rubygems.org' +source "http://rubygems.org" -gem 'rails', '~> 6.0.0.rc1' +gem "rails", "~> 6.0.0" +gem "perx-rubocop", "~> 0.0.3" group :local do - gem 'guard-rspec', '~> 4.2' - gem 'pry' + gem "guard-rspec", "~> 4.2" + gem "pry" end platforms :ruby do - gem 'sqlite3', '~> 1.4' + gem "sqlite3", "~> 1.4" end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 60.0.rc1' - gem 'activerecord-jdbcmysql-adapter', '~> 60.0.rc1' - gem 'activerecord-jdbcpostgresql-adapter', '~> 60.0.rc1' + gem "activerecord-jdbc-adapter", "~> 60.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 60.0" + gem "activerecord-jdbcmysql-adapter", "~> 60.0" end -gemspec path: '../' +gemspec path: "../" diff --git a/gemfiles/rails_master.gemfile b/gemfiles/rails_master.gemfile index af85bb04..dd8bccf6 100644 --- a/gemfiles/rails_master.gemfile +++ b/gemfiles/rails_master.gemfile @@ -1,24 +1,23 @@ -# frozen_string_literal: true - # This file was generated by Appraisal -source 'http://rubygems.org' +source "http://rubygems.org" -gem 'rails', git: 'https://github.com/rails/rails.git' +gem "rails", git: "https://github.com/rails/rails.git" +gem "perx-rubocop", "~> 0.0.3" group :local do - gem 'guard-rspec', '~> 4.2' - gem 'pry' + gem "guard-rspec", "~> 4.2" + gem "pry" end platforms :ruby do - gem 'sqlite3', '~> 1.4' + gem "sqlite3", "~> 1.4" end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 52.0' - gem 'activerecord-jdbcmysql-adapter', '~> 52.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' + gem "activerecord-jdbc-adapter", "~> 52.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 52.0" + gem "activerecord-jdbcmysql-adapter", "~> 52.0" end -gemspec path: '../' +gemspec path: "../" From 91b1d68938fe9deeadf475f66a1701e61df7f91d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 22 Mar 2020 22:27:42 +0800 Subject: [PATCH 070/282] Fixing rubocop vesion and ignoring gemfiles --- .rubocop.yml | 4 ++++ Gemfile | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.rubocop.yml b/.rubocop.yml index e8cc53e7..06ac8bf4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -4,6 +4,10 @@ inherit_gem: perx-rubocop: - default.yml +AllCops: + Exclude: + - 'gemfiles/**/*.gemfile' + Style/WordArray: Exclude: - spec/schemas/**/*.rb diff --git a/Gemfile b/Gemfile index 8bad8db6..45de0046 100644 --- a/Gemfile +++ b/Gemfile @@ -4,8 +4,9 @@ source 'http://rubygems.org' gemspec -gem 'rails', '>= 3.1.2' gem 'perx-rubocop', '~> 0.0.3' +gem 'rails', '>= 3.1.2' +gem 'rubocop', '=0.77.0' group :local do gem 'guard-rspec', '~> 4.2' From ad32b082f0ac4461a1be737ef962288496f1ea1a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 2 Apr 2020 11:09:15 +0800 Subject: [PATCH 071/282] [CI] removed unused exclusions --- .travis.yml | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/.travis.yml b/.travis.yml index 48273b26..14a51e2f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,26 +37,7 @@ jobs: allow_failures: - rvm: ruby-head - gemfile: gemfiles/rails_master.gemfile - - rvm: 2.2.9 - gemfile: gemfiles/rails_5_2.gemfile - # JRuby does not provide support for anything below rails 5 - - rvm: jruby-9.2.11.0 - gemfile: gemfiles/rails_4_2.gemfile exclude: - - rvm: 2.1.9 - gemfile: gemfiles/rails_5_0.gemfile - - rvm: 2.1.9 - gemfile: gemfiles/rails_5_1.gemfile - - rvm: 2.1.9 - gemfile: gemfiles/rails_5_2.gemfile - - rvm: 2.1.9 - gemfile: gemfiles/rails_6_0.gemfile - - rvm: 2.1.9 - gemfile: gemfiles/rails_master.gemfile - - rvm: 2.2.9 - gemfile: gemfiles/rails_6_0.gemfile - - rvm: 2.3.6 - gemfile: gemfiles/rails_6_0.gemfile - rvm: 2.4.3 gemfile: gemfiles/rails_6_0.gemfile fast_finish: true From d527441a6eaadcf1f55a34846f70d78f6c8c735a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 2 Apr 2020 11:21:40 +0800 Subject: [PATCH 072/282] [Chore] ran rubocop safe autocorrect --- Gemfile | 1 - Guardfile | 4 +- Rakefile | 56 ++++++++++------- spec/dummy/Rakefile | 4 +- .../20110613152810_create_dummy_models.rb | 36 +++++------ .../20111202022214_create_table_books.rb | 4 +- .../20180415260934_create_public_tokens.rb | 4 +- spec/dummy/db/schema.rb | 62 +++++++++---------- spec/dummy/db/seeds.rb | 6 +- spec/dummy_engine/Gemfile | 4 +- spec/dummy_engine/Rakefile | 7 +-- spec/dummy_engine/bin/rails | 8 ++- spec/dummy_engine/dummy_engine.gemspec | 30 ++++----- spec/dummy_engine/test/dummy/Rakefile | 4 +- 14 files changed, 129 insertions(+), 101 deletions(-) diff --git a/Gemfile b/Gemfile index 45de0046..b0f35aba 100644 --- a/Gemfile +++ b/Gemfile @@ -6,7 +6,6 @@ gemspec gem 'perx-rubocop', '~> 0.0.3' gem 'rails', '>= 3.1.2' -gem 'rubocop', '=0.77.0' group :local do gem 'guard-rspec', '~> 4.2' diff --git a/Guardfile b/Guardfile index 5d3fa72d..ffec03ce 100644 --- a/Guardfile +++ b/Guardfile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # A sample Guardfile # More info at https://github.com/guard/guard#readme @@ -5,7 +7,7 @@ guard :rspec do watch(%r{^spec/.+_spec\.rb$}) watch(%r{^lib/apartment/(.+)\.rb$}) { |m| "spec/unit/#{m[1]}_spec.rb" } watch(%r{^lib/apartment/(.+)\.rb$}) { |m| "spec/integration/#{m[1]}_spec.rb" } - watch('spec/spec_helper.rb') { "spec" } + watch('spec/spec_helper.rb') { 'spec' } # # Rails example # watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } diff --git a/Rakefile b/Rakefile index 956310f1..735d192c 100644 --- a/Rakefile +++ b/Rakefile @@ -1,19 +1,25 @@ -require 'bundler' rescue 'You must `gem install bundler` and `bundle install` to run rake tasks' +# frozen_string_literal: true + +begin + require 'bundler' +rescue StandardError + 'You must `gem install bundler` and `bundle install` to run rake tasks' +end Bundler.setup Bundler::GemHelper.install_tasks require 'appraisal' -require "rspec" -require "rspec/core/rake_task" +require 'rspec' +require 'rspec/core/rake_task' -RSpec::Core::RakeTask.new(:spec => %w{ db:copy_credentials db:test:prepare }) do |spec| - spec.pattern = "spec/**/*_spec.rb" +RSpec::Core::RakeTask.new(spec: %w[db:copy_credentials db:test:prepare]) do |spec| + spec.pattern = 'spec/**/*_spec.rb' # spec.rspec_opts = '--order rand:47078' end namespace :spec do - [:tasks, :unit, :adapters, :integration].each do |type| + %i[tasks unit adapters integration].each do |type| RSpec::Core::RakeTask.new(type => :spec) do |spec| spec.pattern = "spec/#{type}/**/*_spec.rb" end @@ -27,11 +33,11 @@ task :console do Pry.start end -task :default => :spec +task default: :spec namespace :db do namespace :test do - task :prepare => %w{postgres:drop_db postgres:build_db mysql:drop_db mysql:build_db} + task prepare: %w[postgres:drop_db postgres:build_db mysql:drop_db mysql:build_db] end desc "copy sample database credential files over if real files don't exist" @@ -40,29 +46,33 @@ namespace :db do apartment_db_file = 'spec/config/database.yml' rails_db_file = 'spec/dummy/config/database.yml' - FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, :verbose => true) unless File.exists?(apartment_db_file) - FileUtils.copy(rails_db_file + '.sample', rails_db_file, :verbose => true) unless File.exists?(rails_db_file) + FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, verbose: true) unless File.exist?(apartment_db_file) + FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) unless File.exist?(rails_db_file) end end namespace :postgres do require 'active_record' - require "#{File.join(File.dirname(__FILE__), 'spec', 'support', 'config')}" + require File.join(File.dirname(__FILE__), 'spec', 'support', 'config').to_s desc 'Build the PostgreSQL test databases' task :build_db do params = [] - params << "-E UTF8" + params << '-E UTF8' params << pg_config['database'] params << "-U#{pg_config['username']}" params << "-h#{pg_config['host']}" if pg_config['host'] params << "-p#{pg_config['port']}" if pg_config['port'] - %x{ createdb #{params.join(' ')} } rescue "test db already exists" + begin + `createdb #{params.join(' ')}` + rescue StandardError + 'test db already exists' + end ActiveRecord::Base.establish_connection pg_config migrate end - desc "drop the PostgreSQL test database" + desc 'drop the PostgreSQL test database' task :drop_db do puts "dropping database #{pg_config['database']}" params = [] @@ -70,14 +80,13 @@ namespace :postgres do params << "-U#{pg_config['username']}" params << "-h#{pg_config['host']}" if pg_config['host'] params << "-p#{pg_config['port']}" if pg_config['port'] - %x{ dropdb #{params.join(' ')} } + `dropdb #{params.join(' ')}` end - end namespace :mysql do require 'active_record' - require "#{File.join(File.dirname(__FILE__), 'spec', 'support', 'config')}" + require File.join(File.dirname(__FILE__), 'spec', 'support', 'config').to_s desc 'Build the MySQL test databases' task :build_db do @@ -86,12 +95,16 @@ namespace :mysql do params << "-u #{my_config['username']}" if my_config['username'] params << "-p#{my_config['password']}" if my_config['password'] params << "--port #{my_config['port']}" if my_config['port'] - %x{ mysqladmin #{params.join(' ')} create #{my_config['database']} } rescue "test db already exists" + begin + `mysqladmin #{params.join(' ')} create #{my_config['database']}` + rescue StandardError + 'test db already exists' + end ActiveRecord::Base.establish_connection my_config migrate end - desc "drop the MySQL test database" + desc 'drop the MySQL test database' task :drop_db do puts "dropping database #{my_config['database']}" params = [] @@ -99,12 +112,11 @@ namespace :mysql do params << "-u #{my_config['username']}" if my_config['username'] params << "-p#{my_config['password']}" if my_config['password'] params << "--port #{my_config['port']}" if my_config['port'] - %x{ mysqladmin #{params.join(' ')} drop #{my_config['database']} --force} + `mysqladmin #{params.join(' ')} drop #{my_config['database']} --force` end - end -# TODO clean this up +# TODO: clean this up def config Apartment::Test.config['connections'] end diff --git a/spec/dummy/Rakefile b/spec/dummy/Rakefile index 9724472e..d189df36 100644 --- a/spec/dummy/Rakefile +++ b/spec/dummy/Rakefile @@ -1,7 +1,9 @@ +# frozen_string_literal: true + # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) require 'rake' Dummy::Application.load_tasks diff --git a/spec/dummy/db/migrate/20110613152810_create_dummy_models.rb b/spec/dummy/db/migrate/20110613152810_create_dummy_models.rb index d1f620eb..1da7c0c7 100644 --- a/spec/dummy/db/migrate/20110613152810_create_dummy_models.rb +++ b/spec/dummy/db/migrate/20110613152810_create_dummy_models.rb @@ -1,4 +1,6 @@ -migration_class = (ActiveRecord::VERSION::MAJOR >= 5) ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration +# frozen_string_literal: true + +migration_class = ActiveRecord::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration class CreateDummyModels < migration_class def self.up create_table :companies do |t| @@ -10,24 +12,23 @@ def self.up t.string :name t.datetime :birthdate t.string :sex - end - - create_table :delayed_jobs do |t| - t.integer :priority, :default => 0 - t.integer :attempts, :default => 0 - t.text :handler - t.text :last_error - t.datetime :run_at - t.datetime :locked_at - t.datetime :failed_at - t.string :locked_by - t.datetime :created_at - t.datetime :updated_at - t.string :queue - end + end - add_index "delayed_jobs", ["priority", "run_at"], :name => "delayed_jobs_priority" + create_table :delayed_jobs do |t| + t.integer :priority, default: 0 + t.integer :attempts, default: 0 + t.text :handler + t.text :last_error + t.datetime :run_at + t.datetime :locked_at + t.datetime :failed_at + t.string :locked_by + t.datetime :created_at + t.datetime :updated_at + t.string :queue + end + add_index 'delayed_jobs', %w[priority run_at], name: 'delayed_jobs_priority' end def self.down @@ -35,5 +36,4 @@ def self.down drop_table :users drop_table :delayed_jobs end - end diff --git a/spec/dummy/db/migrate/20111202022214_create_table_books.rb b/spec/dummy/db/migrate/20111202022214_create_table_books.rb index e841e2dd..d525063d 100644 --- a/spec/dummy/db/migrate/20111202022214_create_table_books.rb +++ b/spec/dummy/db/migrate/20111202022214_create_table_books.rb @@ -1,4 +1,6 @@ -migration_class = (ActiveRecord::VERSION::MAJOR >= 5) ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration +# frozen_string_literal: true + +migration_class = ActiveRecord::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration class CreateTableBooks < migration_class def up create_table :books do |t| diff --git a/spec/dummy/db/migrate/20180415260934_create_public_tokens.rb b/spec/dummy/db/migrate/20180415260934_create_public_tokens.rb index c24c45bf..24e27249 100644 --- a/spec/dummy/db/migrate/20180415260934_create_public_tokens.rb +++ b/spec/dummy/db/migrate/20180415260934_create_public_tokens.rb @@ -1,4 +1,6 @@ -migration_class = (ActiveRecord::VERSION::MAJOR >= 5) ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration +# frozen_string_literal: true + +migration_class = ActiveRecord::VERSION::MAJOR >= 5 ? ActiveRecord::Migration[4.2] : ActiveRecord::Migration class CreatePublicTokens < migration_class def up create_table :public_tokens do |t| diff --git a/spec/dummy/db/schema.rb b/spec/dummy/db/schema.rb index 3fb281f7..ab0d1c00 100644 --- a/spec/dummy/db/schema.rb +++ b/spec/dummy/db/schema.rb @@ -1,3 +1,5 @@ +# frozen_string_literal: true + # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. @@ -10,46 +12,44 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2018_04_15_260934) do - +ActiveRecord::Schema.define(version: 20_180_415_260_934) do # These are extensions that must be enabled in order to support this database - enable_extension "plpgsql" + enable_extension 'plpgsql' - create_table "books", force: :cascade do |t| - t.string "name" - t.integer "pages" - t.datetime "published" + create_table 'books', force: :cascade do |t| + t.string 'name' + t.integer 'pages' + t.datetime 'published' end - create_table "companies", force: :cascade do |t| - t.boolean "dummy" - t.string "database" + create_table 'companies', force: :cascade do |t| + t.boolean 'dummy' + t.string 'database' end - create_table "delayed_jobs", force: :cascade do |t| - t.integer "priority", default: 0 - t.integer "attempts", default: 0 - t.text "handler" - t.text "last_error" - t.datetime "run_at" - t.datetime "locked_at" - t.datetime "failed_at" - t.string "locked_by" - t.datetime "created_at" - t.datetime "updated_at" - t.string "queue" - t.index ["priority", "run_at"], name: "delayed_jobs_priority" + create_table 'delayed_jobs', force: :cascade do |t| + t.integer 'priority', default: 0 + t.integer 'attempts', default: 0 + t.text 'handler' + t.text 'last_error' + t.datetime 'run_at' + t.datetime 'locked_at' + t.datetime 'failed_at' + t.string 'locked_by' + t.datetime 'created_at' + t.datetime 'updated_at' + t.string 'queue' + t.index %w[priority run_at], name: 'delayed_jobs_priority' end - create_table "public_tokens", id: :serial, force: :cascade do |t| - t.string "token" - t.integer "user_id" + create_table 'public_tokens', id: :serial, force: :cascade do |t| + t.string 'token' + t.integer 'user_id' end - create_table "users", force: :cascade do |t| - t.string "name" - t.datetime "birthdate" - t.string "sex" + create_table 'users', force: :cascade do |t| + t.string 'name' + t.datetime 'birthdate' + t.string 'sex' end - end diff --git a/spec/dummy/db/seeds.rb b/spec/dummy/db/seeds.rb index 4aa28df6..66ad2762 100644 --- a/spec/dummy/db/seeds.rb +++ b/spec/dummy/db/seeds.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + def create_users - 3.times {|x| User.where(name: "Some User #{x}").first_or_create! } + 3.times { |x| User.where(name: "Some User #{x}").first_or_create! } end -create_users \ No newline at end of file +create_users diff --git a/spec/dummy_engine/Gemfile b/spec/dummy_engine/Gemfile index 2ae66b0d..59f9baba 100644 --- a/spec/dummy_engine/Gemfile +++ b/spec/dummy_engine/Gemfile @@ -1,4 +1,6 @@ -source "https://rubygems.org" +# frozen_string_literal: true + +source 'https://rubygems.org' # Declare your gem's dependencies in dummy_engine.gemspec. # Bundler will treat runtime dependencies like base dependencies, and diff --git a/spec/dummy_engine/Rakefile b/spec/dummy_engine/Rakefile index 565abf87..72a61a74 100644 --- a/spec/dummy_engine/Rakefile +++ b/spec/dummy_engine/Rakefile @@ -1,3 +1,5 @@ +# frozen_string_literal: true + begin require 'bundler/setup' rescue LoadError @@ -14,11 +16,9 @@ RDoc::Task.new(:rdoc) do |rdoc| rdoc.rdoc_files.include('lib/**/*.rb') end -APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__) +APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__) load 'rails/tasks/engine.rake' - - Bundler::GemHelper.install_tasks require 'rake/testtask' @@ -30,5 +30,4 @@ Rake::TestTask.new(:test) do |t| t.verbose = false end - task default: :test diff --git a/spec/dummy_engine/bin/rails b/spec/dummy_engine/bin/rails index cb6a9e45..800e13a6 100755 --- a/spec/dummy_engine/bin/rails +++ b/spec/dummy_engine/bin/rails @@ -1,11 +1,13 @@ #!/usr/bin/env ruby +# frozen_string_literal: true + # This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. -ENGINE_ROOT = File.expand_path('../..', __FILE__) -ENGINE_PATH = File.expand_path('../../lib/dummy_engine/engine', __FILE__) +ENGINE_ROOT = File.expand_path('..', __dir__) +ENGINE_PATH = File.expand_path('../lib/dummy_engine/engine', __dir__) # Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) require 'rails/all' diff --git a/spec/dummy_engine/dummy_engine.gemspec b/spec/dummy_engine/dummy_engine.gemspec index d17f9156..6bd6cca8 100644 --- a/spec/dummy_engine/dummy_engine.gemspec +++ b/spec/dummy_engine/dummy_engine.gemspec @@ -1,24 +1,26 @@ -$:.push File.expand_path("../lib", __FILE__) +# frozen_string_literal: true + +$:.push File.expand_path('lib', __dir__) # Maintain your gem's version: -require "dummy_engine/version" +require 'dummy_engine/version' # Describe your gem and declare its dependencies: Gem::Specification.new do |s| - s.name = "dummy_engine" + s.name = 'dummy_engine' s.version = DummyEngine::VERSION - s.authors = ["Your name"] - s.email = ["Your email"] - s.homepage = "" - s.summary = "Summary of DummyEngine." - s.description = "Description of DummyEngine." - s.license = "MIT" + s.authors = ['Your name'] + s.email = ['Your email'] + s.homepage = '' + s.summary = 'Summary of DummyEngine.' + s.description = 'Description of DummyEngine.' + s.license = 'MIT' - s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] - s.test_files = Dir["test/**/*"] + s.files = Dir['{app,config,db,lib}/**/*', 'MIT-LICENSE', 'Rakefile', 'README.rdoc'] + s.test_files = Dir['test/**/*'] - s.add_dependency "rails", "~> 4.1.6" - s.add_dependency "apartment" + s.add_dependency 'apartment' + s.add_dependency 'rails', '~> 4.1.6' - s.add_development_dependency "sqlite3" + s.add_development_dependency 'sqlite3' end diff --git a/spec/dummy_engine/test/dummy/Rakefile b/spec/dummy_engine/test/dummy/Rakefile index ba6b733d..e51cf0e1 100644 --- a/spec/dummy_engine/test/dummy/Rakefile +++ b/spec/dummy_engine/test/dummy/Rakefile @@ -1,6 +1,8 @@ +# frozen_string_literal: true + # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path('config/application', __dir__) Rails.application.load_tasks From b609d483ca01ee9890389295be3dece2ade1414a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 2 Apr 2020 11:27:32 +0800 Subject: [PATCH 073/282] Remove test related files from gem --- apartment.gemspec | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/apartment.gemspec b/apartment.gemspec index 5f623e4e..4d8d1884 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -11,7 +11,15 @@ Gem::Specification.new do |s| s.summary = 'A Ruby gem for managing database multitenancy. Apartment Gem drop in replacement' s.description = 'Apartment allows Rack applications to deal with database multitenancy through ActiveRecord' s.email = ['ryan@influitive.com', 'brad@influitive.com', 'rui.p.baltazar@gmail.com'] - s.files = `git ls-files`.split($/) + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been + # added into git. + s.files = Dir.chdir(File.expand_path(__dir__)) do + `git ls-files -z`.split("\x0").reject do |f| + # NOTE: ignore all test related + f.match(%r{^(test|spec|features)/}) + end + end s.executables = s.files.grep(%r{^bin/}).map { |f| File.basename(f) } s.test_files = s.files.grep(%r{^(test|spec|features)/}) s.require_paths = ['lib'] From 23bcbbd963f6ee1b3964adadc92bef15a6089a16 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 2 Apr 2020 11:31:38 +0800 Subject: [PATCH 074/282] [Chore] fixed rubocop warning --- spec/dummy_engine/dummy_engine.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/dummy_engine/dummy_engine.gemspec b/spec/dummy_engine/dummy_engine.gemspec index 6bd6cca8..afb00e8f 100644 --- a/spec/dummy_engine/dummy_engine.gemspec +++ b/spec/dummy_engine/dummy_engine.gemspec @@ -1,6 +1,6 @@ # frozen_string_literal: true -$:.push File.expand_path('lib', __dir__) +$LOAD_PATH << File.expand_path('lib', __dir__) # Maintain your gem's version: require 'dummy_engine/version' From 2e0256b304e680e0564bc0b2b0ab3fac9514115d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 09:33:57 +0800 Subject: [PATCH 075/282] [Chore] refactored files to their names --- lib/apartment.rb | 36 ++++++++++--------- .../active_record/internal_metadata.rb | 11 ++++++ .../active_record/schema_migration.rb | 13 +++++++ lib/apartment/adapters/abstract_adapter.rb | 3 +- lib/apartment/tenant.rb | 4 ++- 5 files changed, 48 insertions(+), 19 deletions(-) create mode 100644 lib/apartment/active_record/internal_metadata.rb create mode 100644 lib/apartment/active_record/schema_migration.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index f57ac4bb..85da7624 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -7,23 +7,25 @@ require 'apartment/tenant' if ActiveRecord.version.release >= Gem::Version.new('6.1') - module ActiveRecord - class SchemaMigration < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord - class << self - def table_exists? - connection.table_exists?(table_name) - end - end - end - - class InternalMetadata < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord - class << self - def table_exists? - connection.table_exists?(table_name) - end - end - end - end + require_relative 'apartment/active_record/schema_migration' + require_relative 'apartment/active_record/internal_metadata' + # module ActiveRecord + # class SchemaMigration < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord + # class << self + # def table_exists? + # connection.table_exists?(table_name) + # end + # end + # end + + # class InternalMetadata < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord + # class << self + # def table_exists? + # connection.table_exists?(table_name) + # end + # end + # end + # end end module Apartment diff --git a/lib/apartment/active_record/internal_metadata.rb b/lib/apartment/active_record/internal_metadata.rb new file mode 100644 index 00000000..2c494990 --- /dev/null +++ b/lib/apartment/active_record/internal_metadata.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# rubocop:disable Rails/ApplicationRecord +class InternalMetadata < ActiveRecord::Base # :nodoc: + class << self + def table_exists? + connection.table_exists?(table_name) + end + end +end +# rubocop:enable Rails/ApplicationRecord diff --git a/lib/apartment/active_record/schema_migration.rb b/lib/apartment/active_record/schema_migration.rb new file mode 100644 index 00000000..7bc07360 --- /dev/null +++ b/lib/apartment/active_record/schema_migration.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module ActiveRecord + # rubocop:disable Rails/ApplicationRecord + class SchemaMigration < ActiveRecord::Base # :nodoc: + class << self + def table_exists? + connection.table_exists?(table_name) + end + end + end + # rubocop:enable Rails/ApplicationRecord +end diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 6df74679..c9a548aa 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -103,7 +103,8 @@ def each(tenants = Apartment.tenant_names) # Establish a new connection for each specific excluded model # def process_excluded_models - # All other models will shared a connection (at Apartment.connection_class) and we can modify at will + # All other models will shared a connection (at Apartment.connection_class) + # and we can modify at will Apartment.excluded_models.each do |excluded_model| process_excluded_model(excluded_model) end diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 93e755a0..bc69f9c9 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -9,7 +9,9 @@ module Tenant extend self extend Forwardable - def_delegators :adapter, :create, :drop, :switch, :switch!, :current, :each, :reset, :set_callback, :seed, :current_tenant, :default_tenant, :environmentify + def_delegators :adapter, :create, :drop, :switch, :switch!, :current, :each, + :reset, :set_callback, :seed, :current_tenant, + :default_tenant, :environmentify attr_writer :config From 3213a4e43c56261b63413fd34004f5e6bd43f2f6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 09:42:57 +0800 Subject: [PATCH 076/282] [Chore] removed commented block --- lib/apartment.rb | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 85da7624..5e7fa65f 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -9,23 +9,6 @@ if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' require_relative 'apartment/active_record/internal_metadata' - # module ActiveRecord - # class SchemaMigration < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord - # class << self - # def table_exists? - # connection.table_exists?(table_name) - # end - # end - # end - - # class InternalMetadata < ActiveRecord::Base # :nodoc: # rubocop:disable Rails/ApplicationRecord - # class << self - # def table_exists? - # connection.table_exists?(table_name) - # end - # end - # end - # end end module Apartment From 155f78857b29128ab73daf5bfd87b11040a57736 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Apr 2020 12:50:32 +0800 Subject: [PATCH 077/282] [i-27] Added tenant_connected_to to replace active record base connected_to --- lib/apartment/adapters/abstract_adapter.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index c9a548aa..bd459ccf 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -62,6 +62,18 @@ def drop(tenant) raise_drop_tenant_error!(tenant, e) end + # Add support for switching the connection as one would do using + # ActiveRecord::Base but ensuring that the schema is set that was set before + # is maintained in the new connection. When active record establishes a + # new connection, it will reset the configuration, thus setting the search + # path to the default schema + def tenant_connected_to(database: nil, role: nil, prevent_writes: false, &blk) + ActiveRecord::Base.connected_to(database: database, role: role, prevent_writes: prevent_writes) do + switch!(current) + yield(blk) + end + end + # Switch to a new tenant # # @param {String} tenant name From 12cc206c2cdaadfee5cfeda703029e2027611170 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Apr 2020 13:40:40 +0800 Subject: [PATCH 078/282] [i-27] removed special method for switching tenant and adding alias for active record --- lib/apartment.rb | 14 ++++++++++++++ lib/apartment/adapters/abstract_adapter.rb | 12 ------------ 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 5e7fa65f..aa9fa91b 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -135,3 +135,17 @@ def extract_tenant_config # The Tenant attempting to be created already exists TenantExists = Class.new(ApartmentError) end + +if ActiveRecord.version.release >= Gem::Version.new('6.0') + module ActiveRecord::ConnectionHandling + def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) + connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(Apartment::Tenant.current) + yield(blk) + end + end + + alias connected_to_without_tenant connected_to + alias connected_to connected_to_with_tenant + end +end diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index bd459ccf..c9a548aa 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -62,18 +62,6 @@ def drop(tenant) raise_drop_tenant_error!(tenant, e) end - # Add support for switching the connection as one would do using - # ActiveRecord::Base but ensuring that the schema is set that was set before - # is maintained in the new connection. When active record establishes a - # new connection, it will reset the configuration, thus setting the search - # path to the default schema - def tenant_connected_to(database: nil, role: nil, prevent_writes: false, &blk) - ActiveRecord::Base.connected_to(database: database, role: role, prevent_writes: prevent_writes) do - switch!(current) - yield(blk) - end - end - # Switch to a new tenant # # @param {String} tenant name From 2780a1e89d5077ddc365469ccff7adc6dffb2da0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 3 Apr 2020 13:41:10 +0800 Subject: [PATCH 079/282] [i-27] fix rubocop --- lib/apartment.rb | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index aa9fa91b..70661dbe 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -137,15 +137,17 @@ def extract_tenant_config end if ActiveRecord.version.release >= Gem::Version.new('6.0') - module ActiveRecord::ConnectionHandling - def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) - connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do - Apartment::Tenant.switch!(Apartment::Tenant.current) - yield(blk) + module ActiveRecord + module ConnectionHandling + def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) + connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(Apartment::Tenant.current) + yield(blk) + end end - end - alias connected_to_without_tenant connected_to - alias connected_to connected_to_with_tenant + alias connected_to_without_tenant connected_to + alias connected_to connected_to_with_tenant + end end end From d145a51f3f7fa2b22fc447a82c00eb097d8db70f Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 6 Apr 2020 10:24:09 +0800 Subject: [PATCH 080/282] [i-27] moving monkeypatches to their folders --- lib/apartment.rb | 18 ++---------------- .../active_record/connection_handling.rb | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 16 deletions(-) create mode 100644 lib/apartment/active_record/connection_handling.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 70661dbe..d436050e 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -11,6 +11,8 @@ require_relative 'apartment/active_record/internal_metadata' end +require_relative 'active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') + module Apartment class << self extend Forwardable @@ -135,19 +137,3 @@ def extract_tenant_config # The Tenant attempting to be created already exists TenantExists = Class.new(ApartmentError) end - -if ActiveRecord.version.release >= Gem::Version.new('6.0') - module ActiveRecord - module ConnectionHandling - def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) - connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do - Apartment::Tenant.switch!(Apartment::Tenant.current) - yield(blk) - end - end - - alias connected_to_without_tenant connected_to - alias connected_to connected_to_with_tenant - end - end -end diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb new file mode 100644 index 00000000..8beca085 --- /dev/null +++ b/lib/apartment/active_record/connection_handling.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module ActiveRecord + module ConnectionHandling + def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) + connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(Apartment::Tenant.current) + yield(blk) + end + end + + alias connected_to_without_tenant connected_to + alias connected_to connected_to_with_tenant + end +end From 0595ff0ae8e02ec278af78cb2f53b538efd6c262 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 6 Apr 2020 12:30:01 +0800 Subject: [PATCH 081/282] [i-27] Adding apartment model that resolves arel table based on apartment current schema --- lib/apartment.rb | 8 +++++++- lib/apartment/model.rb | 16 ++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 lib/apartment/model.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index d436050e..8e56b8af 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -11,7 +11,7 @@ require_relative 'apartment/active_record/internal_metadata' end -require_relative 'active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') +# require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') module Apartment class << self @@ -120,6 +120,12 @@ def extract_tenant_config rescue ActiveRecord::StatementInvalid {} end + + def ensure_tenant(table_name) + return table_name if table_name.include?('.') + + "#{Apartment::Tenant.current}.#{table_name}" + end end # Exceptions diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb new file mode 100644 index 00000000..1097f65d --- /dev/null +++ b/lib/apartment/model.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +module Apartment + module Model + extend ActiveSupport::Concern + + included do + def self.arel_table + final_table_name = Apartment.ensure_tenant(table_name) + return @arel_table if @arel_table && @arel_table.name == final_table_name + + @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) + end + end + end +end From e50e324f7c27caf15eddd2ec257ad398fde9c14a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 13:58:20 +0800 Subject: [PATCH 082/282] [i-27] skiping table name modification if not using schemas --- lib/apartment.rb | 16 ++++++++++++---- .../active_record/connection_handling.rb | 15 --------------- lib/apartment/model.rb | 8 ++++++-- 3 files changed, 18 insertions(+), 21 deletions(-) delete mode 100644 lib/apartment/active_record/connection_handling.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 8e56b8af..2a691290 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -11,8 +11,6 @@ require_relative 'apartment/active_record/internal_metadata' end -# require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') - module Apartment class << self extend Forwardable @@ -104,7 +102,9 @@ def pg_excluded_names # Reset all the config for Apartment def reset - (ACCESSOR_METHODS + WRITER_METHODS).each { |method| remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") } + (ACCESSOR_METHODS + WRITER_METHODS).each do |method| + remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") + end end def extract_tenant_config @@ -121,8 +121,16 @@ def extract_tenant_config {} end + # used to ensure that the tenant name is included in the table name + # resolution when using schemas (Postgres). This will eventually + # allow us to skip setting the search path but rather query the tables + # directly. This also means that we will be allowed to keep the prepared + # statements instead of clearing the cache on every switch def ensure_tenant(table_name) - return table_name if table_name.include?('.') + # NOTE: Only postgres supports schemas, so prepending tenant name + # as part of the table name is only available if configuration + # specifies use_schemas + return table_name if table_name.include?('.') || !Apartment.use_schemas "#{Apartment::Tenant.current}.#{table_name}" end diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb deleted file mode 100644 index 8beca085..00000000 --- a/lib/apartment/active_record/connection_handling.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -module ActiveRecord - module ConnectionHandling - def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) - connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do - Apartment::Tenant.switch!(Apartment::Tenant.current) - yield(blk) - end - end - - alias connected_to_without_tenant connected_to - alias connected_to connected_to_with_tenant - end -end diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index 1097f65d..fbed93fc 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -4,13 +4,17 @@ module Apartment module Model extend ActiveSupport::Concern - included do - def self.arel_table + module ClassMethods + def arel_table final_table_name = Apartment.ensure_tenant(table_name) return @arel_table if @arel_table && @arel_table.name == final_table_name @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) end end + # included do + # def self.arel_table + # end + # end end end From b513bd87547085ca4078e241155598a2858c1469 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 13:59:34 +0800 Subject: [PATCH 083/282] [i-27] removed commented code --- lib/apartment/model.rb | 4 ---- 1 file changed, 4 deletions(-) diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index fbed93fc..9a021d3e 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -12,9 +12,5 @@ def arel_table @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) end end - # included do - # def self.arel_table - # end - # end end end From 72c0c322dfa1dd3ef31d26a951b76ffc1293d710 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 14:07:28 +0800 Subject: [PATCH 084/282] [i-27] using config to enable schema prepend --- lib/apartment.rb | 4 +++- lib/apartment/railtie.rb | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 2a691290..dcec062e 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -16,7 +16,8 @@ class << self extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment - append_environment with_multi_server_setup].freeze + append_environment with_multi_server_setup + allow_prepend_tenant_name].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class @@ -127,6 +128,7 @@ def extract_tenant_config # directly. This also means that we will be allowed to keep the prepared # statements instead of clearing the cache on every switch def ensure_tenant(table_name) + return table_name unless Apartment.allow_prepend_tenant_name # NOTE: Only postgres supports schemas, so prepending tenant name # as part of the table name is only available if configuration # specifies use_schemas diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 647b221c..7ff83b1a 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -18,6 +18,7 @@ class Railtie < Rails::Railtie config.seed_after_create = false config.prepend_environment = false config.append_environment = false + config.allow_prepend_tenant_name = false end ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a From ed71488d153584477bf89b11bdebd3d6befcb58c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 14:08:50 +0800 Subject: [PATCH 085/282] [i-27] added prepend_tenant_name config to spec --- spec/unit/config_spec.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index cceaa7e4..e486dac9 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -35,6 +35,14 @@ def tenant_names_from_array(names) expect(Apartment.use_schemas).to be false end + it 'should set allow_prepend_tenant_name' do + Apartment.configure do |config| + config.excluded_models = [] + config.allow_prepend_tenant_name = true + end + expect(Apartment.allow_prepend_tenant_name).to be true + end + it 'should set seed_data_file' do Apartment.configure do |config| config.seed_data_file = seed_data_file_path From 94de7f6b3801c62c0fd976fe4c4e228b328544af Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 14:26:08 +0800 Subject: [PATCH 086/282] [i-27] renamed method --- lib/apartment.rb | 2 +- lib/apartment/model.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index dcec062e..13dbeae3 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -127,7 +127,7 @@ def extract_tenant_config # allow us to skip setting the search path but rather query the tables # directly. This also means that we will be allowed to keep the prepared # statements instead of clearing the cache on every switch - def ensure_tenant(table_name) + def table_name_with_tenant(table_name) return table_name unless Apartment.allow_prepend_tenant_name # NOTE: Only postgres supports schemas, so prepending tenant name # as part of the table name is only available if configuration diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index 9a021d3e..07b78cf5 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -6,7 +6,7 @@ module Model module ClassMethods def arel_table - final_table_name = Apartment.ensure_tenant(table_name) + final_table_name = Apartment.table_name_with_tenant(table_name) return @arel_table if @arel_table && @arel_table.name == final_table_name @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) From 2d1819d326bc39542bc0d7c546943e9c46f972ba Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 15:29:37 +0800 Subject: [PATCH 087/282] [i-27] attempt to run tests with apartment model --- gemfiles/rails_5_0.gemfile | 2 +- gemfiles/rails_5_1.gemfile | 2 +- gemfiles/rails_5_2.gemfile | 2 +- gemfiles/rails_6_0.gemfile | 2 +- gemfiles/rails_master.gemfile | 2 +- spec/adapters/postgresql_adapter_spec.rb | 14 ++++++++++++++ spec/dummy/app/models/user_with_tenant_model.rb | 8 ++++++++ 7 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 spec/dummy/app/models/user_with_tenant_model.rb diff --git a/gemfiles/rails_5_0.gemfile b/gemfiles/rails_5_0.gemfile index a3d3a72c..e963b5b3 100644 --- a/gemfiles/rails_5_0.gemfile +++ b/gemfiles/rails_5_0.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "rails", "~> 5.0.0" gem "perx-rubocop", "~> 0.0.3" +gem "rails", "~> 5.0.0" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_5_1.gemfile b/gemfiles/rails_5_1.gemfile index 7c75050b..8785b959 100644 --- a/gemfiles/rails_5_1.gemfile +++ b/gemfiles/rails_5_1.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "rails", "~> 5.1.0" gem "perx-rubocop", "~> 0.0.3" +gem "rails", "~> 5.1.0" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_5_2.gemfile b/gemfiles/rails_5_2.gemfile index 09ae9502..1afc645b 100644 --- a/gemfiles/rails_5_2.gemfile +++ b/gemfiles/rails_5_2.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "rails", "~> 5.2.0" gem "perx-rubocop", "~> 0.0.3" +gem "rails", "~> 5.2.0" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_6_0.gemfile b/gemfiles/rails_6_0.gemfile index 5559b2e8..6c3d3968 100644 --- a/gemfiles/rails_6_0.gemfile +++ b/gemfiles/rails_6_0.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "rails", "~> 6.0.0" gem "perx-rubocop", "~> 0.0.3" +gem "rails", "~> 6.0.0" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_master.gemfile b/gemfiles/rails_master.gemfile index dd8bccf6..f2add08a 100644 --- a/gemfiles/rails_master.gemfile +++ b/gemfiles/rails_master.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "rails", git: "https://github.com/rails/rails.git" gem "perx-rubocop", "~> 0.0.3" +gem "rails", git: "https://github.com/rails/rails.git" group :local do gem "guard-rspec", "~> 4.2" diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index d553ff8b..8fbbfbff 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -20,6 +20,20 @@ def tenant_names it_should_behave_like 'a generic apartment adapter' it_should_behave_like 'a schema based apartment adapter' + + context 'using allow_prepend_tenant_name' do + let(:schema1) { db1 } + + before do + Apartment.allow_prepend_tenant_name = true + Apartment::Tenant.init + end + + it 'prepends the tenant schema name to the table name' do + Apartment::Tenant.switch!(schema1) + expect(UserWithTenantModel.table_name).to eq("#{schema1}.users") + end + end end context 'using schemas with SQL dump' do diff --git a/spec/dummy/app/models/user_with_tenant_model.rb b/spec/dummy/app/models/user_with_tenant_model.rb new file mode 100644 index 00000000..468d2fec --- /dev/null +++ b/spec/dummy/app/models/user_with_tenant_model.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class UserWithTenantModel < ApplicationRecord + include Apartment::Model + + self.table_name = 'users' + # Dummy models +end From 421d82525fb44d0213aaf9e8b1684c2fb25b267e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 15:57:46 +0800 Subject: [PATCH 088/282] [i-27] updating test --- spec/adapters/postgresql_adapter_spec.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 8fbbfbff..e40f749d 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -29,9 +29,10 @@ def tenant_names Apartment::Tenant.init end - it 'prepends the tenant schema name to the table name' do + it 'prepends the tenant schema name to the table name when building the query' do Apartment::Tenant.switch!(schema1) - expect(UserWithTenantModel.table_name).to eq("#{schema1}.users") + sql = "SELECT \"#{schema1}\".\"users\".* FROM \"#{schema1}\".\"users\" LIMIT 10" + expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) end end end From 651288ced288e3d7ed451f461c3107a2fa90d917 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 16:19:42 +0800 Subject: [PATCH 089/282] [i-27] creating schema --- spec/adapters/postgresql_adapter_spec.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index e40f749d..4c9242a1 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -25,6 +25,7 @@ def tenant_names let(:schema1) { db1 } before do + subject.create(schema1) Apartment.allow_prepend_tenant_name = true Apartment::Tenant.init end From be771edf1d36e5ada5839abe532cb076e53f3d5b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 17:43:12 +0800 Subject: [PATCH 090/282] [i-27] fix test setup --- spec/adapters/postgresql_adapter_spec.rb | 11 ++++++----- spec/dummy/app/models/user_with_tenant_model.rb | 2 ++ 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 4c9242a1..22c2a1c1 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -22,17 +22,18 @@ def tenant_names it_should_behave_like 'a schema based apartment adapter' context 'using allow_prepend_tenant_name' do - let(:schema1) { db1 } + let(:api) { Apartment::Tenant } before do - subject.create(schema1) + Apartment.reset Apartment.allow_prepend_tenant_name = true - Apartment::Tenant.init + api.create(db1) + api.create(db2) end it 'prepends the tenant schema name to the table name when building the query' do - Apartment::Tenant.switch!(schema1) - sql = "SELECT \"#{schema1}\".\"users\".* FROM \"#{schema1}\".\"users\" LIMIT 10" + Apartment::Tenant.switch!(db1) + sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) end end diff --git a/spec/dummy/app/models/user_with_tenant_model.rb b/spec/dummy/app/models/user_with_tenant_model.rb index 468d2fec..9871d748 100644 --- a/spec/dummy/app/models/user_with_tenant_model.rb +++ b/spec/dummy/app/models/user_with_tenant_model.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require 'apartment/model' + class UserWithTenantModel < ApplicationRecord include Apartment::Model From 79e07f4cd4d3b738a86be936c09c3d1069f665a6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 17:45:53 +0800 Subject: [PATCH 091/282] [i-27] fix failing test --- spec/adapters/postgresql_adapter_spec.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 22c2a1c1..94167202 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -25,7 +25,6 @@ def tenant_names let(:api) { Apartment::Tenant } before do - Apartment.reset Apartment.allow_prepend_tenant_name = true api.create(db1) api.create(db2) @@ -35,6 +34,10 @@ def tenant_names Apartment::Tenant.switch!(db1) sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + + Apartment::Tenant.switch!(db2) + sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" + expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) end end end From 6e6159170c238c655e244319017071c68d874bbd Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 17:47:44 +0800 Subject: [PATCH 092/282] [i-27] duplicate test coverage for jdbc postgresql adapter --- spec/adapters/jdbc_postgresql_adapter_spec.rb | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index 49dfaf1a..f7635af4 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -20,6 +20,27 @@ def tenant_names it_should_behave_like 'a generic apartment adapter' it_should_behave_like 'a schema based apartment adapter' + + context 'using allow_prepend_tenant_name' do + let(:api) { Apartment::Tenant } + + before do + Apartment.allow_prepend_tenant_name = true + api.create(db1) + api.create(db2) + end + + it 'prepends the tenant schema name to the table name when building the query' do + Apartment::Tenant.switch!(db1) + sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" + expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + + Apartment::Tenant.switch!(db2) + sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" + expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + end + end + end context 'using databases' do From 23e9e1e133cbe681e1b61c31cf8ca808f91db9dc Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 18:03:14 +0800 Subject: [PATCH 093/282] [i-27] fix rubocop --- spec/adapters/jdbc_postgresql_adapter_spec.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index f7635af4..1198aeda 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -40,7 +40,6 @@ def tenant_names expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) end end - end context 'using databases' do From d3e695ee66a96820624a97c838f9b382911a9a7c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 18:33:43 +0800 Subject: [PATCH 094/282] [i-27] updated readme --- README.md | 51 +++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 4694ed26..81d9aa95 100644 --- a/README.md +++ b/README.md @@ -341,7 +341,42 @@ Rails will always access the 'public' tenant when accessing these models, but no ### Postgresql Schemas -## Providing a Different default_schema +#### Allow prepend tenant name + +`config.allow_prepend_tenant_name` currently defaults to `false`. + +This configuration only applies while using postgres adapter and `config.use_schemas` is set to `true`. +This is also intended to be used in combination with `Apartment::Model` module. What this module +does is to overwrite the `arel_table` method, used internally by Rails to create the arel_table +object and build the final SQL query to include the apartment's current tenant schema name. +This becomes particularly helpful when we have read/write replicas in our rails application and +we need to switch the connection between read and write DB. +When in our application we run `SomeModel.connected_to(role: :reading)` this will switch the connection but also reset the schema that it is pointing to. + +The alternative to this is whenever you switch the connection manually, ensure that you switch to +the expected schema as well. E.g. + +```ruby +ActiveRecord::Base.connected_to(role: :reading) do + Apartment::Tenant.switch!(your_schema) + do_your_logic +end +``` + +#### Alternative: Creating new schemas by using raw SQL dumps + +Apartment can be forced to use raw SQL dumps insted of `schema.rb` for creating new schemas. Use this when you are using some extra features in postgres that can't be represented in `schema.rb`, like materialized views etc. + +This only applies while using postgres adapter and `config.use_schemas` is set to `true`. +(Note: this option doesn't use `db/structure.sql`, it creates SQL dump by executing `pg_dump`) + +Enable this option with: + +```ruby +config.use_sql = true +``` + +### Providing a Different default_schema By default, ActiveRecord will use `"$user", public` as the default `schema_search_path`. This can be modified if you wish to use a different default schema be setting: @@ -351,7 +386,7 @@ config.default_schema = "some_other_schema" With that set, all excluded models will use this schema as the table name prefix instead of `public` and `reset` on `Apartment::Tenant` will return to this schema as well. -## Persistent Schemas +### Persistent Schemas Apartment will normally just switch the `schema_search_path` whole hog to the one passed in. This can lead to problems if you want other schemas to always be searched as well. Enter `persistent_schemas`. You can configure a list of other schemas that will always remain in the search path, while the default gets swapped out: @@ -457,18 +492,6 @@ schema in the `search_path` at all times. We won't be able to do this though unt also contain the tenanted tables, which is an open issue with no real milestone to be completed. Happy to accept PR's on the matter. -#### Alternative: Creating new schemas by using raw SQL dumps - -Apartment can be forced to use raw SQL dumps insted of `schema.rb` for creating new schemas. Use this when you are using some extra features in postgres that can't be represented in `schema.rb`, like materialized views etc. - -This only applies while using postgres adapter and `config.use_schemas` is set to `true`. -(Note: this option doesn't use `db/structure.sql`, it creates SQL dump by executing `pg_dump`) - -Enable this option with: -```ruby -config.use_sql = true -``` - ### Managing Migrations In order to migrate all of your tenants (or postgresql schemas) you need to provide a list From 27fc97ae32e5c24d75c8547b700ead504b5c6aa3 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 18:37:53 +0800 Subject: [PATCH 095/282] [i-27] remove extra whitespaces --- spec/adapters/jdbc_postgresql_adapter_spec.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index 1198aeda..644c5fe6 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -33,11 +33,12 @@ def tenant_names it 'prepends the tenant schema name to the table name when building the query' do Apartment::Tenant.switch!(db1) sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + # NOTE: for some reason there is an extra space in the output of to_sql + expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) Apartment::Tenant.switch!(db2) sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) end end end From 29c743402e4b1c3ed1c57f11a4acaf2837452d26 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 7 Apr 2020 19:06:34 +0800 Subject: [PATCH 096/282] [i-27] for some reason there is an extra space in the output of to_sql --- spec/adapters/postgresql_adapter_spec.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 94167202..ca8525e7 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -33,11 +33,12 @@ def tenant_names it 'prepends the tenant schema name to the table name when building the query' do Apartment::Tenant.switch!(db1) sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + # NOTE: for some reason there is an extra space in the output of to_sql + expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) Apartment::Tenant.switch!(db2) sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql).to eq(sql) + expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) end end end From f5b833f43fd5cce28bfb20d50fa5281d35c77934 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 19:56:47 +0800 Subject: [PATCH 097/282] using the other approach for updating the tenant based on the connection switch --- lib/apartment.rb | 2 ++ .../active_record/connection_handling.rb | 15 +++++++++++++++ lib/apartment/model.rb | 14 +++++++------- 3 files changed, 24 insertions(+), 7 deletions(-) create mode 100644 lib/apartment/active_record/connection_handling.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 13dbeae3..e2ac9f6e 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,6 +6,8 @@ require 'active_record' require 'apartment/tenant' +require_relative 'active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') + if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' require_relative 'apartment/active_record/internal_metadata' diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb new file mode 100644 index 00000000..8beca085 --- /dev/null +++ b/lib/apartment/active_record/connection_handling.rb @@ -0,0 +1,15 @@ +# frozen_string_literal: true + +module ActiveRecord + module ConnectionHandling + def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) + connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(Apartment::Tenant.current) + yield(blk) + end + end + + alias connected_to_without_tenant connected_to + alias connected_to connected_to_with_tenant + end +end diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index 07b78cf5..e8b3d5d8 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -4,13 +4,13 @@ module Apartment module Model extend ActiveSupport::Concern - module ClassMethods - def arel_table - final_table_name = Apartment.table_name_with_tenant(table_name) - return @arel_table if @arel_table && @arel_table.name == final_table_name + # module ClassMethods + # def arel_table + # final_table_name = Apartment.table_name_with_tenant(table_name) + # return @arel_table if @arel_table && @arel_table.name == final_table_name - @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) - end - end + # @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) + # end + # end end end From 55368fb9ca8cf0ba897816d04e91615f3b0a9337 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 19:57:30 +0800 Subject: [PATCH 098/282] Fixed loading path --- lib/apartment.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index e2ac9f6e..eb4c4951 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,7 +6,7 @@ require 'active_record' require 'apartment/tenant' -require_relative 'active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') +require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' From c6eda8edf4fd633f83eaf6a70cf740698f97253d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 20:37:19 +0800 Subject: [PATCH 099/282] patch postgresql arel visit table to determine which schema to use --- lib/apartment.rb | 4 +++- lib/apartment/arel/visitors/postgresql.rb | 28 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 lib/apartment/arel/visitors/postgresql.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index eb4c4951..def7c128 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,7 +6,9 @@ require 'active_record' require 'apartment/tenant' -require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') +# require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') + +require_relative 'apartment/arel/visitors/postgresql' if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' diff --git a/lib/apartment/arel/visitors/postgresql.rb b/lib/apartment/arel/visitors/postgresql.rb new file mode 100644 index 00000000..9d3751e2 --- /dev/null +++ b/lib/apartment/arel/visitors/postgresql.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +module Arel # :nodoc: all + module Visitors + class PostgreSQL < Arel::Visitors::ToSql + private + + def visit_Arel_Table(o, collector) + if o.table_alias + collector << quoted_table_name_with_tenant(o.name) << " " << quote_table_name(o.table_alias) + else + collector << quoted_table_name_with_tenant(o.name) + end + end + + def quoted_table_name_with_tenant(table_name) + # NOTE: Only postgres supports schemas, so prepending tenant name + # as part of the table name is only available if configuration + # specifies use_schemas + if Apartment.allow_prepend_tenant_name && Apartment.use_schemas && !table_name.include?('.') + quote_table_name("#{Apartment::Tenant.current}.#{table_name}") + else + quote_table_name(table_name) + end + end + end + end +end From f78afc9deaa0248a6115d50a8adc182cd2b12df3 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 21:14:54 +0800 Subject: [PATCH 100/282] cached find by statement to use tenant for cache key --- lib/apartment.rb | 17 ----------------- .../active_record/connection_handling.rb | 15 --------------- lib/apartment/model.rb | 15 +++++++-------- 3 files changed, 7 insertions(+), 40 deletions(-) delete mode 100644 lib/apartment/active_record/connection_handling.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index def7c128..36e6cb98 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,8 +6,6 @@ require 'active_record' require 'apartment/tenant' -# require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') - require_relative 'apartment/arel/visitors/postgresql' if ActiveRecord.version.release >= Gem::Version.new('6.1') @@ -125,21 +123,6 @@ def extract_tenant_config rescue ActiveRecord::StatementInvalid {} end - - # used to ensure that the tenant name is included in the table name - # resolution when using schemas (Postgres). This will eventually - # allow us to skip setting the search path but rather query the tables - # directly. This also means that we will be allowed to keep the prepared - # statements instead of clearing the cache on every switch - def table_name_with_tenant(table_name) - return table_name unless Apartment.allow_prepend_tenant_name - # NOTE: Only postgres supports schemas, so prepending tenant name - # as part of the table name is only available if configuration - # specifies use_schemas - return table_name if table_name.include?('.') || !Apartment.use_schemas - - "#{Apartment::Tenant.current}.#{table_name}" - end end # Exceptions diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb deleted file mode 100644 index 8beca085..00000000 --- a/lib/apartment/active_record/connection_handling.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -module ActiveRecord - module ConnectionHandling - def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) - connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do - Apartment::Tenant.switch!(Apartment::Tenant.current) - yield(blk) - end - end - - alias connected_to_without_tenant connected_to - alias connected_to connected_to_with_tenant - end -end diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index e8b3d5d8..0df0e379 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -4,13 +4,12 @@ module Apartment module Model extend ActiveSupport::Concern - # module ClassMethods - # def arel_table - # final_table_name = Apartment.table_name_with_tenant(table_name) - # return @arel_table if @arel_table && @arel_table.name == final_table_name - - # @arel_table = Arel::Table.new(final_table_name, type_caster: type_caster) - # end - # end + module ClassMethods + def cached_find_by_statement(key, &block) + cache_key = "#{Apartment::Tenant.current}_#{key}".to_sym + cache = @find_by_statement_cache[connection.prepared_statements] + cache.compute_if_absent(cache_key) { ActiveRecord::StatementCache.create(connection, &block) } + end + end end end From b0ad53c14fa5f5662482478c70f758ca68c58d19 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 21:26:15 +0800 Subject: [PATCH 101/282] Address rubocop errors --- lib/apartment/arel/visitors/postgresql.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/apartment/arel/visitors/postgresql.rb b/lib/apartment/arel/visitors/postgresql.rb index 9d3751e2..43d98257 100644 --- a/lib/apartment/arel/visitors/postgresql.rb +++ b/lib/apartment/arel/visitors/postgresql.rb @@ -5,13 +5,17 @@ module Visitors class PostgreSQL < Arel::Visitors::ToSql private + # rubocop:disable Naming/MethodName + # rubocop:disable Naming/MethodParameterName def visit_Arel_Table(o, collector) if o.table_alias - collector << quoted_table_name_with_tenant(o.name) << " " << quote_table_name(o.table_alias) + collector << quoted_table_name_with_tenant(o.name) << ' ' << quote_table_name(o.table_alias) else collector << quoted_table_name_with_tenant(o.name) end end + # rubocop:enable Naming/MethodParameterName + # rubocop:enable Naming/MethodName def quoted_table_name_with_tenant(table_name) # NOTE: Only postgres supports schemas, so prepending tenant name From b6bdcdfeca5365ccb4d4d801c725cd14a2e1f68c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 21:33:57 +0800 Subject: [PATCH 102/282] Fixed failing specs --- spec/adapters/jdbc_postgresql_adapter_spec.rb | 4 ++-- spec/adapters/postgresql_adapter_spec.rb | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index 644c5fe6..c78c351e 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -32,12 +32,12 @@ def tenant_names it 'prepends the tenant schema name to the table name when building the query' do Apartment::Tenant.switch!(db1) - sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" + sql = "SELECT \"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" # NOTE: for some reason there is an extra space in the output of to_sql expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) Apartment::Tenant.switch!(db2) - sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" + sql = "SELECT \"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) end end diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index ca8525e7..f1adcaec 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -32,12 +32,12 @@ def tenant_names it 'prepends the tenant schema name to the table name when building the query' do Apartment::Tenant.switch!(db1) - sql = "SELECT \"#{db1}\".\"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" + sql = "SELECT \"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" # NOTE: for some reason there is an extra space in the output of to_sql expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) Apartment::Tenant.switch!(db2) - sql = "SELECT \"#{db2}\".\"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" + sql = "SELECT \"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) end end From d141639f3b6a809e1911fd956519f589d1124e5c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 9 Apr 2020 09:45:51 +0800 Subject: [PATCH 103/282] Fixed cache key format. Added notes on cached find_by_statement --- lib/apartment/model.rb | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index 0df0e379..be03b2b4 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -5,8 +5,14 @@ module Model extend ActiveSupport::Concern module ClassMethods + # NOTE: key is actually an array of keys. E.g. If we run the following + # query: `Setting.find_by(key: 'something', value: 'amazing')` key will + # have an array of symbols: `[:key, :something]` def cached_find_by_statement(key, &block) - cache_key = "#{Apartment::Tenant.current}_#{key}".to_sym + # Modifying the cache key to have a reference to the current tenant, + # so the cached statement is referring only to the tenant in which we've + # executed this + cache_key = [Apartment::Tenant.current] + key cache = @find_by_statement_cache[connection.prepared_statements] cache.compute_if_absent(cache_key) { ActiveRecord::StatementCache.create(connection, &block) } end From 5d76a8cfde70a467ec6e0a8a22c52d55fbedb29c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 11:00:43 +0800 Subject: [PATCH 104/282] [#31] Updated travis ruby versions --- .travis.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 14a51e2f..e3db764e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,9 +5,10 @@ services: - docker rvm: - jruby-9.2.11.0 - - 2.4.3 - - 2.5.0 - - 2.6.2 + - 2.4.10 + - 2.5.8 + - 2.6.6 + - 2.7.1 - ruby-head branches: @@ -37,8 +38,5 @@ jobs: allow_failures: - rvm: ruby-head - gemfile: gemfiles/rails_master.gemfile - exclude: - - rvm: 2.4.3 - gemfile: gemfiles/rails_6_0.gemfile fast_finish: true cache: bundler From 0ba04de68fb1bfb7ec153e0d1bda13cfd4d7cadb Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 11:03:10 +0800 Subject: [PATCH 105/282] [#31] Added jruby head to test matrix --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index e3db764e..fc7b1f3c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ rvm: - 2.5.8 - 2.6.6 - 2.7.1 + - jruby-head - ruby-head branches: @@ -37,6 +38,7 @@ env: jobs: allow_failures: - rvm: ruby-head + - rvm: jruby-head - gemfile: gemfiles/rails_master.gemfile fast_finish: true cache: bundler From 6d754f58ad3260b320a3d0da3e693b51e638dc6c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 11:26:43 +0800 Subject: [PATCH 106/282] [#31] Excluding 2.4.10 and rails 6 combination --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.travis.yml b/.travis.yml index fc7b1f3c..ec00e229 100644 --- a/.travis.yml +++ b/.travis.yml @@ -40,5 +40,8 @@ jobs: - rvm: ruby-head - rvm: jruby-head - gemfile: gemfiles/rails_master.gemfile + exclude: + - rvm: 2.4.10 + gemfile: gemfiles/rails_6_0.gemfile fast_finish: true cache: bundler From 80bb3a4d7ac8fb4d6e3d959c45fa7e5ac40f3911 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 8 Apr 2020 11:47:04 +0800 Subject: [PATCH 107/282] [#31] Using bundler 2.x --- .travis.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index ec00e229..6dd15e76 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,9 +29,6 @@ before_install: - sudo /etc/init.d/mysql stop - sudo /etc/init.d/postgresql stop - docker-compose up -d - - gem uninstall -v '>= 2' -i $(rvm gemdir)@global -ax bundler || true - - gem uninstall bundler -v '>= 2' -x || true - - gem install bundler -v '< 2' env: RUBY_GC_MALLOC_LIMIT: 90000000 RUBY_GC_HEAP_FREE_SLOTS: 200000 From e260dfc424933d85b70ac2e6e92a5347c346258e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 9 Apr 2020 10:29:36 +0800 Subject: [PATCH 108/282] [#31] relaxed bundler development dependency --- apartment.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apartment.gemspec b/apartment.gemspec index 4d8d1884..cdd419a7 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -34,7 +34,7 @@ Gem::Specification.new do |s| s.add_dependency 'rack', '>= 1.3.6', '< 3.0' s.add_development_dependency 'appraisal', '~> 2.2' - s.add_development_dependency 'bundler', '>= 1.3', '< 2.0' + s.add_development_dependency 'bundler', '>= 1.3', '< 3.0' s.add_development_dependency 'capybara', '~> 2.0' s.add_development_dependency 'rake', '~> 0.9' s.add_development_dependency 'rspec', '~> 3.4' From 8b4723d75df658548e2fa0373a547126ec2656f6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 9 Apr 2020 11:17:59 +0800 Subject: [PATCH 109/282] [#35] update cache key to use a string or an array depending on what we get --- lib/apartment/model.rb | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/apartment/model.rb b/lib/apartment/model.rb index be03b2b4..5a75a140 100644 --- a/lib/apartment/model.rb +++ b/lib/apartment/model.rb @@ -5,14 +5,20 @@ module Model extend ActiveSupport::Concern module ClassMethods - # NOTE: key is actually an array of keys. E.g. If we run the following - # query: `Setting.find_by(key: 'something', value: 'amazing')` key will - # have an array of symbols: `[:key, :something]` + # NOTE: key can either be an array of symbols or a single value. + # E.g. If we run the following query: + # `Setting.find_by(key: 'something', value: 'amazing')` key will have an array of symbols: `[:key, :something]` + # while if we run: + # `Setting.find(10)` key will have the value 'id' def cached_find_by_statement(key, &block) # Modifying the cache key to have a reference to the current tenant, # so the cached statement is referring only to the tenant in which we've # executed this - cache_key = [Apartment::Tenant.current] + key + cache_key = if key.is_a? String + "#{Apartment::Tenant.current}_#{key}" + else + [Apartment::Tenant.current] + key + end cache = @find_by_statement_cache[connection.prepared_statements] cache.compute_if_absent(cache_key) { ActiveRecord::StatementCache.create(connection, &block) } end From b27311d3837f99a1db2467a43c87b1b586b88975 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 14 Apr 2020 15:12:18 +0800 Subject: [PATCH 110/282] Added before hook to connected to to try to set the tenant --- lib/apartment.rb | 4 +++- .../active_record/connection_handling.rb | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 lib/apartment/active_record/connection_handling.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 36e6cb98..42c85398 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,7 +6,9 @@ require 'active_record' require 'apartment/tenant' -require_relative 'apartment/arel/visitors/postgresql' +# require_relative 'apartment/arel/visitors/postgresql' + +require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb new file mode 100644 index 00000000..c9c1056f --- /dev/null +++ b/lib/apartment/active_record/connection_handling.rb @@ -0,0 +1,17 @@ +# frozen_string_literal: true + +module ActiveRecord + module ConnectionHandling + def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) + current_tenant = Apartment::Tenant.current + + connected_to_without_tenant(database: database, role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(current_tenant) + yield(blk) + end + end + + alias connected_to_without_tenant connected_to + alias connected_to connected_to_with_tenant + end +end From 3fa374ad9e4920eb61da779c78b998c2f6e54d19 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 15 Apr 2020 11:03:56 +0800 Subject: [PATCH 111/282] [Chore] Removed references to allow prepend tenant name --- README.md | 22 ------------- lib/apartment.rb | 3 +- lib/apartment/arel/visitors/postgresql.rb | 32 ------------------- lib/apartment/railtie.rb | 1 - spec/adapters/jdbc_postgresql_adapter_spec.rb | 21 ------------ spec/adapters/postgresql_adapter_spec.rb | 21 ------------ spec/unit/config_spec.rb | 8 ----- 7 files changed, 1 insertion(+), 107 deletions(-) delete mode 100644 lib/apartment/arel/visitors/postgresql.rb diff --git a/README.md b/README.md index 81d9aa95..3ac0b6fc 100644 --- a/README.md +++ b/README.md @@ -341,28 +341,6 @@ Rails will always access the 'public' tenant when accessing these models, but no ### Postgresql Schemas -#### Allow prepend tenant name - -`config.allow_prepend_tenant_name` currently defaults to `false`. - -This configuration only applies while using postgres adapter and `config.use_schemas` is set to `true`. -This is also intended to be used in combination with `Apartment::Model` module. What this module -does is to overwrite the `arel_table` method, used internally by Rails to create the arel_table -object and build the final SQL query to include the apartment's current tenant schema name. -This becomes particularly helpful when we have read/write replicas in our rails application and -we need to switch the connection between read and write DB. -When in our application we run `SomeModel.connected_to(role: :reading)` this will switch the connection but also reset the schema that it is pointing to. - -The alternative to this is whenever you switch the connection manually, ensure that you switch to -the expected schema as well. E.g. - -```ruby -ActiveRecord::Base.connected_to(role: :reading) do - Apartment::Tenant.switch!(your_schema) - do_your_logic -end -``` - #### Alternative: Creating new schemas by using raw SQL dumps Apartment can be forced to use raw SQL dumps insted of `schema.rb` for creating new schemas. Use this when you are using some extra features in postgres that can't be represented in `schema.rb`, like materialized views etc. diff --git a/lib/apartment.rb b/lib/apartment.rb index 42c85398..9c0d664e 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -20,8 +20,7 @@ class << self extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment - append_environment with_multi_server_setup - allow_prepend_tenant_name].freeze + append_environment with_multi_server_setup].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class diff --git a/lib/apartment/arel/visitors/postgresql.rb b/lib/apartment/arel/visitors/postgresql.rb deleted file mode 100644 index 43d98257..00000000 --- a/lib/apartment/arel/visitors/postgresql.rb +++ /dev/null @@ -1,32 +0,0 @@ -# frozen_string_literal: true - -module Arel # :nodoc: all - module Visitors - class PostgreSQL < Arel::Visitors::ToSql - private - - # rubocop:disable Naming/MethodName - # rubocop:disable Naming/MethodParameterName - def visit_Arel_Table(o, collector) - if o.table_alias - collector << quoted_table_name_with_tenant(o.name) << ' ' << quote_table_name(o.table_alias) - else - collector << quoted_table_name_with_tenant(o.name) - end - end - # rubocop:enable Naming/MethodParameterName - # rubocop:enable Naming/MethodName - - def quoted_table_name_with_tenant(table_name) - # NOTE: Only postgres supports schemas, so prepending tenant name - # as part of the table name is only available if configuration - # specifies use_schemas - if Apartment.allow_prepend_tenant_name && Apartment.use_schemas && !table_name.include?('.') - quote_table_name("#{Apartment::Tenant.current}.#{table_name}") - else - quote_table_name(table_name) - end - end - end - end -end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 7ff83b1a..647b221c 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -18,7 +18,6 @@ class Railtie < Rails::Railtie config.seed_after_create = false config.prepend_environment = false config.append_environment = false - config.allow_prepend_tenant_name = false end ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index c78c351e..49dfaf1a 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -20,27 +20,6 @@ def tenant_names it_should_behave_like 'a generic apartment adapter' it_should_behave_like 'a schema based apartment adapter' - - context 'using allow_prepend_tenant_name' do - let(:api) { Apartment::Tenant } - - before do - Apartment.allow_prepend_tenant_name = true - api.create(db1) - api.create(db2) - end - - it 'prepends the tenant schema name to the table name when building the query' do - Apartment::Tenant.switch!(db1) - sql = "SELECT \"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" - # NOTE: for some reason there is an extra space in the output of to_sql - expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) - - Apartment::Tenant.switch!(db2) - sql = "SELECT \"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) - end - end end context 'using databases' do diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index f1adcaec..d553ff8b 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -20,27 +20,6 @@ def tenant_names it_should_behave_like 'a generic apartment adapter' it_should_behave_like 'a schema based apartment adapter' - - context 'using allow_prepend_tenant_name' do - let(:api) { Apartment::Tenant } - - before do - Apartment.allow_prepend_tenant_name = true - api.create(db1) - api.create(db2) - end - - it 'prepends the tenant schema name to the table name when building the query' do - Apartment::Tenant.switch!(db1) - sql = "SELECT \"users\".* FROM \"#{db1}\".\"users\" LIMIT 10" - # NOTE: for some reason there is an extra space in the output of to_sql - expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) - - Apartment::Tenant.switch!(db2) - sql = "SELECT \"users\".* FROM \"#{db2}\".\"users\" LIMIT 10" - expect(UserWithTenantModel.all.limit(10).to_sql.gsub(/\s+/, ' ')).to eq(sql) - end - end end context 'using schemas with SQL dump' do diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index e486dac9..cceaa7e4 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -35,14 +35,6 @@ def tenant_names_from_array(names) expect(Apartment.use_schemas).to be false end - it 'should set allow_prepend_tenant_name' do - Apartment.configure do |config| - config.excluded_models = [] - config.allow_prepend_tenant_name = true - end - expect(Apartment.allow_prepend_tenant_name).to be true - end - it 'should set seed_data_file' do Apartment.configure do |config| config.seed_data_file = seed_data_file_path From b99748a97b067506ea3591607da96d023e344fb3 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 10:50:46 +0800 Subject: [PATCH 112/282] [Release 2.5.0] --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index e682d893..1e72510d 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.4.0' + VERSION = '2.5.0' end From 296750cd61b636083f9c7b8b1f2e5813779513b8 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 4 May 2020 19:02:59 +0800 Subject: [PATCH 113/282] [#42] added simple test to check callbacks are called. each adapter is responsible for reseting if needed --- lib/apartment/adapters/abstract_adapter.rb | 16 ++++----- lib/apartment/adapters/sqlite3_adapter.rb | 2 ++ spec/adapters/postgresql_adapter_spec.rb | 2 ++ .../generic_adapters_callbacks_examples.rb | 33 +++++++++++++++++++ 4 files changed, 43 insertions(+), 10 deletions(-) create mode 100644 spec/examples/generic_adapters_callbacks_examples.rb diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index c9a548aa..20bc216f 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -68,8 +68,6 @@ def drop(tenant) # def switch!(tenant = nil) run_callbacks :switch do - return reset if tenant.nil? - connect_to_new(tenant).tap do Apartment.connection.clear_query_cache end @@ -130,14 +128,12 @@ def seed_data # @return {String} tenant name with Rails environment *optionally* prepended # def environmentify(tenant) - if !tenant.include?(Rails.env) - if Apartment.prepend_environment - "#{Rails.env}_#{tenant}" - elsif Apartment.append_environment - "#{tenant}_#{Rails.env}" - else - tenant - end + return tenant if tenant.nil? || tenant.include?(Rails.env) + + if Apartment.prepend_environment + "#{Rails.env}_#{tenant}" + elsif Apartment.append_environment + "#{tenant}_#{Rails.env}" else tenant end diff --git a/lib/apartment/adapters/sqlite3_adapter.rb b/lib/apartment/adapters/sqlite3_adapter.rb index 44896ef4..bfa6f3de 100644 --- a/lib/apartment/adapters/sqlite3_adapter.rb +++ b/lib/apartment/adapters/sqlite3_adapter.rb @@ -33,6 +33,8 @@ def current protected def connect_to_new(tenant) + return reset if tenant.nil? + unless File.exist?(database_file(tenant)) raise TenantNotFound, "The tenant #{environmentify(tenant)} cannot be found." diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index d553ff8b..71366c59 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -8,6 +8,8 @@ subject { Apartment::Tenant.postgresql_adapter config } + it_should_behave_like 'a generic apartment adapter callbacks' + context 'using schemas with schema.rb' do before { Apartment.use_schemas = true } diff --git a/spec/examples/generic_adapters_callbacks_examples.rb b/spec/examples/generic_adapters_callbacks_examples.rb new file mode 100644 index 00000000..faedd6b4 --- /dev/null +++ b/spec/examples/generic_adapters_callbacks_examples.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +require 'spec_helper' + +# NOTE: This is a dummy test because at the moment i cant think of a way to +# ensure that the callbacks are properly called. I'm open for ideas or I'll +# just delete this. +shared_examples_for 'a generic apartment adapter callbacks' do + include Apartment::Spec::AdapterRequirements + + before do + Apartment.prepend_environment = false + Apartment.append_environment = false + end + + describe '#switch! to nil' do + before do + Apartment::Adapters::AbstractAdapter.set_callback :switch, :before do + puts("Before tenant switch from: #{current}") + end + + Apartment::Adapters::AbstractAdapter.set_callback :switch, :after do + puts("After tenant switch to: #{current}") + end + + Apartment::Tenant.switch!(nil) + end + + it 'runs both before and after callbacks' do + expect(true).to eq true + end + end +end From 74d724b589a64253b70d6223108e8f47a8edc257 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 08:32:53 +0800 Subject: [PATCH 114/282] [#42] improved test basing it on the reported issue --- .../generic_adapters_callbacks_examples.rb | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/spec/examples/generic_adapters_callbacks_examples.rb b/spec/examples/generic_adapters_callbacks_examples.rb index faedd6b4..20500f00 100644 --- a/spec/examples/generic_adapters_callbacks_examples.rb +++ b/spec/examples/generic_adapters_callbacks_examples.rb @@ -6,6 +6,10 @@ # ensure that the callbacks are properly called. I'm open for ideas or I'll # just delete this. shared_examples_for 'a generic apartment adapter callbacks' do + class MyProc + def self.call; end + end + include Apartment::Spec::AdapterRequirements before do @@ -13,21 +17,38 @@ Apartment.append_environment = false end - describe '#switch! to nil' do + describe '#switch!' do before do Apartment::Adapters::AbstractAdapter.set_callback :switch, :before do - puts("Before tenant switch from: #{current}") + MyProc.call(Apartment::Tenant.current) end Apartment::Adapters::AbstractAdapter.set_callback :switch, :after do - puts("After tenant switch to: #{current}") + MyProc.call(Apartment::Tenant.current) + end + + allow(MyProc).to receive(:call) + end + + context 'when tenant is nil' do + before do + Apartment::Tenant.switch!(nil) end - Apartment::Tenant.switch!(nil) + it 'runs both before and after callbacks' do + expect(MyProc).to have_received(:call).twice + end end - it 'runs both before and after callbacks' do - expect(true).to eq true + context 'when tenant is not nil' do + before do + puts db1 + Apartment::Tenant.switch!(db1) + end + + it 'runs both before and after callbacks' do + expect(MyProc).to have_received(:call).twice + end end end end From d5751175f0ee5e6370827b0eeb950636b29b94c4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 08:46:44 +0800 Subject: [PATCH 115/282] [#42] Fixed failing test --- .../examples/generic_adapters_callbacks_examples.rb | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/spec/examples/generic_adapters_callbacks_examples.rb b/spec/examples/generic_adapters_callbacks_examples.rb index 20500f00..5d878d38 100644 --- a/spec/examples/generic_adapters_callbacks_examples.rb +++ b/spec/examples/generic_adapters_callbacks_examples.rb @@ -2,12 +2,9 @@ require 'spec_helper' -# NOTE: This is a dummy test because at the moment i cant think of a way to -# ensure that the callbacks are properly called. I'm open for ideas or I'll -# just delete this. shared_examples_for 'a generic apartment adapter callbacks' do class MyProc - def self.call; end + def self.call(tenant_name); end end include Apartment::Spec::AdapterRequirements @@ -30,6 +27,13 @@ def self.call; end allow(MyProc).to receive(:call) end + # NOTE: Part of the test setup creates and switches tenants, so we need + # to reset the callbacks to ensure that each test run has the correct + # counts + after do + Apartment::Adapters::AbstractAdapter.reset_callbacks :switch + end + context 'when tenant is nil' do before do Apartment::Tenant.switch!(nil) @@ -42,7 +46,6 @@ def self.call; end context 'when tenant is not nil' do before do - puts db1 Apartment::Tenant.switch!(db1) end From ca54606a0391956e273da76125a9c6a0e6a36b26 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 09:15:04 +0800 Subject: [PATCH 116/282] [#42] connect to new ensures reset if tenant nil --- lib/apartment/adapters/abstract_adapter.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 20bc216f..5b796532 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -171,6 +171,8 @@ def create_tenant_command(conn, tenant) # @param {String} tenant Database name # def connect_to_new(tenant) + return reset if tenant.nil? + query_cache_enabled = ActiveRecord::Base.connection.query_cache_enabled Apartment.establish_connection multi_tenantify(tenant) From 61ee2117bb086bacd7ea6b6a76e745bb1beeb7cc Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 10:59:37 +0800 Subject: [PATCH 117/282] [#42] Add test coverage to remaining adapters --- spec/adapters/jdbc_mysql_adapter_spec.rb | 1 + spec/adapters/jdbc_postgresql_adapter_spec.rb | 2 ++ spec/adapters/mysql2_adapter_spec.rb | 2 ++ spec/adapters/sqlite3_adapter_spec.rb | 2 ++ 4 files changed, 7 insertions(+) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 4833f93d..764893b3 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -14,6 +14,7 @@ def tenant_names let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } + it_should_behave_like 'a generic apartment adapter callbacks' it_should_behave_like 'a generic apartment adapter' it_should_behave_like 'a connection based apartment adapter' end diff --git a/spec/adapters/jdbc_postgresql_adapter_spec.rb b/spec/adapters/jdbc_postgresql_adapter_spec.rb index 49dfaf1a..67d3c981 100644 --- a/spec/adapters/jdbc_postgresql_adapter_spec.rb +++ b/spec/adapters/jdbc_postgresql_adapter_spec.rb @@ -8,6 +8,8 @@ describe Apartment::Adapters::JDBCPostgresqlAdapter, database: :postgresql do subject { Apartment::Tenant.jdbc_postgresql_adapter config.symbolize_keys } + it_should_behave_like 'a generic apartment adapter callbacks' + context 'using schemas' do before { Apartment.use_schemas = true } diff --git a/spec/adapters/mysql2_adapter_spec.rb b/spec/adapters/mysql2_adapter_spec.rb index 29529514..ca3e577f 100644 --- a/spec/adapters/mysql2_adapter_spec.rb +++ b/spec/adapters/mysql2_adapter_spec.rb @@ -14,6 +14,8 @@ def tenant_names let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } + it_should_behave_like 'a generic apartment adapter callbacks' + context 'using - the equivalent of - schemas' do before { Apartment.use_schemas = true } diff --git a/spec/adapters/sqlite3_adapter_spec.rb b/spec/adapters/sqlite3_adapter_spec.rb index 252cdb66..f05c76ba 100644 --- a/spec/adapters/sqlite3_adapter_spec.rb +++ b/spec/adapters/sqlite3_adapter_spec.rb @@ -8,6 +8,8 @@ subject { Apartment::Tenant.sqlite3_adapter config } + it_should_behave_like 'a generic apartment adapter callbacks' + context 'using connections' do def tenant_names db_dir = File.expand_path('../dummy/db', __dir__) From 9022aa5d2a144e4bd5ddbf7dffd9fda7c112126b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 15:54:39 +0800 Subject: [PATCH 118/282] [#26] Add tenant_present_check configuration and inspecting it before checking for tenant presence --- .rubocop_todo.yml | 2 +- lib/apartment/adapters/postgresql_adapter.rb | 13 +++++++++---- lib/apartment/railtie.rb | 1 + 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 0f709629..dd9305f8 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -21,7 +21,7 @@ Metrics/BlockLength: # Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. # URISchemes: http, https Metrics/LineLength: - Max: 237 + Max: 200 # Offense count: 4 # Configuration parameters: CountComments, ExcludedMethods. diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 3e98b627..d414b07d 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -62,12 +62,11 @@ def drop_command(conn, tenant) # def connect_to_new(tenant = nil) return reset if tenant.nil? - # rubocop:disable Style/RaiseArgs - raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.schema_exists?(tenant.to_s) - # rubocop:enable Style/RaiseArgs + tenant = tenant.to_s + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) - @current = tenant.to_s + @current = tenant Apartment.connection.schema_search_path = full_search_path # When the PostgreSQL version is < 9.3, @@ -80,6 +79,12 @@ def connect_to_new(tenant = nil) private + def tenant_exists?(tenant) + return true unless Apartment.tenant_present_check + + Apartment.connection.schema_exists?(tenant) + end + def create_tenant_command(conn, tenant) conn.execute(%(CREATE SCHEMA "#{tenant}")) end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 647b221c..e58d86c3 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -18,6 +18,7 @@ class Railtie < Rails::Railtie config.seed_after_create = false config.prepend_environment = false config.append_environment = false + config.tenant_present_check = true end ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a From aabab8ab70902413d7aaf60f3b695bcdc41644ef Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 16:54:57 +0800 Subject: [PATCH 119/282] [#26] Check for configuration also on jdbc postgresql adapter --- lib/apartment.rb | 2 +- .../adapters/jdbc_postgresql_adapter.rb | 13 ++++++--- lib/apartment/adapters/postgresql_adapter.rb | 2 +- lib/apartment/railtie.rb | 2 +- spec/examples/schema_adapter_examples.rb | 28 ++++++++++++++++--- 5 files changed, 36 insertions(+), 11 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 9c0d664e..4b051e6b 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -20,7 +20,7 @@ class << self extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment - append_environment with_multi_server_setup].freeze + append_environment with_multi_server_setup tenant_presence_check].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 4353cfbf..16113b27 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -37,12 +37,11 @@ class JDBCPostgresqlSchemaAdapter < PostgresqlSchemaAdapter # def connect_to_new(tenant = nil) return reset if tenant.nil? - # rubocop:disable Style/RaiseArgs - raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.all_schemas.include? tenant.to_s - # rubocop:enable Style/RaiseArgs + tenant = tenant.to_s + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) - @current = tenant.to_s + @current = tenant Apartment.connection.schema_search_path = full_search_path rescue ActiveRecord::StatementInvalid, ActiveRecord::JDBCError raise TenantNotFound, "One of the following schema(s) is invalid: #{full_search_path}" @@ -50,6 +49,12 @@ def connect_to_new(tenant = nil) private + def tenant_exists?(tenant) + return true unless Apartment.tenant_presence_check + + Apartment.connection.all_schemas.include? tenant + end + def rescue_from ActiveRecord::JDBCError end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index d414b07d..824a6a26 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -80,7 +80,7 @@ def connect_to_new(tenant = nil) private def tenant_exists?(tenant) - return true unless Apartment.tenant_present_check + return true unless Apartment.tenant_presence_check Apartment.connection.schema_exists?(tenant) end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index e58d86c3..04af0c96 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -18,7 +18,7 @@ class Railtie < Rails::Railtie config.seed_after_create = false config.prepend_environment = false config.append_environment = false - config.tenant_present_check = true + config.tenant_presence_check = true end ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index d253ced9..00596e83 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -164,6 +164,14 @@ end describe '#switch!' do + let(:tenant_presence_check) { true } + + before do + Apartment.configure do |config| + config.tenant_presence_check = tenant_presence_check + end + end + it 'should connect to new schema' do subject.switch!(schema1) expect(connection.schema_search_path).to start_with %("#{schema1}") @@ -174,10 +182,22 @@ expect(connection.schema_search_path).to eq(%("#{public_schema}")) end - it 'should raise an error if schema is invalid' do - expect do - subject.switch! 'unknown_schema' - end.to raise_error(Apartment::TenantNotFound) + context 'when configuration checks for tenant presence before switching' do + it 'should raise an error if schema is invalid' do + expect do + subject.switch! 'unknown_schema' + end.to raise_error(Apartment::TenantNotFound) + end + end + + context 'when configuration skips tenant presence check before switching' do + let(:tenant_presence_check) { false } + + it 'should not raise any errors' do + expect do + subject.switch! 'unknown_schema' + end.to_not raise_error(Apartment::TenantNotFound) + end end context 'numeric databases' do From 1dfa007bade8badd5eaf2901f16418105a275c7f Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 17:13:42 +0800 Subject: [PATCH 120/282] [#26] Fixed failing specs by ensuring configuration does not get modified while running tests --- spec/examples/generic_adapter_examples.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 252ac47c..bc0b1390 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -8,6 +8,7 @@ before do Apartment.prepend_environment = false Apartment.append_environment = false + Apartment.tenant_presence_check = true end describe '#init' do From 41393a0eaf8a9c90ceca80032005dbed55dae39a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 17:17:05 +0800 Subject: [PATCH 121/282] [#26] simplified test setup --- spec/examples/schema_adapter_examples.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 00596e83..0aac53e2 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -166,11 +166,7 @@ describe '#switch!' do let(:tenant_presence_check) { true } - before do - Apartment.configure do |config| - config.tenant_presence_check = tenant_presence_check - end - end + before { Apartment.tenant_presence_check = tenant_presence_check } it 'should connect to new schema' do subject.switch!(schema1) From 315b8cb793b5f029f09f32d3f624317aae676d05 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 5 May 2020 17:26:17 +0800 Subject: [PATCH 122/282] [#26] added readme description for the configuration --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index 3ac0b6fc..ecfb6883 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,20 @@ Apartment.configure do |config| end ``` +### Skip tenant schema check + +This is configurable by setting: `tenant_presence_check`. It defaults to true +in order to maintain the original gem behavior. This is only checked when using one of the PostgreSQL adapters. +The original gem behavior, when running `switch` would look for the existence of the schema before switching. This adds an extra query on every context switch. While in the default simple scenarios this is a valid check, in high volume platforms this adds some unnecessary overhead which can be detected in some other ways on the application level. + +Setting this configuration value to `false` will disable the schema presence check before trying to switch the context. + +```ruby +Apartment.configure do |config| + tenant_presence_check = false +end +``` + ### Excluding models If you have some models that should always access the 'public' tenant, you can specify this by configuring Apartment using `Apartment.configure`. This will yield a config object for you. You can set excluded models like so: From 9e1d18dee3874fcfbdf8565e94b7ce32176d659a Mon Sep 17 00:00:00 2001 From: Jeremiah Date: Thu, 7 May 2020 16:33:28 -0700 Subject: [PATCH 123/282] Update console.rb --- lib/apartment/console.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index a2ed609f..a8267d58 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -35,3 +35,11 @@ def tenant_list tenant_list += Apartment.tenant_names tenant_list.uniq end + +def tenant_info_msg + log_level = ActiveRecord::Base.logger.level + ActiveRecord::Base.logger.level = :error + puts "Available Tenants: #{tenant_list}\n" + puts "Use `st 'tenant'` to switch tenants & `tenant_list` to see list\n" + ActiveRecord::Base.logger.level = log_level +end From edcc2079abad06b8178a6b47c4fb3ff8a1dd576c Mon Sep 17 00:00:00 2001 From: Jeremiah Date: Thu, 7 May 2020 16:35:06 -0700 Subject: [PATCH 124/282] Update custom_console.rb --- lib/apartment/custom_console.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index c3c49c5d..6b38223b 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -4,6 +4,7 @@ module Apartment module CustomConsole begin require 'pry-rails' + require 'apartment/console' rescue LoadError # rubocop:disable Rails/Output puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' @@ -21,6 +22,9 @@ module CustomConsole end Pry.config.prompt = Pry::Prompt[:ros][:value] + Pry.config.hooks.add_hook(:when_started, "startup message") do |target, options, pry| + tenant_info_msg + end end end end From 0e934bd0dda88b3b3964df8fedd8035c7c011755 Mon Sep 17 00:00:00 2001 From: Jeremiah Date: Thu, 7 May 2020 16:38:09 -0700 Subject: [PATCH 125/282] Update custom_console.rb --- lib/apartment/custom_console.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index 6b38223b..e30111ee 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -22,7 +22,7 @@ module CustomConsole end Pry.config.prompt = Pry::Prompt[:ros][:value] - Pry.config.hooks.add_hook(:when_started, "startup message") do |target, options, pry| + Pry.config.hooks.add_hook(:when_started, "startup message") do tenant_info_msg end end From 03857034f5f8667283ab029792a8a5f86378e2e8 Mon Sep 17 00:00:00 2001 From: Jeremiah Date: Thu, 7 May 2020 16:52:46 -0700 Subject: [PATCH 126/282] Update custom_console.rb --- lib/apartment/custom_console.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index e30111ee..a81b90cc 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -4,7 +4,6 @@ module Apartment module CustomConsole begin require 'pry-rails' - require 'apartment/console' rescue LoadError # rubocop:disable Rails/Output puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' From 9dad02eddd3fd2af3b8194b96088a6368cc6ef17 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 11 May 2020 10:17:35 +0800 Subject: [PATCH 127/282] [Chore] Fix Rubocop --- lib/apartment/console.rb | 2 ++ lib/apartment/custom_console.rb | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index a8267d58..b95baa64 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -39,7 +39,9 @@ def tenant_list def tenant_info_msg log_level = ActiveRecord::Base.logger.level ActiveRecord::Base.logger.level = :error + # rubocop:disable Rails/Output puts "Available Tenants: #{tenant_list}\n" puts "Use `st 'tenant'` to switch tenants & `tenant_list` to see list\n" + # rubocop:enable Rails/Output ActiveRecord::Base.logger.level = log_level end diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index a81b90cc..2eacd838 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -21,7 +21,7 @@ module CustomConsole end Pry.config.prompt = Pry::Prompt[:ros][:value] - Pry.config.hooks.add_hook(:when_started, "startup message") do + Pry.config.hooks.add_hook(:when_started, 'startup message') do tenant_info_msg end end From a0d5ce582d16e75e1597da467e7ed8ba97f3fa05 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 11 May 2020 10:20:39 +0800 Subject: [PATCH 128/282] [Chore] Updated rubocop to run on PR as well --- .github/workflows/.rubocop-linter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/.rubocop-linter.yml b/.github/workflows/.rubocop-linter.yml index cab9704b..1cbca2f6 100644 --- a/.github/workflows/.rubocop-linter.yml +++ b/.github/workflows/.rubocop-linter.yml @@ -1,6 +1,6 @@ name: Rubocop Lint -on: [push] +on: [push, pull_request] jobs: build: From e95102dedeae0ed08fd593ac0075c4ba60d1af9a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 14 May 2020 15:05:56 +0800 Subject: [PATCH 129/282] [#37] Pry changed internal implementation after 0.13 --- lib/apartment/custom_console.rb | 42 +++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index 2eacd838..88119022 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -10,20 +10,42 @@ module CustomConsole # rubocop:enable Rails/Output end - if Pry::Prompt.respond_to?(:add) - desc = "Includes the current Rails environment and project folder name.\n" \ - '[1] [project_name][Rails.env][Apartment::Tenant.current] pry(main)>' + desc = "Includes the current Rails environment and project folder name.\n" \ + '[1] [project_name][Rails.env][Apartment::Tenant.current] pry(main)>' + prompt_procs = [ + proc { |target_self, nest_level, pry| prompt_contents(pry, target_self, nest_level, '>') }, + proc { |target_self, nest_level, pry| prompt_contents(pry, target_self, nest_level, '*') } + ] + + if Gem::Version.new(Pry::VERSION) >= Gem::Version.new('0.13') + Pry.config.prompt = Pry::Prompt.new 'ros', desc, prompt_procs + else Pry::Prompt.add 'ros', desc, %w[> *] do |target_self, nest_level, pry, sep| - "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ - "#{pry.config.prompt_name}(#{Pry.view_clip(target_self)})" \ - "#{":#{nest_level}" unless nest_level.zero?}#{sep} " + prompt_contents(pry, target_self, nest_level, sep) end + end - Pry.config.prompt = Pry::Prompt[:ros][:value] - Pry.config.hooks.add_hook(:when_started, 'startup message') do - tenant_info_msg - end + # if Pry::Prompt.respond_to?(:add) + # desc = "Includes the current Rails environment and project folder name.\n" \ + # '[1] [project_name][Rails.env][Apartment::Tenant.current] pry(main)>' + + # Pry::Prompt.add 'ros', desc, %w[> *] do |target_self, nest_level, pry, sep| + # "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ + # "#{pry.config.prompt_name}(#{Pry.view_clip(target_self)})" \ + # "#{":#{nest_level}" unless nest_level.zero?}#{sep} " + # end + + # Pry.config.prompt = Pry::Prompt[:ros][:value] + # Pry.config.hooks.add_hook(:when_started, 'startup message') do + # tenant_info_msg + # end + # end + + def self.prompt_contents(pry, target_self, nest_level, sep) + "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ + "#{pry.config.prompt_name}(#{Pry.view_clip(target_self)})" \ + "#{":#{nest_level}" unless nest_level.zero?}#{sep} " end end end From 75a7441a98ad9dc5b2e5ef3249a1af19ce399032 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 14 May 2020 15:12:17 +0800 Subject: [PATCH 130/282] [#37] Cleanup tenant info message --- lib/apartment/console.rb | 3 --- lib/apartment/custom_console.rb | 19 ++++--------------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index b95baa64..7fcb1d61 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -37,11 +37,8 @@ def tenant_list end def tenant_info_msg - log_level = ActiveRecord::Base.logger.level - ActiveRecord::Base.logger.level = :error # rubocop:disable Rails/Output puts "Available Tenants: #{tenant_list}\n" puts "Use `st 'tenant'` to switch tenants & `tenant_list` to see list\n" # rubocop:enable Rails/Output - ActiveRecord::Base.logger.level = log_level end diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index 88119022..eddb1475 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -24,23 +24,12 @@ module CustomConsole Pry::Prompt.add 'ros', desc, %w[> *] do |target_self, nest_level, pry, sep| prompt_contents(pry, target_self, nest_level, sep) end + Pry.config.prompt = Pry::Prompt[:ros][:value] end - # if Pry::Prompt.respond_to?(:add) - # desc = "Includes the current Rails environment and project folder name.\n" \ - # '[1] [project_name][Rails.env][Apartment::Tenant.current] pry(main)>' - - # Pry::Prompt.add 'ros', desc, %w[> *] do |target_self, nest_level, pry, sep| - # "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ - # "#{pry.config.prompt_name}(#{Pry.view_clip(target_self)})" \ - # "#{":#{nest_level}" unless nest_level.zero?}#{sep} " - # end - - # Pry.config.prompt = Pry::Prompt[:ros][:value] - # Pry.config.hooks.add_hook(:when_started, 'startup message') do - # tenant_info_msg - # end - # end + Pry.config.hooks.add_hook(:when_started, 'startup message') do + tenant_info_msg + end def self.prompt_contents(pry, target_self, nest_level, sep) "[#{pry.input_ring.size}] [#{PryRails::Prompt.formatted_env}][#{Apartment::Tenant.current}] " \ From 366a2849acbe974d457962fa732cb10232b52db1 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 14 May 2020 17:53:52 +0800 Subject: [PATCH 131/282] Version bump --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 1e72510d..fa0f43a6 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.5.0' + VERSION = '2.6.0' end From 26fc746fc3dbd50c9203755fd26c429fc0dd6a27 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Mon, 13 Apr 2020 14:47:22 -0400 Subject: [PATCH 132/282] Avoid getting a connection to the database before it's necessary We init the first time we request a connection. On code reloads, we "forget" about our init state and we call it again. After init, ensure the search path is set properly --- lib/apartment/adapters/abstract_adapter.rb | 6 +++++ lib/apartment/adapters/postgresql_adapter.rb | 5 ++++ lib/apartment/railtie.rb | 27 +++++++++----------- lib/apartment/tenant.rb | 19 ++++++++++---- spec/examples/generic_adapter_examples.rb | 2 +- 5 files changed, 38 insertions(+), 21 deletions(-) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 5b796532..52fb56a7 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -35,6 +35,12 @@ def create(tenant) end end + # Initialize Apartment config options such as excluded_models + # + def init + process_excluded_models + end + # Note alias_method here doesn't work with inheritence apparently ?? # def current diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 824a6a26..63b3d12e 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -39,6 +39,11 @@ def reset Apartment.connection.schema_search_path = full_search_path end + def init + super + Apartment.connection.schema_search_path = full_search_path + end + def current @current || default_tenant end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 04af0c96..ba3a9dc5 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -24,26 +24,23 @@ class Railtie < Rails::Railtie ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a end - # Hook into ActionDispatch::Reloader to ensure Apartment is properly initialized - # Note that this doens't entirely work as expected in Development, because this is called before classes are reloaded - # See the middleware/console declarations below to help with this. Hope to fix that soon. - # + # Make sure Apartment is reconfigured when the code is reloaded config.to_prepare do - next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } - next if ARGV.any? { |arg| arg == 'webpacker:compile' } + Apartment::Tenant.reinitialize + end - begin - Apartment.connection_class.connection_pool.with_connection do - Apartment::Tenant.init - end - rescue ::ActiveRecord::NoDatabaseError, PG::ConnectionBad - # Since `db:create` and other tasks invoke this block from Rails 5.2.0, - # we need to swallow the error to execute `db:create` properly. - Rails.logger.warn do - 'Failed to initialize Apartment because a database connection could not be established.' + # + # Ensure that Apartment::Tenant.init is called when + # a new connection is requested. + # + module ApartmentInitializer + def connection + super.tap do + Apartment::Tenant.init_once end end end + ActiveRecord::Base.singleton_class.prepend ApartmentInitializer # # Ensure rake tasks are loaded diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index bc69f9c9..17560b27 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -10,15 +10,23 @@ module Tenant extend Forwardable def_delegators :adapter, :create, :drop, :switch, :switch!, :current, :each, - :reset, :set_callback, :seed, :current_tenant, + :reset, :init, :set_callback, :seed, :current_tenant, :default_tenant, :environmentify attr_writer :config - # Initialize Apartment config options such as excluded_models - # - def init - adapter.process_excluded_models + def init_once + return if @already_initialized + + # To avoid infinite loops in work init is doing, + # we need to set @already_initialized to true + # before init is called + @already_initialized = true + init + end + + def reinitialize + @already_initialized = false end # Fetch the proper multi-tenant adapter based on Rails config @@ -53,6 +61,7 @@ def adapter # def reload!(config = nil) Thread.current[:apartment_adapter] = nil + reinitialize @config = config end diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index bc0b1390..1a8b44d4 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -25,7 +25,7 @@ .instance_variable_get(:@queue) .size - expect(num_available_connections).to eq(1) + expect(num_available_connections).to eq(0) end end end From 73dc0661b590579e636c111618aec3ebccf635dd Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 20 May 2020 17:29:25 +0800 Subject: [PATCH 133/282] [Fix] Custom Console should require apartment console --- lib/apartment/custom_console.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index eddb1475..eae9f4bb 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require_relative 'console' + module Apartment module CustomConsole begin From 1a27a890607783d4d8425509196eeff52747265c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 20 May 2020 19:20:49 +0800 Subject: [PATCH 134/282] [#52] enhance after db create --- lib/apartment/tasks/enhancements.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/tasks/enhancements.rb b/lib/apartment/tasks/enhancements.rb index f9a13206..ede5c1f3 100644 --- a/lib/apartment/tasks/enhancements.rb +++ b/lib/apartment/tasks/enhancements.rb @@ -7,7 +7,7 @@ module Apartment class RakeTaskEnhancer module TASKS ENHANCE_BEFORE = %w[db:drop].freeze - ENHANCE_AFTER = %w[db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed].freeze + ENHANCE_AFTER = %w[db:create db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed].freeze freeze end From 2c51aabf157c430c68429d3f4902dae7697bcb82 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 10:56:47 +0800 Subject: [PATCH 135/282] [#52] fixing gem requirements based in test output --- apartment.gemspec | 1 - 1 file changed, 1 deletion(-) diff --git a/apartment.gemspec b/apartment.gemspec index cdd419a7..d07567df 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -46,7 +46,6 @@ Gem::Specification.new do |s| s.add_development_dependency 'activerecord-jdbcpostgresql-adapter' s.add_development_dependency 'jdbc-mysql' s.add_development_dependency 'jdbc-postgres' - s.add_development_dependency 'jruby-openssl' else s.add_development_dependency 'mysql2', '~> 0.5' s.add_development_dependency 'pg', '~> 1.2' From 52874a8ee3c0e225970b46701d780dcd562bf4a5 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 11:17:52 +0800 Subject: [PATCH 136/282] [52] fixed failing specs --- spec/adapters/jdbc_mysql_adapter_spec.rb | 2 +- spec/examples/generic_adapter_examples.rb | 20 +++++++++----------- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 764893b3..62219e23 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,7 +9,7 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row['schema_name'] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row[0] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 1a8b44d4..6459bf36 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -13,20 +13,16 @@ describe '#init' do it 'should not retain a connection after railtie' do - # this test should work on rails >= 4, the connection pool code is - # completely different for 3.2 so we'd have to have a messy conditional.. - unless Rails::VERSION::MAJOR < 4 - ActiveRecord::Base.connection_pool.disconnect! + ActiveRecord::Base.connection_pool.disconnect! - Apartment::Railtie.config.to_prepare_blocks.map(&:call) + Apartment::Railtie.config.to_prepare_blocks.map(&:call) - num_available_connections = Apartment.connection_class.connection_pool - .instance_variable_get(:@available) - .instance_variable_get(:@queue) - .size + num_available_connections = Apartment.connection_class.connection_pool + .instance_variable_get(:@available) + .instance_variable_get(:@queue) + .size - expect(num_available_connections).to eq(0) - end + expect(num_available_connections).to eq(0) end end @@ -35,6 +31,8 @@ # describe '#create' do it 'should create the new databases' do + binding.pry + expect(tenant_names).to include(db1) expect(tenant_names).to include(db2) end From b625e037bb4d9a3458e21a3687dd1320f78c2154 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 11:40:59 +0800 Subject: [PATCH 137/282] [#52] Addressed rubocop issues --- spec/examples/generic_adapter_examples.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 6459bf36..525e0b77 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -18,9 +18,9 @@ Apartment::Railtie.config.to_prepare_blocks.map(&:call) num_available_connections = Apartment.connection_class.connection_pool - .instance_variable_get(:@available) - .instance_variable_get(:@queue) - .size + .instance_variable_get(:@available) + .instance_variable_get(:@queue) + .size expect(num_available_connections).to eq(0) end @@ -31,8 +31,6 @@ # describe '#create' do it 'should create the new databases' do - binding.pry - expect(tenant_names).to include(db1) expect(tenant_names).to include(db2) end From 833a145f0b9db9951126e55f2321ec1ced52f022 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 12:13:27 +0800 Subject: [PATCH 138/282] [#52] fixed failing specs --- spec/adapters/jdbc_mysql_adapter_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 62219e23..6785b83b 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,7 +9,7 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row[0] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row["SCHEMA_NAME"] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } From 7c2fe955733ac6a12a7fceb4b4edbdf376b72d7e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 12:34:48 +0800 Subject: [PATCH 139/282] [#52] added logging to debug on ci --- spec/adapters/jdbc_mysql_adapter_spec.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 6785b83b..30d5e4c9 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,7 +9,10 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row["SCHEMA_NAME"] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| + puts row.inspect + row["SCHEMA_NAME"] + } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } From ac9896815733ec5ed12415bdfbb22fb19f4aac5e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 12:41:58 +0800 Subject: [PATCH 140/282] [#52] ci uses lower case --- spec/adapters/jdbc_mysql_adapter_spec.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 30d5e4c9..3062290d 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,10 +9,7 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| - puts row.inspect - row["SCHEMA_NAME"] - } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row["schema_name"] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } From e94a442f81d2d1ca85976230d391455b1d0d97e8 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 25 May 2020 16:00:35 +0800 Subject: [PATCH 141/282] [#52] fix rubocop --- spec/adapters/jdbc_mysql_adapter_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 3062290d..764893b3 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,7 +9,7 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row["schema_name"] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row['schema_name'] } end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } From f8eefc43767fd94a190b182d4ef58178bebebd11 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Tue, 19 May 2020 15:57:59 -0400 Subject: [PATCH 142/282] fix: reset sequence_name after tenant switch The sequence_name contains the schema name, so after switching we point to the wrong one. Gems such as ActiveRecord-Import use it --- lib/apartment/adapters/postgresql_adapter.rb | 15 +++++++++++++++ spec/examples/schema_adapter_examples.rb | 2 ++ 2 files changed, 17 insertions(+) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 63b3d12e..af735256 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -37,6 +37,7 @@ def initialize(config) def reset @current = default_tenant Apartment.connection.schema_search_path = full_search_path + reset_sequence_names end def init @@ -78,6 +79,7 @@ def connect_to_new(tenant = nil) # there is a issue for prepared statement with changing search_path. # https://www.postgresql.org/docs/9.3/static/sql-prepare.html Apartment.connection.clear_cache! if postgresql_version < 90_300 + reset_sequence_names rescue *rescuable_exceptions raise TenantNotFound, "One of the following schema(s) is invalid: \"#{tenant}\" #{full_search_path}" end @@ -109,6 +111,19 @@ def postgresql_version # public from Rails 5.0. Apartment.connection.send(:postgresql_version) end + + def reset_sequence_names + # sequence_name contains the schema, so it must be reset after switch + # There is `reset_sequence_name`, but that method actually goes to the database + # to find out the new name. Therefore, we do this hack to only unset the name, + # and it will be dynamically found the next time it is needed + ActiveRecord::Base.descendants + .select { |c| c.instance_variable_defined?(:@sequence_name) } + .reject { |c| c.instance_variable_defined?(:@explicit_sequence_name) && c.instance_variable_get(:@explicit_sequence_name) } + .each do |c| + c.remove_instance_variable :@sequence_name + end + end end # Another Adapter for Postgresql when using schemas and SQL diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 0aac53e2..fed495a3 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -123,9 +123,11 @@ it 'connects and resets' do subject.switch(schema1) do expect(connection.schema_search_path).to start_with %("#{schema1}") + expect(User.sequence_name).to eq "#{schema1}.#{User.table_name}_id_seq" end expect(connection.schema_search_path).to start_with %("#{public_schema}") + expect(User.sequence_name).to eq "#{public_schema}.#{User.table_name}_id_seq" end end From 3cfaeb46c3608b5bef3697099958fa1f79456360 Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Tue, 19 May 2020 17:06:21 -0400 Subject: [PATCH 143/282] fix init after reload on development On 26fc746fc3d, init is not forced to be executed on `to_prepare`. This helps us avoid a connection at startup. However, things break down after a reload because things like `ExcludedModel.count` don't go through the `connection` method that we overrode, at least until after we queried the table name. Let's make sure that we initialize before using arel too. --- lib/apartment/railtie.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index ba3a9dc5..ddc3e18e 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -39,6 +39,11 @@ def connection Apartment::Tenant.init_once end end + + def arel_table + Apartment::Tenant.init_once + super + end end ActiveRecord::Base.singleton_class.prepend ApartmentInitializer From 443bebf8caac3d5d4b102176a0419670e629bd88 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 1 Jun 2020 18:57:55 +0800 Subject: [PATCH 144/282] Excluding default schema from tasks --- lib/tasks/apartment.rake | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index d8353821..6af72b1e 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -121,11 +121,15 @@ apartment_namespace = namespace :apartment do end def each_tenant(&block) - Parallel.each(tenants, in_threads: Apartment.parallel_migration_threads) do |tenant| + Parallel.each(tenants_without_default, in_threads: Apartment.parallel_migration_threads) do |tenant| block.call(tenant) end end + def tenants_without_default + tenants - [Apartment.default_schema] + end + def tenants ENV['DB'] ? ENV['DB'].split(',').map(&:strip) : Apartment.tenant_names || [] end From f16105a6af08a3f710dc84a4c3c98855f96a590b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 2 Jun 2020 13:27:32 +0800 Subject: [PATCH 145/282] Version bump --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index fa0f43a6..5a564a2c 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.6.0' + VERSION = '2.6.1' end From e41c682d37a0572898ad4cec7902b4c158a1734e Mon Sep 17 00:00:00 2001 From: Heber Uriegas Date: Thu, 28 May 2020 10:08:26 -0500 Subject: [PATCH 146/282] Add database and schema to active record log --- lib/apartment.rb | 3 +- lib/apartment/active_record/log_subscriber.rb | 41 +++++++++++++++++++ lib/apartment/railtie.rb | 1 + .../apartment/install/templates/apartment.rb | 5 +++ 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 lib/apartment/active_record/log_subscriber.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 4b051e6b..854a0250 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -8,6 +8,7 @@ # require_relative 'apartment/arel/visitors/postgresql' +require_relative 'apartment/active_record/log_subscriber' require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') if ActiveRecord.version.release >= Gem::Version.new('6.1') @@ -20,7 +21,7 @@ class << self extend Forwardable ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment - append_environment with_multi_server_setup tenant_presence_check].freeze + append_environment with_multi_server_setup tenant_presence_check active_record_log].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb new file mode 100644 index 00000000..ca090264 --- /dev/null +++ b/lib/apartment/active_record/log_subscriber.rb @@ -0,0 +1,41 @@ +# frozen_string_literal: true + +module ActiveRecord + class LogSubscriber + def apartment_log + return unless Apartment.active_record_log + + database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) + schema = nil + schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", ActiveSupport::LogSubscriber::YELLOW, true) unless Apartment.connection.schema_search_path.nil? + "#{database}#{schema}" + end + + def payload_binds(binds, type_casted_binds) + return unless (binds || []).empty? + + casted_params = type_casted_binds(type_casted_binds) + binds = ' ' + binds.zip(casted_params).map { |attr, value| render_bind(attr, value) }.inspect + binds + end + + def sql(event) + self.class.runtime += event.duration + return unless logger.debug? + + payload = event.payload + + return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) + + name = "#{payload[:name]} (#{event.duration.round(1)}ms)" + name = "CACHE #{name}" if payload[:cached] + sql = payload[:sql] + binds = payload_binds(payload[:binds], payload[:type_casted_binds]) + + name = colorize_payload_name(name, payload[:name]) + sql = color(sql, sql_color(sql), true) if colorize_logging + + debug " #{apartment_log}#{name} #{sql}#{binds}" + end + end +end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index ddc3e18e..101c8b43 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -19,6 +19,7 @@ class Railtie < Rails::Railtie config.prepend_environment = false config.append_environment = false config.tenant_presence_check = true + config.active_record_log = false end ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a diff --git a/lib/generators/apartment/install/templates/apartment.rb b/lib/generators/apartment/install/templates/apartment.rb index 2a774737..ece13534 100644 --- a/lib/generators/apartment/install/templates/apartment.rb +++ b/lib/generators/apartment/install/templates/apartment.rb @@ -96,6 +96,11 @@ # the new tenant # # config.pg_excluded_names = ["uuid_generate_v4"] + + # Specifies whether the database and schema (when using PostgreSQL schemas) will prepend in ActiveRecord log. + # Uncomment the line below if you want to enable this behavior. + # + # config.active_record_log = true end # Setup a custom Tenant switching middleware. The Proc should return the name of the Tenant that From 8c84e97d1790dd26ef7c2b104eeb9c7b4af52cd9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 3 Jun 2020 12:04:25 +0800 Subject: [PATCH 147/282] Use diffend.io proxy --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index b0f35aba..c17fcbee 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ # frozen_string_literal: true -source 'http://rubygems.org' +source 'https://my.diffend.io/protect/gems' gemspec From eb95ac3e13dc04a5d3e70b11c5efced6fe258895 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 7 Jun 2020 10:46:57 +0800 Subject: [PATCH 148/282] [Resolves #62] added Missing notes in history.md --- HISTORY.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/HISTORY.md b/HISTORY.md index 5bf2609c..f76c9d24 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,60 @@ +# 2.6.1 + +## Enhancements +- N/a + +## Bugfixes +- [Resolves influitive#607] Avoid early connection + - + - + - +- [Resolves #52] Rake db:setup tries to seed non existent tenant - +- [Resolves #56] DB rollback uses second last migration - + +## Chores +- N/a + +# 2.6.0 + +## Enhancements +- [Resolves #26] Support configuration for skip checking of schema existence before switching +- [Resolves #41] Add tenant info to console boot + +## Bugfixes +- [Resolves #37] Custom Console deprecation warning +- [Resolves #42] After switch callback not working with nil argument + +## Chores +- Updated github actions configuration to run on PRs as well + +# 2.5.0 + +## Enhancements +- [Resolves #6] Adds support for rails 6.1 +- [Resolves #27] Adds support to not rely on set search path, but instead prepends the schema name to the table name when using postgresql with schemas. +- [Resolves #35] Cache keys are now tenant dependent + +## Bugfixes +- [Resolves #27] Manually switching connection between read and write forgets the schema + +## Chores +- [Resolves #31] Add latest ruby versions to test matrix + +# 2.4.0 + +## Enhancements +- [Resolves #14] Add console info about tenants and fast switches #17 +- Skip init if we're running webpacker:compile #18 + +## Bugfixes +- Don't crash when no database connection is present #16 +- Rescuing ActiveRecord::NoDatabaseError when dropping tenants #19 + +## Chores +- Rakefile should use mysql port from configuration #5 +- [Resolves #9] Cleanup rubocop todo #8 +- Cleanup travis matrix #23 + # 2.3.0 * January 3, 2020 From cbf4f228d3874dd9a308c86923bb92add64b017a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 14 Jun 2020 15:34:50 +0800 Subject: [PATCH 149/282] Configure story branch --- .story_branch.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.story_branch.yml b/.story_branch.yml index d9ad6922..4143ff44 100644 --- a/.story_branch.yml +++ b/.story_branch.yml @@ -1,4 +1,5 @@ --- tracker: github +issue_placement: beginning project_id: - rails-on-services/apartment From e6b4cae00e6784a27d8cb1fde55c058cfe9c75e7 Mon Sep 17 00:00:00 2001 From: Lawrence Chou Date: Sat, 20 Jun 2020 10:31:43 +0800 Subject: [PATCH 150/282] Remove depracated tld_length config option: tld_length was removed in https://github.com/influitive/apartment/pull/309 , this configuration option doesn't have any effect now. --- lib/apartment.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 854a0250..3f9cfeea 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -25,7 +25,7 @@ class << self WRITER_METHODS = %i[tenant_names database_schema_file excluded_models default_schema persistent_schemas connection_class - tld_length db_migrate_tenants seed_data_file + db_migrate_tenants seed_data_file parallel_migration_threads pg_excluded_names].freeze attr_accessor(*ACCESSOR_METHODS) @@ -54,6 +54,10 @@ def tenants_with_config extract_tenant_config end + def tld_length=(_) + Apartment::Deprecation.warn('`config.tld_length` have no effect because it was removed in https://github.com/influitive/apartment/pull/309') + end + def db_config_for(tenant) (tenants_with_config[tenant] || connection_config) end From ee8649d79a37ea92373cadbea0e7f2f748524235 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 13:57:54 +0800 Subject: [PATCH 151/282] installing rubocop and running it before tests --- .travis.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.travis.yml b/.travis.yml index 6dd15e76..22adaf7d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -29,6 +29,13 @@ before_install: - sudo /etc/init.d/mysql stop - sudo /etc/init.d/postgresql stop - docker-compose up -d + +install: + - gem install --no-document rubocop + +before_script: + - rubocop --version + env: RUBY_GC_MALLOC_LIMIT: 90000000 RUBY_GC_HEAP_FREE_SLOTS: 200000 From f9523d0e4ebd355422b0c53e6a5615a9fcb059ae Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 14:09:05 +0800 Subject: [PATCH 152/282] installing and running --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 22adaf7d..9b807ec2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,11 +30,11 @@ before_install: - sudo /etc/init.d/postgresql stop - docker-compose up -d -install: - - gem install --no-document rubocop - before_script: - - rubocop --version + - bundle install + +script: + - bundle exec rubocop env: RUBY_GC_MALLOC_LIMIT: 90000000 From 3d95c22ce1d2d18c5061843efb18760d3329c56f Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 14:13:43 +0800 Subject: [PATCH 153/282] explicetly including rubocop --- .travis.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9b807ec2..8ee11c87 100644 --- a/.travis.yml +++ b/.travis.yml @@ -30,16 +30,14 @@ before_install: - sudo /etc/init.d/postgresql stop - docker-compose up -d -before_script: - - bundle install - -script: - - bundle exec rubocop - env: RUBY_GC_MALLOC_LIMIT: 90000000 RUBY_GC_HEAP_FREE_SLOTS: 200000 jobs: + include: + - name: Rubocop Lint + script: bundle exec rubocop + allow_failures: - rvm: ruby-head - rvm: jruby-head From d928ccbf17cbb9de792f32147a904d82a5b8ee4a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 21:42:10 +0800 Subject: [PATCH 154/282] attempt to run rubopcop on travis --- .travis.yml | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8ee11c87..795afa40 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,13 +4,13 @@ language: ruby services: - docker rvm: - - jruby-9.2.11.0 - - 2.4.10 - - 2.5.8 - - 2.6.6 + # - jruby-9.2.11.0 + # - 2.4.10 + # - 2.5.8 + # - 2.6.6 - 2.7.1 - - jruby-head - - ruby-head + # - jruby-head + # - ruby-head branches: only: @@ -18,11 +18,11 @@ branches: - development gemfile: - - gemfiles/rails_5_0.gemfile - - gemfiles/rails_5_1.gemfile - - gemfiles/rails_5_2.gemfile + # - gemfiles/rails_5_0.gemfile + # - gemfiles/rails_5_1.gemfile + # - gemfiles/rails_5_2.gemfile - gemfiles/rails_6_0.gemfile - - gemfiles/rails_master.gemfile + # - gemfiles/rails_master.gemfile bundler_args: --without local before_install: @@ -36,7 +36,7 @@ env: jobs: include: - name: Rubocop Lint - script: bundle exec rubocop + script: gem install perx-rubocop && rubocop allow_failures: - rvm: ruby-head From 523dc0790b43f3e24d860a6a8f2c3e00251f32f1 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 21:48:19 +0800 Subject: [PATCH 155/282] added to ignore list vendor dir --- .rubocop.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.rubocop.yml b/.rubocop.yml index 06ac8bf4..2c505894 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -7,6 +7,7 @@ inherit_gem: AllCops: Exclude: - 'gemfiles/**/*.gemfile' + - 'gemfiles/vendor/**/*' Style/WordArray: Exclude: From c642bb7ddcef680cc603e8a487d962e46b20e955 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 21:52:55 +0800 Subject: [PATCH 156/282] re-enable travis matrix --- .travis.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index 795afa40..ef952b31 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,13 +4,13 @@ language: ruby services: - docker rvm: - # - jruby-9.2.11.0 - # - 2.4.10 - # - 2.5.8 - # - 2.6.6 + - jruby-9.2.11.0 + - 2.4.10 + - 2.5.8 + - 2.6.6 - 2.7.1 - # - jruby-head - # - ruby-head + - jruby-head + - ruby-head branches: only: @@ -18,11 +18,11 @@ branches: - development gemfile: - # - gemfiles/rails_5_0.gemfile - # - gemfiles/rails_5_1.gemfile - # - gemfiles/rails_5_2.gemfile + - gemfiles/rails_5_0.gemfile + - gemfiles/rails_5_1.gemfile + - gemfiles/rails_5_2.gemfile - gemfiles/rails_6_0.gemfile - # - gemfiles/rails_master.gemfile + - gemfiles/rails_master.gemfile bundler_args: --without local before_install: From 9531971e1a17beb1cbc51a7993ba19a158646d8d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 22:08:41 +0800 Subject: [PATCH 157/282] removed rubocop github action --- .github/workflows/.rubocop-linter.yml | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 .github/workflows/.rubocop-linter.yml diff --git a/.github/workflows/.rubocop-linter.yml b/.github/workflows/.rubocop-linter.yml deleted file mode 100644 index 1cbca2f6..00000000 --- a/.github/workflows/.rubocop-linter.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Rubocop Lint - -on: [push, pull_request] - -jobs: - build: - - runs-on: ubuntu-latest - - container: - image: ruby:2.6.5 - - steps: - - uses: actions/checkout@v1 - - name: Rubocop Linter - uses: andrewmcodes/rubocop-linter-action@v2.0.0 - with: - additional_gems: 'perx-rubocop:0.0.3' - fail_level: 'warning' - version: '0.77.0' - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 6f4086a8e7ea51a967a1bbeaeca9b1e4ac624459 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 22:43:01 +0800 Subject: [PATCH 158/282] [70] moved methods to module --- lib/tasks/apartment.rake | 53 ++++++++++------------------------------ 1 file changed, 13 insertions(+), 40 deletions(-) diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 6af72b1e..3623f927 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -1,12 +1,13 @@ # frozen_string_literal: true require 'apartment/migrator' +require 'apartment/tasks/task_helper' require 'parallel' apartment_namespace = namespace :apartment do desc 'Create all tenants' task :create do - tenants.each do |tenant| + Apartment::TaskHelper.tenants.each do |tenant| begin puts("Creating #{tenant} tenant") Apartment::Tenant.create(tenant) @@ -18,7 +19,7 @@ apartment_namespace = namespace :apartment do desc 'Drop all tenants' task :drop do - tenants.each do |tenant| + Apartment::TaskHelper.tenants.each do |tenant| begin puts("Dropping #{tenant} tenant") Apartment::Tenant.drop(tenant) @@ -30,8 +31,8 @@ apartment_namespace = namespace :apartment do desc 'Migrate all tenants' task :migrate do - warn_if_tenants_empty - each_tenant do |tenant| + Apartment::TaskHelper.warn_if_tenants_empty + Apartment::TaskHelper.each_tenant do |tenant| begin puts("Migrating #{tenant} tenant") Apartment::Migrator.migrate tenant @@ -43,9 +44,9 @@ apartment_namespace = namespace :apartment do desc 'Seed all tenants' task :seed do - warn_if_tenants_empty + Apartment::TaskHelper.warn_if_tenants_empty - each_tenant do |tenant| + Apartment::TaskHelper.each_tenant do |tenant| begin puts("Seeding #{tenant} tenant") Apartment::Tenant.switch(tenant) do @@ -59,11 +60,11 @@ apartment_namespace = namespace :apartment do desc 'Rolls the migration back to the previous version (specify steps w/ STEP=n) across all tenants.' task :rollback do - warn_if_tenants_empty + Apartment::TaskHelper.warn_if_tenants_empty step = ENV['STEP'] ? ENV['STEP'].to_i : 1 - each_tenant do |tenant| + Apartment::TaskHelper.each_tenant do |tenant| begin puts("Rolling back #{tenant} tenant") Apartment::Migrator.rollback tenant, step @@ -76,12 +77,12 @@ apartment_namespace = namespace :apartment do namespace :migrate do desc 'Runs the "up" for a given migration VERSION across all tenants.' task :up do - warn_if_tenants_empty + Apartment::TaskHelper.warn_if_tenants_empty version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version - each_tenant do |tenant| + Apartment::TaskHelper.each_tenant do |tenant| begin puts("Migrating #{tenant} tenant up") Apartment::Migrator.run :up, tenant, version @@ -93,12 +94,12 @@ apartment_namespace = namespace :apartment do desc 'Runs the "down" for a given migration VERSION across all tenants.' task :down do - warn_if_tenants_empty + Apartment::TaskHelper.warn_if_tenants_empty version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil raise 'VERSION is required' unless version - each_tenant do |tenant| + Apartment::TaskHelper.each_tenant do |tenant| begin puts("Migrating #{tenant} tenant down") Apartment::Migrator.run :down, tenant, version @@ -119,32 +120,4 @@ apartment_namespace = namespace :apartment do end end end - - def each_tenant(&block) - Parallel.each(tenants_without_default, in_threads: Apartment.parallel_migration_threads) do |tenant| - block.call(tenant) - end - end - - def tenants_without_default - tenants - [Apartment.default_schema] - end - - def tenants - ENV['DB'] ? ENV['DB'].split(',').map(&:strip) : Apartment.tenant_names || [] - end - - def warn_if_tenants_empty - return unless tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' - - puts <<-WARNING - [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: - - 1. You may not have created any, in which case you can ignore this message - 2. You've run `apartment:migrate` directly without loading the Rails environment - * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate` - - Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. - WARNING - end end From dcb627cdda99f70d495070d9ed2cf87a01afbebd Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 22:44:40 +0800 Subject: [PATCH 159/282] [70] added module --- lib/apartment/tasks/task_helper.rb | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 lib/apartment/tasks/task_helper.rb diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb new file mode 100644 index 00000000..b1020dbc --- /dev/null +++ b/lib/apartment/tasks/task_helper.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +module Apartment + module TaskHelper + def self.each_tenant(&block) + Parallel.each(tenants_without_default, in_threads: Apartment.parallel_migration_threads) do |tenant| + block.call(tenant) + end + end + + def self.tenants_without_default + tenants - [Apartment.default_schema] + end + + def self.tenants + ENV['DB'] ? ENV['DB'].split(',').map(&:strip) : Apartment.tenant_names || [] + end + + def self.warn_if_tenants_empty + return unless tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' + + puts <<-WARNING + [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: + + 1. You may not have created any, in which case you can ignore this message + 2. You've run `apartment:migrate` directly without loading the Rails environment + * `apartment:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate` + + Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. + WARNING + end + end +end From 1610f5778b4ac1c9781e6784373c9e1ad63a4da8 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 23:31:26 +0800 Subject: [PATCH 160/282] [#70] fix rubocop --- lib/apartment/tasks/task_helper.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index b1020dbc..311228f4 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -19,6 +19,7 @@ def self.tenants def self.warn_if_tenants_empty return unless tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' + # rubocop:disable Rails/Output puts <<-WARNING [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: @@ -28,6 +29,7 @@ def self.warn_if_tenants_empty Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. WARNING + # rubocop:enable Rails/Output end end end From 59851e909b38527677f13e6195f5aa5d6c477a80 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 23:09:48 +0800 Subject: [PATCH 161/282] [61] do not attempt connection with nil tenant in mysql --- lib/apartment/adapters/mysql2_adapter.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index d35427ff..2ad2191a 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -39,6 +39,7 @@ def initialize(config) # Reset current tenant to the default_tenant # def reset + return if @default_tenant.nil? Apartment.connection.execute "use `#{default_tenant}`" end From 9d1d2ae6ec08c364bd187696bc82dd2ac004e0d2 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 24 Jun 2020 23:43:33 +0800 Subject: [PATCH 162/282] [#61] fixed rubocop --- lib/apartment/adapters/mysql2_adapter.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index 2ad2191a..d7a68d44 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -40,6 +40,7 @@ def initialize(config) # def reset return if @default_tenant.nil? + Apartment.connection.execute "use `#{default_tenant}`" end From aae15e0661f0e6ad5cfb559db42188869cd010a4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 09:51:41 +0800 Subject: [PATCH 163/282] [#61] removed setting default schema in apartment. mysql reset returns unless there is a default tenant --- lib/apartment.rb | 8 ++------ lib/apartment/adapters/mysql2_adapter.rb | 2 +- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 3f9cfeea..b9cdc77a 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -20,11 +20,11 @@ module Apartment class << self extend Forwardable - ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment + ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment default_schema append_environment with_multi_server_setup tenant_presence_check active_record_log].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models - default_schema persistent_schemas connection_class + persistent_schemas connection_class db_migrate_tenants seed_data_file parallel_migration_threads pg_excluded_names].freeze @@ -75,10 +75,6 @@ def excluded_models @excluded_models || [] end - def default_schema - @default_schema || 'public' # TODO: 'public' is postgres specific - end - def parallel_migration_threads @parallel_migration_threads || 0 end diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index d7a68d44..71adbe60 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -39,7 +39,7 @@ def initialize(config) # Reset current tenant to the default_tenant # def reset - return if @default_tenant.nil? + return unless default_tenant Apartment.connection.execute "use `#{default_tenant}`" end From 9c42715b0892297cb4066af8d357b2ccebaacace Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 09:59:32 +0800 Subject: [PATCH 164/282] [#61] replaced default_schema with default_tenant --- HISTORY.md | 2 +- README.md | 6 +++--- TODO.md | 1 - lib/apartment.rb | 4 +--- lib/apartment/adapters/abstract_adapter.rb | 1 - lib/apartment/adapters/postgresql_adapter.rb | 2 ++ spec/examples/schema_adapter_examples.rb | 20 ++++++++++---------- spec/support/apartment_helpers.rb | 2 +- spec/support/contexts.rb | 14 +++++++------- 9 files changed, 25 insertions(+), 27 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index f76c9d24..472519e6 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -302,7 +302,7 @@ # 0.16.0 * June 1, 2012 - - Apartment now supports a default_schema to be set, rather than relying on ActiveRecord's default schema_search_path + - Apartment now supports a default_tenant to be set, rather than relying on ActiveRecord's default schema_search_path - Additional schemas can always be maintained in the schema_search_path by configuring persistent_schemas [ryanbrunner] - This means Hstore is officially supported!! - There is now a full domain based elevator to switch dbs based on the whole domain [lcowell] diff --git a/README.md b/README.md index ecfb6883..b1adea78 100644 --- a/README.md +++ b/README.md @@ -368,12 +368,12 @@ Enable this option with: config.use_sql = true ``` -### Providing a Different default_schema +### Providing a Different default_tenant By default, ActiveRecord will use `"$user", public` as the default `schema_search_path`. This can be modified if you wish to use a different default schema be setting: ```ruby -config.default_schema = "some_other_schema" +config.default_tenant = "some_other_schema" ``` With that set, all excluded models will use this schema as the table name prefix instead of `public` and `reset` on `Apartment::Tenant` will return to this schema as well. @@ -446,7 +446,7 @@ schema_search_path: "public,shared_extensions" ... ``` -This would be for a config with `default_schema` set to `public` and `persistent_schemas` set to `['shared_extensions']`. **Note**: This only works on Heroku with [Rails 4.1+](https://devcenter.heroku.com/changelog-items/426). For apps that use older Rails versions hosted on Heroku, the only way to properly setup is to start with a fresh PostgreSQL instance: +This would be for a config with `default_tenant` set to `public` and `persistent_schemas` set to `['shared_extensions']`. **Note**: This only works on Heroku with [Rails 4.1+](https://devcenter.heroku.com/changelog-items/426). For apps that use older Rails versions hosted on Heroku, the only way to properly setup is to start with a fresh PostgreSQL instance: 1. Append `?schema_search_path=public,hstore` to your `DATABASE_URL` environment variable, by this you don't have to revise the `database.yml` file (which is impossible since Heroku regenerates a completely different and immutable `database.yml` of its own on each deploy) 2. Run `heroku pg:psql` from your command line diff --git a/TODO.md b/TODO.md index 533b9ab2..a5226393 100644 --- a/TODO.md +++ b/TODO.md @@ -46,6 +46,5 @@ Quick TODOs -1. `default_tenant` should be up to the adapter, not the Apartment class, deprecate `default_schema` 2. deprecation.rb rescues everything, we have a hard dependency on ActiveSupport so this is unnecessary 3. diff --git a/lib/apartment.rb b/lib/apartment.rb index b9cdc77a..b0371297 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -20,7 +20,7 @@ module Apartment class << self extend Forwardable - ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment default_schema + ACCESSOR_METHODS = %i[use_schemas use_sql seed_after_create prepend_environment default_tenant append_environment with_multi_server_setup tenant_presence_check active_record_log].freeze WRITER_METHODS = %i[tenant_names database_schema_file excluded_models @@ -78,8 +78,6 @@ def excluded_models def parallel_migration_threads @parallel_migration_threads || 0 end - alias default_tenant default_schema - alias default_tenant= default_schema= def persistent_schemas @persistent_schemas || [] diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 52fb56a7..ce18f396 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -54,7 +54,6 @@ def current def default_tenant @default_tenant || Apartment.default_tenant end - alias default_schema default_tenant # TODO: deprecate default_schema # Drop the tenant # diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index af735256..106197a5 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -25,6 +25,8 @@ def rescue_from # Separate Adapter for Postgresql when using schemas class PostgresqlSchemaAdapter < AbstractAdapter def initialize(config) + @default_tenant = 'public' + super reset diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index fed495a3..e172d613 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -31,17 +31,17 @@ expect(Company.table_name).to eq('public.companies') end - context 'with a default_schema', default_schema: true do + context 'with a default_tenant', default_tenant: true do it 'should set the proper table_name on excluded_models' do Apartment::Tenant.init - expect(Company.table_name).to eq("#{default_schema}.companies") + expect(Company.table_name).to eq("#{default_tenant}.companies") end it 'sets the search_path correctly' do Apartment::Tenant.init - expect(User.connection.schema_search_path).to match(/|#{default_schema}|/) + expect(User.connection.schema_search_path).to match(/|#{default_tenant}|/) end end @@ -138,11 +138,11 @@ expect(connection.schema_search_path).to start_with %("#{public_schema}") end - context 'with default_schema', default_schema: true do + context 'with default_tenant', default_tenant: true do it 'should reset to the default schema' do subject.switch!(schema1) subject.reset - expect(connection.schema_search_path).to start_with %("#{default_schema}") + expect(connection.schema_search_path).to start_with %("#{default_tenant}") end end @@ -156,10 +156,10 @@ expect(connection.schema_search_path).to end_with persistent_schemas.map { |schema| %("#{schema}") }.join(', ') end - context 'with default_schema', default_schema: true do + context 'with default_tenant', default_tenant: true do it 'prioritizes the switched schema to front of schema_search_path' do - subject.reset # need to re-call this as the default_schema wasn't set at the time that the above reset ran - expect(connection.schema_search_path).to start_with %("#{default_schema}") + subject.reset # need to re-call this as the default_tenant wasn't set at the time that the above reset ran + expect(connection.schema_search_path).to start_with %("#{default_tenant}") end end end @@ -213,13 +213,13 @@ after { subject.drop(db) } end - describe 'with default_schema specified', default_schema: true do + describe 'with default_tenant specified', default_tenant: true do before do subject.switch!(schema1) end it 'should switch out the default schema rather than public' do - expect(connection.schema_search_path).not_to include default_schema + expect(connection.schema_search_path).not_to include default_tenant end it 'should still switch to the switched schema' do diff --git a/spec/support/apartment_helpers.rb b/spec/support/apartment_helpers.rb index d45ea1b3..0641b13f 100644 --- a/spec/support/apartment_helpers.rb +++ b/spec/support/apartment_helpers.rb @@ -10,7 +10,7 @@ def reset Apartment.excluded_models = nil Apartment.use_schemas = nil Apartment.seed_after_create = nil - Apartment.default_schema = nil + Apartment.default_tenant = nil end def next_db diff --git a/spec/support/contexts.rb b/spec/support/contexts.rb index 9c63f0a1..6581f8b0 100644 --- a/spec/support/contexts.rb +++ b/spec/support/contexts.rb @@ -2,18 +2,18 @@ # Some shared contexts for specs -shared_context 'with default schema', default_schema: true do - let(:default_schema) { Apartment::Test.next_db } +shared_context 'with default schema', default_tenant: true do + let(:default_tenant) { Apartment::Test.next_db } before do - Apartment::Test.create_schema(default_schema) - Apartment.default_schema = default_schema + Apartment::Test.create_schema(default_tenant) + Apartment.default_tenant = default_tenant end after do - # resetting default_schema so we can drop and any further resets won't try to access droppped schema - Apartment.default_schema = nil - Apartment::Test.drop_schema(default_schema) + # resetting default_tenant so we can drop and any further resets won't try to access droppped schema + Apartment.default_tenant = nil + Apartment::Test.drop_schema(default_tenant) end end From aba9dbfd11c6ade6bed99a9c3b52b660933bc1e9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 10:00:17 +0800 Subject: [PATCH 165/282] [#61] revert history --- HISTORY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HISTORY.md b/HISTORY.md index 472519e6..f76c9d24 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -302,7 +302,7 @@ # 0.16.0 * June 1, 2012 - - Apartment now supports a default_tenant to be set, rather than relying on ActiveRecord's default schema_search_path + - Apartment now supports a default_schema to be set, rather than relying on ActiveRecord's default schema_search_path - Additional schemas can always be maintained in the schema_search_path by configuring persistent_schemas [ryanbrunner] - This means Hstore is officially supported!! - There is now a full domain based elevator to switch dbs based on the whole domain [lcowell] From 26e1443153c6b10c99ff5154f53fc0ccd37b7111 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 10:48:01 +0800 Subject: [PATCH 166/282] [#61] setting default tenant on postgresql config --- lib/apartment/adapters/postgresql_adapter.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 106197a5..145cf559 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -25,13 +25,15 @@ def rescue_from # Separate Adapter for Postgresql when using schemas class PostgresqlSchemaAdapter < AbstractAdapter def initialize(config) - @default_tenant = 'public' - super reset end + def default_tenant + @default_tenant ||= Apartment.default_tenant || 'public' + end + # Reset schema search path to the default schema_search_path # # @return {String} default schema search path From e7528572962a32005ec9e0b5c3029a16c7b5d72e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 21:52:46 +0800 Subject: [PATCH 167/282] [#61] fixed merge conflict leftover --- lib/apartment/tasks/task_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index 311228f4..aefa8dd4 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -9,7 +9,7 @@ def self.each_tenant(&block) end def self.tenants_without_default - tenants - [Apartment.default_schema] + tenants - [Apartment.default_tenant] end def self.tenants From 3d3276818e969f04e3f52596f6f6959889b04bb0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 22:16:46 +0800 Subject: [PATCH 168/282] [#61] apartment default tenant is only used to initialize the adapter default tenant if present --- spec/tenant_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/tenant_spec.rb b/spec/tenant_spec.rb index aa32a0ff..e3aacf04 100644 --- a/spec/tenant_spec.rb +++ b/spec/tenant_spec.rb @@ -83,7 +83,7 @@ it 'has a threadsafe adapter' do subject.switch!(db1) - thread = Thread.new { expect(subject.current).to eq(Apartment.default_tenant) } + thread = Thread.new { expect(subject.current).to eq(subject.adapter.default_tenant) } thread.join expect(subject.current).to eq(db1) end From 2d7ab16aae33e52658aca60bbf277caf12547c28 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 25 Jun 2020 22:27:02 +0800 Subject: [PATCH 169/282] [#61] dont cache the default tenant --- lib/apartment/adapters/postgresql_adapter.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 145cf559..0cc8f231 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -31,7 +31,7 @@ def initialize(config) end def default_tenant - @default_tenant ||= Apartment.default_tenant || 'public' + @default_tenant = Apartment.default_tenant || 'public' end # Reset schema search path to the default schema_search_path From 4c44f0c8c96cb84726c08c0ec9c407423787cde8 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 26 Jun 2020 10:50:48 +0800 Subject: [PATCH 170/282] Version Bump to 2.7.0 --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 5a564a2c..0986bd0e 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.6.1' + VERSION = '2.7.0' end From 5ae5d9b76dc7d00882ee04e5975e38df5227c2fd Mon Sep 17 00:00:00 2001 From: pavel Date: Thu, 25 Jun 2020 19:25:18 +0200 Subject: [PATCH 171/282] update rake --- apartment.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apartment.gemspec b/apartment.gemspec index d07567df..5b4fca15 100644 --- a/apartment.gemspec +++ b/apartment.gemspec @@ -36,7 +36,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'appraisal', '~> 2.2' s.add_development_dependency 'bundler', '>= 1.3', '< 3.0' s.add_development_dependency 'capybara', '~> 2.0' - s.add_development_dependency 'rake', '~> 0.9' + s.add_development_dependency 'rake', '~> 13.0' s.add_development_dependency 'rspec', '~> 3.4' s.add_development_dependency 'rspec-rails', '~> 3.4' From a1de9d64c25387d529cd8f72cbcc67e63a648305 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sat, 27 Jun 2020 11:34:18 +0800 Subject: [PATCH 172/282] [Chore] renamed gemspec to match gem name --- apartment.gemspec => ros-apartment.gemspec | 1 - 1 file changed, 1 deletion(-) rename apartment.gemspec => ros-apartment.gemspec (97%) diff --git a/apartment.gemspec b/ros-apartment.gemspec similarity index 97% rename from apartment.gemspec rename to ros-apartment.gemspec index 5b4fca15..5c01be69 100644 --- a/apartment.gemspec +++ b/ros-apartment.gemspec @@ -27,7 +27,6 @@ Gem::Specification.new do |s| s.homepage = 'https://github.com/rails-on-services/apartment' s.licenses = ['MIT'] - # must be >= 3.1.2 due to bug in prepared_statements s.add_dependency 'activerecord', '>= 5.0.0', '< 6.1' s.add_dependency 'parallel', '< 2.0' s.add_dependency 'public_suffix', '>= 2.0.5', '< 5.0' From b6af077ceb4b16b3a5e27c0126f8d645107b5a24 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 26 Jun 2020 23:41:21 +0800 Subject: [PATCH 173/282] [#82] remove create from enhanced tasks and seed requires create to have run --- lib/apartment/tasks/enhancements.rb | 2 +- lib/tasks/apartment.rake | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/apartment/tasks/enhancements.rb b/lib/apartment/tasks/enhancements.rb index ede5c1f3..f9a13206 100644 --- a/lib/apartment/tasks/enhancements.rb +++ b/lib/apartment/tasks/enhancements.rb @@ -7,7 +7,7 @@ module Apartment class RakeTaskEnhancer module TASKS ENHANCE_BEFORE = %w[db:drop].freeze - ENHANCE_AFTER = %w[db:create db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed].freeze + ENHANCE_AFTER = %w[db:migrate db:rollback db:migrate:up db:migrate:down db:migrate:redo db:seed].freeze freeze end diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 3623f927..f4583074 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -7,6 +7,8 @@ require 'parallel' apartment_namespace = namespace :apartment do desc 'Create all tenants' task :create do + Apartment::TaskHelper.warn_if_tenants_empty + Apartment::TaskHelper.tenants.each do |tenant| begin puts("Creating #{tenant} tenant") @@ -43,7 +45,7 @@ apartment_namespace = namespace :apartment do end desc 'Seed all tenants' - task :seed do + task seed: :create do Apartment::TaskHelper.warn_if_tenants_empty Apartment::TaskHelper.each_tenant do |tenant| From f508098cf8508ca51357032d3e758f97a78c73ab Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sat, 27 Jun 2020 12:23:09 +0800 Subject: [PATCH 174/282] Version Bump to 2.7.1 --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 0986bd0e..215a1191 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.7.0' + VERSION = '2.7.1' end From 6f7ecf2fc9e21bc5e9965165905570fd803d463a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sat, 27 Jun 2020 12:27:49 +0800 Subject: [PATCH 175/282] Update history with the recent releases --- HISTORY.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/HISTORY.md b/HISTORY.md index f76c9d24..43165b28 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,36 @@ +# 2.7.1 + +# Enhancements + +- N/a + +# Bugfixes + +- [Resolves #82] Enhanced db:create breaks plugin compatibility - + +# Chores + +- Update rake version in development +- Renamed gemspec to match gem name + +# 2.7.0 + +# Enhancements + +- [Resolves #70] Rake tasks define methods on main - +- Add database and schema to active record log. Configurable, defaults to false to keep current behavior - + +# Bugfixes + +- [Fixes #61] Fix database create in mysql - + +# Chores + +- Remove deprecated tld_length config option: tld_length was removed in influitive#309, this configuration option doesn't have any effect now. - +- Using [diffend.io proxy](https://diffend.io) to safely check required gems +- Added [story branch](https://github.com/story-branch/story_branch) to the configuration +- Using travis-ci to run rubocop as well, replacing github actions: github actions do not work in fork's PRs + # 2.6.1 ## Enhancements From 96f36fde37c9ce16ac8acaaf36d77e3a4a821892 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 15:58:45 +0800 Subject: [PATCH 176/282] [#81] check for var existence before --- lib/apartment/adapters/postgresql_adapter.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 0cc8f231..a2ca1163 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -125,7 +125,9 @@ def reset_sequence_names .select { |c| c.instance_variable_defined?(:@sequence_name) } .reject { |c| c.instance_variable_defined?(:@explicit_sequence_name) && c.instance_variable_get(:@explicit_sequence_name) } .each do |c| - c.remove_instance_variable :@sequence_name + # NOTE: due to this https://github.com/rails-on-services/apartment/issues/81 + # unreproduceable error we're checking before trying to remove it + c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) end end end From 99dfda82b9817085ca9f177862e839d006012d24 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 16:03:38 +0800 Subject: [PATCH 177/282] [#80] added changelog action --- .github/workflows/changelog.yml | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .github/workflows/changelog.yml diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 00000000..c6796c9b --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,2 @@ +- name: Automatic Changelog Generator + uses: CharMixer/auto-changelog-action@v1 From b506bc7be3f37867b52315d4a852ab5a488051a9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 16:07:09 +0800 Subject: [PATCH 178/282] [#80] updated action --- .github/workflows/changelog.yml | 42 +++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index c6796c9b..27a5f690 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -1,2 +1,40 @@ -- name: Automatic Changelog Generator - uses: CharMixer/auto-changelog-action@v1 +name: Changelog + +on: + pull_request: + types: [closed] + + release: + types: [published] + + issues: + types: [closed, edited] + +jobs: + generate_changelog: + runs-on: ubuntu-latest + name: Generate changelog for master branch + steps: + - uses: actions/checkout@v1 + + - name: Generate changelog + uses: charmixer/auto-changelog-action@v1 + with: + token: ${{ secrets.YOUR_GITHUB_TOKEN or GITHUB_TOKEN }} + + - name: Commit files + env: + CI_USER: ${{ secrets.YOUR_GITHUB_USER }} + CI_EMAIL: ${{ secrets.YOUR_GITHUB_EMAIL }} + run: | + git config --local user.email "$CI_EMAIL" + git config --local user.name "$CI_USER" + git add CHANGELOG.md && git commit -m 'Updated CHANGELOG.md' && echo ::set-env name=push::1 || echo "No changes to CHANGELOG.md" + + - name: Push changes + if: env.push == 1 + env: + CI_USER: ${{ secrets.YOUR_GITHUB_USER }} + CI_TOKEN: ${{ secrets.YOUR_GITHUB_TOKEN or GITHUB_TOKEN }} + run: | + git push "https://$CI_USER:$CI_TOKEN@github.com/$GITHUB_REPOSITORY.git" HEAD:master From ea144128face956accedf820717558ba263f502a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 16:32:02 +0800 Subject: [PATCH 179/282] [#80] ran automatic changelog generator to create changelog file --- CHANGELOG.md | 870 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 870 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..583563c0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,870 @@ +# Changelog + +## [Unreleased](https://github.com/rails-on-services/apartment/tree/HEAD) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.1...HEAD) + +**Closed issues:** + +- Error creating tenant with uuid column [\#85](https://github.com/rails-on-services/apartment/issues/85) +- enhanced db:create task breaks plugins compatibility [\#82](https://github.com/rails-on-services/apartment/issues/82) + +## [v2.7.1](https://github.com/rails-on-services/apartment/tree/v2.7.1) (2020-06-27) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.0...v2.7.1) + +**Merged pull requests:** + +- Prepare Release 2.7.1 [\#84](https://github.com/rails-on-services/apartment/pull/84) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#82\] Enhanced db create task breaks plugins compatibility [\#83](https://github.com/rails-on-services/apartment/pull/83) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[ci\] update rake [\#79](https://github.com/rails-on-services/apartment/pull/79) ([ahorek](https://github.com/ahorek)) + +## [v2.7.0](https://github.com/rails-on-services/apartment/tree/v2.7.0) (2020-06-26) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.6.1...v2.7.0) + +**Implemented enhancements:** + +- Rake tasks define methods on main [\#70](https://github.com/rails-on-services/apartment/issues/70) + +**Fixed bugs:** + +- Undefined method devise with 2.6.1 [\#65](https://github.com/rails-on-services/apartment/issues/65) +- db:create is failed [\#61](https://github.com/rails-on-services/apartment/issues/61) + +**Closed issues:** + +- configure story branch [\#68](https://github.com/rails-on-services/apartment/issues/68) +- HISTORY.md has not been updated for latest releases [\#62](https://github.com/rails-on-services/apartment/issues/62) +- \[Postgresql users\] Help testing development branch in your environment [\#34](https://github.com/rails-on-services/apartment/issues/34) + +**Merged pull requests:** + +- Prepare Release - 2.7.0 [\#77](https://github.com/rails-on-services/apartment/pull/77) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Fixes \#61\] db create is failed [\#76](https://github.com/rails-on-services/apartment/pull/76) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#70\] rake tasks define methods on main [\#75](https://github.com/rails-on-services/apartment/pull/75) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Chore\] Update travis config to run rubocop [\#74](https://github.com/rails-on-services/apartment/pull/74) ([rpbaltazar](https://github.com/rpbaltazar)) +- Remove and warn depracated config `tld\_length` [\#72](https://github.com/rails-on-services/apartment/pull/72) ([choznerol](https://github.com/choznerol)) +- \[Resolves \#62\] added Missing notes in history.md [\#63](https://github.com/rails-on-services/apartment/pull/63) ([rpbaltazar](https://github.com/rpbaltazar)) +- Add database and schema to active record log [\#55](https://github.com/rails-on-services/apartment/pull/55) ([woohoou](https://github.com/woohoou)) + +## [v2.6.1](https://github.com/rails-on-services/apartment/tree/v2.6.1) (2020-06-02) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.6.0...v2.6.1) + +**Closed issues:** + +- db:rollback uses second latest migration for tenants [\#56](https://github.com/rails-on-services/apartment/issues/56) +- rake db:setup tries to seed non existing tenant [\#52](https://github.com/rails-on-services/apartment/issues/52) +- Custom Console deprecation warning [\#37](https://github.com/rails-on-services/apartment/issues/37) + +**Merged pull requests:** + +- Version bump - 2.6.1 [\#60](https://github.com/rails-on-services/apartment/pull/60) ([rpbaltazar](https://github.com/rpbaltazar)) +- Prepare Release - 2.6.1 [\#59](https://github.com/rails-on-services/apartment/pull/59) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[\#56\] Db rollback uses second latest migration [\#57](https://github.com/rails-on-services/apartment/pull/57) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[\#52\] enhance after db create [\#54](https://github.com/rails-on-services/apartment/pull/54) ([rpbaltazar](https://github.com/rpbaltazar)) +- fix init after reload on development [\#53](https://github.com/rails-on-services/apartment/pull/53) ([fsateler](https://github.com/fsateler)) +- fix: reset sequence\_name after tenant switch [\#51](https://github.com/rails-on-services/apartment/pull/51) ([fsateler](https://github.com/fsateler)) +- Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) + +## [v2.6.0](https://github.com/rails-on-services/apartment/tree/v2.6.0) (2020-05-14) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.5.0...v2.6.0) + +**Closed issues:** + +- Error Dropping Tenant [\#46](https://github.com/rails-on-services/apartment/issues/46) +- After switch callback not working with nil argument [\#42](https://github.com/rails-on-services/apartment/issues/42) +- Add tenant info to console boot? [\#41](https://github.com/rails-on-services/apartment/issues/41) +- Support configuration for skip checking of schema existence before switching [\#26](https://github.com/rails-on-services/apartment/issues/26) + +**Merged pull requests:** + +- \[Resolves \#37\] Custom console deprecation warning [\#49](https://github.com/rails-on-services/apartment/pull/49) ([rpbaltazar](https://github.com/rpbaltazar)) +- Prepare Release 2.6.0 [\#48](https://github.com/rails-on-services/apartment/pull/48) ([rpbaltazar](https://github.com/rpbaltazar)) +- Add console welcome message [\#47](https://github.com/rails-on-services/apartment/pull/47) ([JeremiahChurch](https://github.com/JeremiahChurch)) +- \[Resolves \#26\] Support configuration for skip checking of schema existence before switching [\#45](https://github.com/rails-on-services/apartment/pull/45) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#42\] After switch callback not working with nil argument [\#43](https://github.com/rails-on-services/apartment/pull/43) ([rpbaltazar](https://github.com/rpbaltazar)) + +## [v2.5.0](https://github.com/rails-on-services/apartment/tree/v2.5.0) (2020-05-05) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/2.4.0...v2.5.0) + +**Implemented enhancements:** + +- Add latest ruby verisons to test matrix [\#31](https://github.com/rails-on-services/apartment/issues/31) +- Deprecate EOL ruby and rails versions [\#11](https://github.com/rails-on-services/apartment/issues/11) + +**Fixed bugs:** + +- When manually switching the connection it resets the search path [\#27](https://github.com/rails-on-services/apartment/issues/27) + +**Closed issues:** + +- Cached statement breaks in find [\#35](https://github.com/rails-on-services/apartment/issues/35) +- rails 6.1.alpha support [\#6](https://github.com/rails-on-services/apartment/issues/6) +- How to exclude all models from engine? [\#4](https://github.com/rails-on-services/apartment/issues/4) + +**Merged pull requests:** + +- Prepare Release 2.5.0 [\#44](https://github.com/rails-on-services/apartment/pull/44) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#27\] Added before hook to connected to to try to set the tenant [\#40](https://github.com/rails-on-services/apartment/pull/40) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#35\] update cache key to use a string or an array [\#36](https://github.com/rails-on-services/apartment/pull/36) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Hotfix \#27\] Some errors were being thrown due to caching issues [\#33](https://github.com/rails-on-services/apartment/pull/33) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Chore\] refactored files to their names [\#29](https://github.com/rails-on-services/apartment/pull/29) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#27\] When manually switching the connection it resets the search path [\#28](https://github.com/rails-on-services/apartment/pull/28) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) +- Support rails 6.1 [\#7](https://github.com/rails-on-services/apartment/pull/7) ([jean-francois-labbe](https://github.com/jean-francois-labbe)) + +## [2.4.0](https://github.com/rails-on-services/apartment/tree/2.4.0) (2020-04-01) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.3.0...2.4.0) + +**Implemented enhancements:** + +- Add console info about tenants and fast switches [\#14](https://github.com/rails-on-services/apartment/issues/14) +- Update travis config to only run PR's instead of running all commits [\#12](https://github.com/rails-on-services/apartment/issues/12) + +**Closed issues:** + +- Rubocop cleanup [\#9](https://github.com/rails-on-services/apartment/issues/9) +- Apartment.configure throws NoMethodError [\#3](https://github.com/rails-on-services/apartment/issues/3) +- upcoming Rails 6 multi-database [\#2](https://github.com/rails-on-services/apartment/issues/2) + +**Merged pull requests:** + +- Fix gemspec open versions and updated version [\#25](https://github.com/rails-on-services/apartment/pull/25) ([rpbaltazar](https://github.com/rpbaltazar)) +- Fix gemspec open versions and updated version [\#24](https://github.com/rails-on-services/apartment/pull/24) ([rpbaltazar](https://github.com/rpbaltazar)) +- Cleanup travis matrix [\#23](https://github.com/rails-on-services/apartment/pull/23) ([rpbaltazar](https://github.com/rpbaltazar)) +- Prepare v2.4.0 Release [\#22](https://github.com/rails-on-services/apartment/pull/22) ([rpbaltazar](https://github.com/rpbaltazar)) +- Updated readme badges [\#21](https://github.com/rails-on-services/apartment/pull/21) ([rpbaltazar](https://github.com/rpbaltazar)) +- Rescuing ActiveRecord::NoDatabaseError when dropping tenants [\#19](https://github.com/rails-on-services/apartment/pull/19) ([rpbaltazar](https://github.com/rpbaltazar)) +- Skip init if we're running webpacker:compile [\#18](https://github.com/rails-on-services/apartment/pull/18) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#14\] Add console info about tenants and fast switches [\#17](https://github.com/rails-on-services/apartment/pull/17) ([rpbaltazar](https://github.com/rpbaltazar)) +- Don't crash when no database connection is present [\#16](https://github.com/rails-on-services/apartment/pull/16) ([ArthurWD](https://github.com/ArthurWD)) +- \[Resolves \#12\] Update travis config to only run PRs instead of all commits [\#13](https://github.com/rails-on-services/apartment/pull/13) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Chore\] Fix rubocop usage [\#10](https://github.com/rails-on-services/apartment/pull/10) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#9\] Cleanup rubocop todo [\#8](https://github.com/rails-on-services/apartment/pull/8) ([rpbaltazar](https://github.com/rpbaltazar)) +- Rakefile should use mysql port from configuration [\#5](https://github.com/rails-on-services/apartment/pull/5) ([jean-francois-labbe](https://github.com/jean-francois-labbe)) + +## [v2.3.0](https://github.com/rails-on-services/apartment/tree/v2.3.0) (2020-01-03) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.2.1...v2.3.0) + +**Merged pull requests:** + +- \[Resolves\] Basic support for Rails 6 [\#1](https://github.com/rails-on-services/apartment/pull/1) ([rpbaltazar](https://github.com/rpbaltazar)) + +## [v2.2.1](https://github.com/rails-on-services/apartment/tree/v2.2.1) (2019-06-19) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.2.0...v2.2.1) + +## [v2.2.0](https://github.com/rails-on-services/apartment/tree/v2.2.0) (2018-04-13) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.1.0...v2.2.0) + +## [v2.1.0](https://github.com/rails-on-services/apartment/tree/v2.1.0) (2017-12-15) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.0.0...v2.1.0) + +## [v2.0.0](https://github.com/rails-on-services/apartment/tree/v2.0.0) (2017-07-26) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v1.2.0...v2.0.0) + +## [v1.2.0](https://github.com/rails-on-services/apartment/tree/v1.2.0) (2016-07-28) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v1.1.0...v1.2.0) + +## [v1.1.0](https://github.com/rails-on-services/apartment/tree/v1.1.0) (2016-05-26) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v1.0.2...v1.1.0) + +## [v1.0.2](https://github.com/rails-on-services/apartment/tree/v1.0.2) (2015-07-02) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v1.0.1...v1.0.2) + +## [v1.0.1](https://github.com/rails-on-services/apartment/tree/v1.0.1) (2015-04-28) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v1.0.0...v1.0.1) + +## [v1.0.0](https://github.com/rails-on-services/apartment/tree/v1.0.0) (2015-02-03) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.26.1...v1.0.0) + +## [v0.26.1](https://github.com/rails-on-services/apartment/tree/v0.26.1) (2015-01-13) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.26.0...v0.26.1) + +## [v0.26.0](https://github.com/rails-on-services/apartment/tree/v0.26.0) (2015-01-05) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.25.2...v0.26.0) + +## [v0.25.2](https://github.com/rails-on-services/apartment/tree/v0.25.2) (2014-09-08) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.25.1...v0.25.2) + +## [v0.25.1](https://github.com/rails-on-services/apartment/tree/v0.25.1) (2014-07-17) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.25.0...v0.25.1) + +## [v0.25.0](https://github.com/rails-on-services/apartment/tree/v0.25.0) (2014-07-03) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.24.3...v0.25.0) + +## [v0.24.3](https://github.com/rails-on-services/apartment/tree/v0.24.3) (2014-03-05) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.24.2...v0.24.3) + +## [v0.24.2](https://github.com/rails-on-services/apartment/tree/v0.24.2) (2014-02-24) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.24.1...v0.24.2) + +## [v0.24.1](https://github.com/rails-on-services/apartment/tree/v0.24.1) (2014-02-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.24.0...v0.24.1) + +## [v0.24.0](https://github.com/rails-on-services/apartment/tree/v0.24.0) (2014-02-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.23.2...v0.24.0) + +## [v0.23.2](https://github.com/rails-on-services/apartment/tree/v0.23.2) (2014-01-09) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.23.1...v0.23.2) + +## [v0.23.1](https://github.com/rails-on-services/apartment/tree/v0.23.1) (2014-01-08) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.23.0...v0.23.1) + +## [v0.23.0](https://github.com/rails-on-services/apartment/tree/v0.23.0) (2013-12-15) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.22.1...v0.23.0) + +## [v0.22.1](https://github.com/rails-on-services/apartment/tree/v0.22.1) (2013-08-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.22.0...v0.22.1) + +## [v0.22.0](https://github.com/rails-on-services/apartment/tree/v0.22.0) (2013-07-09) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.21.1...v0.22.0) + +## [v0.21.1](https://github.com/rails-on-services/apartment/tree/v0.21.1) (2013-05-31) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.21.0...v0.21.1) + +## [v0.21.0](https://github.com/rails-on-services/apartment/tree/v0.21.0) (2013-04-25) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.20.0...v0.21.0) + +## [v0.20.0](https://github.com/rails-on-services/apartment/tree/v0.20.0) (2013-02-06) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.2...v0.20.0) + +## [v0.19.2](https://github.com/rails-on-services/apartment/tree/v0.19.2) (2013-01-30) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/rm...v0.19.2) + +## [rm](https://github.com/rails-on-services/apartment/tree/rm) (2013-01-30) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.0...rm) + +## [v0.19.0](https://github.com/rails-on-services/apartment/tree/v0.19.0) (2012-12-30) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.18.0...v0.19.0) + +## [v0.18.0](https://github.com/rails-on-services/apartment/tree/v0.18.0) (2012-11-28) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.17.3...v0.18.0) + +## [v0.17.3](https://github.com/rails-on-services/apartment/tree/v0.17.3) (2012-11-20) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.17.2...v0.17.3) + +## [v0.17.2](https://github.com/rails-on-services/apartment/tree/v0.17.2) (2012-11-15) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.17.1...v0.17.2) + +## [v0.17.1](https://github.com/rails-on-services/apartment/tree/v0.17.1) (2012-10-30) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.17.0...v0.17.1) + +## [v0.17.0](https://github.com/rails-on-services/apartment/tree/v0.17.0) (2012-09-26) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.16.0...v0.17.0) + +## [v0.16.0](https://github.com/rails-on-services/apartment/tree/v0.16.0) (2012-06-01) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.15.0...v0.16.0) + +## [v0.15.0](https://github.com/rails-on-services/apartment/tree/v0.15.0) (2012-03-18) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.14.4...v0.15.0) + +## [v0.14.4](https://github.com/rails-on-services/apartment/tree/v0.14.4) (2012-03-08) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.14.3...v0.14.4) + +## [v0.14.3](https://github.com/rails-on-services/apartment/tree/v0.14.3) (2012-02-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.14.2...v0.14.3) + +## [v0.14.2](https://github.com/rails-on-services/apartment/tree/v0.14.2) (2012-02-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.13.0.1...v0.14.2) + +## [v0.13.0.1](https://github.com/rails-on-services/apartment/tree/v0.13.0.1) (2012-02-09) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.14.1...v0.13.0.1) + +## [v0.14.1](https://github.com/rails-on-services/apartment/tree/v0.14.1) (2011-12-13) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.14.0...v0.14.1) + +## [v0.14.0](https://github.com/rails-on-services/apartment/tree/v0.14.0) (2011-12-13) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.13.1...v0.14.0) + +## [v0.13.1](https://github.com/rails-on-services/apartment/tree/v0.13.1) (2011-11-08) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.13.0...v0.13.1) + +## [v0.13.0](https://github.com/rails-on-services/apartment/tree/v0.13.0) (2011-10-25) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.12.0...v0.13.0) + +## [v0.12.0](https://github.com/rails-on-services/apartment/tree/v0.12.0) (2011-10-04) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.11.1...v0.12.0) + +## [v0.11.1](https://github.com/rails-on-services/apartment/tree/v0.11.1) (2011-09-22) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.11.0...v0.11.1) + +## [v0.11.0](https://github.com/rails-on-services/apartment/tree/v0.11.0) (2011-09-20) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.10.3...v0.11.0) + +## [v0.10.3](https://github.com/rails-on-services/apartment/tree/v0.10.3) (2011-09-20) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.10.2...v0.10.3) + +## [v0.10.2](https://github.com/rails-on-services/apartment/tree/v0.10.2) (2011-09-15) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.10.1...v0.10.2) + +## [v0.10.1](https://github.com/rails-on-services/apartment/tree/v0.10.1) (2011-08-11) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.10.0...v0.10.1) + +## [v0.10.0](https://github.com/rails-on-services/apartment/tree/v0.10.0) (2011-07-29) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.9.2...v0.10.0) + +## [v0.9.2](https://github.com/rails-on-services/apartment/tree/v0.9.2) (2011-07-04) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.9.1...v0.9.2) + +## [v0.9.1](https://github.com/rails-on-services/apartment/tree/v0.9.1) (2011-06-24) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.9.0...v0.9.1) + +## [v0.9.0](https://github.com/rails-on-services/apartment/tree/v0.9.0) (2011-06-23) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.8.0...v0.9.0) + +## [v0.8.0](https://github.com/rails-on-services/apartment/tree/v0.8.0) (2011-06-23) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.7.0...v0.8.0) + +## [v0.7.0](https://github.com/rails-on-services/apartment/tree/v0.7.0) (2011-06-22) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/0.6.0...v0.7.0) + +## [0.6.0](https://github.com/rails-on-services/apartment/tree/0.6.0) (2011-06-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.6.0...0.6.0) + +## [v0.6.0](https://github.com/rails-on-services/apartment/tree/v0.6.0) (2011-06-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.5.1...v0.6.0) + +## [v0.5.1](https://github.com/rails-on-services/apartment/tree/v0.5.1) (2011-06-21) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/0.5.0...v0.5.1) + +## [0.5.0](https://github.com/rails-on-services/apartment/tree/0.5.0) (2011-06-20) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.5.0...0.5.0) + +## [v0.5.0](https://github.com/rails-on-services/apartment/tree/v0.5.0) (2011-06-20) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.1.3...v0.5.0) + +## [v0.1.3](https://github.com/rails-on-services/apartment/tree/v0.1.3) (2011-04-18) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/7100f34a185ab7d48947f06aa8c14f0cf0a68bb7...v0.1.3) + +# 2.7.1 + + +- N/a + +- [Resolves #82] Enhanced db:create breaks plugin compatibility - + +- Update rake version in development +- Renamed gemspec to match gem name + +# 2.7.0 + + +- [Resolves #70] Rake tasks define methods on main - +- Add database and schema to active record log. Configurable, defaults to false to keep current behavior - + +- [Fixes #61] Fix database create in mysql - + +- Remove deprecated tld_length config option: tld_length was removed in influitive#309, this configuration option doesn't have any effect now. - +- Using [diffend.io proxy](https://diffend.io) to safely check required gems +- Added [story branch](https://github.com/story-branch/story_branch) to the configuration +- Using travis-ci to run rubocop as well, replacing github actions: github actions do not work in fork's PRs + +# 2.6.1 + +- N/a +- [Resolves influitive#607] Avoid early connection + - + - + - +- [Resolves #52] Rake db:setup tries to seed non existent tenant - +- [Resolves #56] DB rollback uses second last migration - + +- N/a + +# 2.6.0 + +- [Resolves #26] Support configuration for skip checking of schema existence before switching +- [Resolves #41] Add tenant info to console boot +- [Resolves #37] Custom Console deprecation warning +- [Resolves #42] After switch callback not working with nil argument + +- Updated github actions configuration to run on PRs as well + +# 2.5.0 + +- [Resolves #6] Adds support for rails 6.1 +- [Resolves #27] Adds support to not rely on set search path, but instead prepends the schema name to the table name when using postgresql with schemas. +- [Resolves #35] Cache keys are now tenant dependent +- [Resolves #27] Manually switching connection between read and write forgets the schema + +- [Resolves #31] Add latest ruby versions to test matrix + +# 2.4.0 + +- [Resolves #14] Add console info about tenants and fast switches #17 +- Skip init if we're running webpacker:compile #18 +- Don't crash when no database connection is present #16 +- Rescuing ActiveRecord::NoDatabaseError when dropping tenants #19 + +- Rakefile should use mysql port from configuration #5 +- [Resolves #9] Cleanup rubocop todo #8 +- Cleanup travis matrix #23 + +# 2.3.0 + * January 3, 2020 + + - Basic support for rails 6 + - Released different gem name, with same API as apartment + +# 2.2.1 + * June 19, 2019 + + - #566: IGNORE_EMPTY_TENANTS environment variable to ignore empty tenants + warning. [Pysis868] + + - #586: Ignore `CREATE SCHEMA public` statement in pg dump [artemave] + - #549: Fix Postgres schema creation with dump SQL [ancorcruz] + +# 2.2.0 + * April 14, 2018 + + - #523: Add Rails 5.2 support [IngusSkaistkalns] + - #504: Test against Ruby 2.5.0 [ahorek] + - #528: Test against Rails 5.2 [meganemura] + + - #504: Remove Rails 4.0/4.1 support [ahorek] + - #545: Stop supporting for JRuby + Rails 5.0 [meganemura] + + - #537: Fix PostgresqlSchemaFromSqlAdapter for newer PostgreSQL [shterrett] + - #532: Issue is reported by [aldrinmartoq] + - #519: Fix exception when main database doesn't exist [mayeco] + + - #514: Fix typo [menorval] + +# 2.1.0 + * December 15, 2017 + + - Add `parallel_migration_threads` configuration option for running migrations + in parallel [ryanbrunner] + - Drop Ruby 2.0.0 support [meganemura] + - ignore_private when parsing subdomains with PublicSuffix [michiomochi] + - Ignore row_security statements in psql dumps for backward compatibility + [meganemura] + - "Host" elevator [shrmnk] + - Enhance db:drop task to act on all tenants [kuzukuzu] + +# 2.0.0 + * July 26, 2017 + + - Raise FileNotFound rather than abort when loading files [meganemura] + - Add 5.1 support with fixes for deprecations [meganemura] + - Fix tests for 5.x and a host of dev-friendly improvements [meganemura] + - Keep query cache config after switching databases [fernandomm] + - Pass constants not strings to middleware stack (Rails 5) [tzabaman] + - Remove deprecations from 1.0.0 [caironoleto] + - Replace `tld_length` configuration option with PublicSuffix gem for the + subdomain elevator [humancopy] + - Pass full config to create_database to allow :encoding/:collation/etc + [kakipo] + - Don't retain a connection during initialization [mikecmpbll] + - Fix database name escaping in drop_command [mikecmpbll] + - Skip initialization for assets:clean and assets:precompile tasks + [frank-west-iii] + +# 1.2.0 + * July 28, 2016 + + - Official Rails 5 support + +# 1.1.0 + * May 26, 2016 + + - Reset tenant after each request + - [Support callbacks](https://github.com/influitive/apartment/commit/ff9c9d092a781026502f5997c0bbedcb5748bc83) on switch [cbeer] + - Preliminary support for [separate database hosts](https://github.com/influitive/apartment/commit/abdffbf8cd9fba87243f16c86390da13e318ee1f) [apneadiving] + +# 1.0.2 + * July 2, 2015 + + - Fix pg_dump env vars - pull/208 [MitinPavel] + - Allow custom seed data file - pull/234 [typeoneerror] + +# 1.0.1 + * April 28, 2015 + + - Fix `Apartment::Deprecation` which was rescuing all exceptions + +# 1.0.0 + * Feb 3, 2015 + + - [BREAKING CHANGE] `Apartment::Tenant.process` is deprecated in favour of `Apartment::Tenant.switch` + - [BREAKING CHANGE] `Apartment::Tenant.switch` without a block is deprecated in favour of `Apartment::Tenant.switch!` + - Raise proper `TenantNotFound`, `TenantExists` exceptions + - Deprecate old `SchemaNotFound`, `DatabaseNotFound` exceptions + +# 0.26.1 + * Jan 13, 2015 + + - Fixed [schema quoting bug](https://github.com/influitive/apartment/issues/198#issuecomment-69782651) [jonsgreen] + +# 0.26.0 + * Jan 5, 2015 + + - Rails 4.2 support + +# 0.25.2 + * Sept 8, 2014 + + - Heroku fix on `assets:precompile` - pull/169 [rabbitt] + +# 0.25.1 + * July 17, 2014 + + - Fixed a few vestiges of Apartment::Database + +# 0.25.0 + * July 3, 2014 + + - [BREAKING CHANGE] - `Apartment::Database` is not deprecated in favour of + `Apartment::Tenant` + - ActiveRecord (and Rails) 4.1 now supported + - A new sql based adapter that dumps the schema using sql + +# 0.24.3 + * March 5, 201 + - Rake Added weren't removed from the generator template + +# 0.24.2 + * February 24, 2014 + + - Better warnings if `apartment:migrate` is run + +# 0.24.1 + * February 21, 201 + - requiring `apartment/tasks/Added` in an initializer doesn't work + - One can disable tenant migrations using `Apartment.db_migrate_tenants = false` in the Rakefile + +# 0.24 + * February 21, 2014 (In honour of the Women's Gold Medal in Hockey at Sochi) + + - [BREAKING CHANGE] `apartment:migrate` task no long + - Instead, you can `require 'apartment/tasks/Added'` in your Apartment initializer + - This will enhance `rake db:migrate` to also run `apartment:migrate` + - You can now forget about ever running `apartment:migrate` again + - Numerous deprecations for things referencing the word 'database' + - This is an ongoing effort to completely replace 'database' with 'tenant' as a better abstraction + - Note the obvious `Apartment::Database` still exists but will hopefully become `Apartment::Tenant` soon + +# 0.23.2 + * January 9, 2014 + + - Increased visibility of #parse_database_name warning + +# 0.23.1 + * January 8, 2014 + + - Schema adapters now initialize with default and persistent schemas + - Deprecated Apartment::Elevators#parse_database_name + +# 0.23.0 + * August 21, 2013 + + - Subdomain Elevator now allows for exclusions + - Delayed::Job has been completely removed + +# 0.22.1 + * August 21, 2013 + + - Fix bug where if your ruby process importing the database schema is run + from a directory other than the app root, Apartment wouldn't know what + schema_migrations to insert into the database (Rails only) + +# 0.22.0 + * June 9, 2013 + + - Numerous bug fixes: + - Mysql reset could connect to wrong database [eric88] + - Postgresql schema names weren't quoted properly [gdott9] + - Fixed error message on SchemaNotFound in `process` + - HostHash elevator allows mapping host based on hash contents [gdott9] + - Official Sidekiq support with the [apartment-sidekiq gem](https://github.com/influitive/apartment-sidekiq) + + +# 0.21.1 + * May 31, 2013 + + - Clearing the AR::QueryCache after switching databases. + - Fixes issue with stale model being loaded for schema adapters + +# 0.21.0 + * April 24, 2013 + + - JDBC support!! [PetrolMan] + +# 0.20.0 + * Feb 6, 2013 + + - Mysql now has a 'schema like' option to perform like Postgresql (default) + - This should be significantly more performant than using connections + - Psych is now supported for Delayed::Job yaml parsing + +# 0.19.2 + * Jan 30, 2013 + + - Database schema file can now be set manually or skipped altogether + +# 0.19.1 + * Jan 30, 2013 + + - Allow schema.rb import file to be specified in config or skip schema.rb import altogether + +# 0.19.0 + * Dec 29, 2012 + + - Apartment is now threadsafe + - New postgis adapter [zonpantli] + - Removed ActionDispatch dependency for use with Rack apps (regression) + +# 0.18.0 + * Nov 27, 2012 + + - Added `append_environment` config option [virtualstaticvoid] + - Cleaned up the readme and generator documentation + - Added `connection_class` config option [smashtank] + - Fixed a [bug](https://github.com/influitive/apartment/issues/17#issuecomment-10758327) in pg adapter when missing schema + +# 0.17.1 + * Oct 30, 2012 + + - Fixed a bug where switching to an unknown db in mysql2 would crash the app [Frodotus] + +# 0.17.0 + * Sept 26, 2012 + + - Apartment has [a new home!](https://github.com/influitive/apartment) + - Support Sidekiq hooks to switch dbs [maedhr] + - Allow VERSION to be used on apartment:migrate [Bhavin Kamani] + +# 0.16.0 + * June 1, 2012 + + - Apartment now supports a default_schema to be set, rather than relying on ActiveRecord's default schema_search_path + - Additional schemas can always be maintained in the schema_search_path by configuring persistent_schemas [ryanbrunner] + - This means Hstore is officially supported!! + - There is now a full domain based elevator to switch dbs based on the whole domain [lcowell] + - There is now a generic elevator that takes a Proc to switch dbs based on the return value of that proc. + +# 0.15.0 + * March 18, 2012 + + - Remove Rails dependency, Apartment can now be used with any Rack based framework using ActiveRecord + +# 0.14.4 + * March 8, 2012 + + - Delayed::Job Hooks now return to the previous database, rather than resetting + +# 0.14.3 + * Feb 21, 2012 + + - Fix yaml serialization of non DJ models + +# 0.14.2 + * Feb 21, 2012 + + - Fix Delayed::Job yaml encoding with Rails > 3.0.x + +# 0.14.1 + * Dec 13, 2011 + + - Fix ActionDispatch::Callbacks deprecation warnings + +# 0.14.0 + * Dec 13, 2011 + + - Rails 3.1 Support + +# 0.13.1 + * Nov 8, 2011 + + - Reset prepared statement cache for rails 3.1.1 before switching dbs when using postgresql schemas + - Only necessary until the next release which will be more schema aware + +# 0.13.0 + * Oct 25, 2011 + + - `process` will now rescue with reset if the previous schema/db is no longer available + - `create` now takes an optional block which allows you to process within the newly created db + - Fixed Rails version >= 3.0.10 and < 3.1 because there have been significant testing problems with 3.1, next version will hopefully fix this + +# 0.12.0 + * Oct 4, 2011 + + - Added a `drop` method for removing databases/schemas + - Refactored abstract adapter to further remove duplication in concrete implementations + - Excluded models now take string references so they are properly reloaded in development + - Better silencing of `schema.rb` loading using `verbose` flag + +# 0.11.1 + * Sep 22, 2011 + + - Better use of Railties for initializing apartment + - The following changes were necessary as I haven't figured out how to properly hook into Rails reloading + - Added reloader middleware in development to init Apartment on each request + - Override `reload!` in console to also init Apartment + +# 0.11.0 + * Sep 20, 2011 + + - Excluded models no longer use a different connection when using postgresql schemas. Instead their table_name is prefixed with `public.` + +# 0.10.3 + * Sep 20, 2011 + + - Fix improper raising of exceptions on create and reset + +# 0.10.2 + * Sep 15, 2011 + + - Remove all the annoying logging for loading db schema and seeding on create + +# 0.10.1 + * Aug 11, 2011 + + - Fixed bug in DJ where new objects (that hadn't been pulled from the db) didn't have the proper database assigned + +# 0.10.0 + * July 29, 2011 + + - Added better support for Delayed Job + - New config option that enables Delayed Job wrappers + - Note that DJ support uses a work-around in order to get queues stored in the public schema, not sure why it doesn't work out of the box, will look into it, until then, see documentation on queue'ng jobs + +# 0.9.2 + * July 4, 2011 + + - Migrations now run associated rails migration fully, fixes schema.rb not being reloaded after migrations + +# 0.9.1 + * June 24, 2011 + + - Hooks now take the payload object as an argument to fetch the proper db for DJ hooks + +# 0.9.0 + * June 23, 2011 + + - Added module to provide delayed job hooks + +# 0.8.0 + * June 23, 2011 + + - Added #current_database which will return the current database (or schema) name + +# 0.7.0 + * June 22, 2011 + + - Added apartment:seed rake task for seeding all dbs + +# 0.6.0 + * June 21, 2011 + + - Added #process to connect to new db, perform operations, then ensure a reset + +# 0.5.1 + * June 21, 2011 + + - Fixed db migrate up/down/rollback + - added db:redo + +# 0.5.0 + * June 20, 2011 + + - Added the concept of an "Elevator", a rack based strategy for db switching + - Added the Subdomain Elevator middleware to enabled db switching based on subdomain + +# 0.4.0 + * June 14, 2011 + + - Added `configure` method on Apartment instead of using yml file, allows for dynamic setting of db names to migrate for rake task + - Added `seed_after_create` config option to import seed data to new db on create + +# 0.3.0 + * June 10, 2011 + + - Added full support for database migration + - Added in method to establish new connection for excluded models on startup rather than on each switch + +# 0.2.0 + * June 6, 2011 * + + - Refactor to use more rails/active_support functionality + - Refactor config to lazily load apartment.yml if exists + - Remove OStruct and just use hashes for fetching methods + - Added schema load on create instead of migrating from scratch + +# 0.1.3 + * March 30, 2011 * + + - Original pass from Ryan + + +\* *This Changelog was automatically generated by [github_changelog_generator](https://github.com/github-changelog-generator/github-changelog-generator)* From 49ab159851a87c7339c619fab3f6ecb7be3348f2 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 16:52:39 +0800 Subject: [PATCH 180/282] [#80] made history md compatible with changelog automation --- CHANGELOG.md | 191 +++++++++++++++++++++++++++++++-------------------- HISTORY.md | 185 ++++++++++++++++++++++++------------------------- 2 files changed, 209 insertions(+), 167 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 583563c0..3ef09db3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ - Error creating tenant with uuid column [\#85](https://github.com/rails-on-services/apartment/issues/85) - enhanced db:create task breaks plugins compatibility [\#82](https://github.com/rails-on-services/apartment/issues/82) +- Support disabling of full\_migration\_on\_create [\#30](https://github.com/rails-on-services/apartment/issues/30) + +**Merged pull requests:** + +- \[Resolves \#81\] check for var existence before [\#89](https://github.com/rails-on-services/apartment/pull/89) ([rpbaltazar](https://github.com/rpbaltazar)) ## [v2.7.1](https://github.com/rails-on-services/apartment/tree/v2.7.1) (2020-06-27) @@ -66,7 +71,6 @@ - \[\#52\] enhance after db create [\#54](https://github.com/rails-on-services/apartment/pull/54) ([rpbaltazar](https://github.com/rpbaltazar)) - fix init after reload on development [\#53](https://github.com/rails-on-services/apartment/pull/53) ([fsateler](https://github.com/fsateler)) - fix: reset sequence\_name after tenant switch [\#51](https://github.com/rails-on-services/apartment/pull/51) ([fsateler](https://github.com/fsateler)) -- Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) ## [v2.6.0](https://github.com/rails-on-services/apartment/tree/v2.6.0) (2020-05-14) @@ -110,9 +114,9 @@ - Prepare Release 2.5.0 [\#44](https://github.com/rails-on-services/apartment/pull/44) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] Added before hook to connected to to try to set the tenant [\#40](https://github.com/rails-on-services/apartment/pull/40) ([rpbaltazar](https://github.com/rpbaltazar)) +- Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) - \[Resolves \#35\] update cache key to use a string or an array [\#36](https://github.com/rails-on-services/apartment/pull/36) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Hotfix \#27\] Some errors were being thrown due to caching issues [\#33](https://github.com/rails-on-services/apartment/pull/33) ([rpbaltazar](https://github.com/rpbaltazar)) -- \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Chore\] refactored files to their names [\#29](https://github.com/rails-on-services/apartment/pull/29) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] When manually switching the connection it resets the search path [\#28](https://github.com/rails-on-services/apartment/pull/28) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -135,6 +139,7 @@ **Merged pull requests:** +- \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - Fix gemspec open versions and updated version [\#25](https://github.com/rails-on-services/apartment/pull/25) ([rpbaltazar](https://github.com/rpbaltazar)) - Fix gemspec open versions and updated version [\#24](https://github.com/rails-on-services/apartment/pull/24) ([rpbaltazar](https://github.com/rpbaltazar)) - Cleanup travis matrix [\#23](https://github.com/rails-on-services/apartment/pull/23) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -405,32 +410,45 @@ [Full Changelog](https://github.com/rails-on-services/apartment/compare/7100f34a185ab7d48947f06aa8c14f0cf0a68bb7...v0.1.3) -# 2.7.1 +# v2.7.1 +**Implemented enhancements:** - N/a +**Fixed bugs:** + - [Resolves #82] Enhanced db:create breaks plugin compatibility - +**Closed issues:** + - Update rake version in development - Renamed gemspec to match gem name -# 2.7.0 +# v2.7.0 +**Implemented enhancements:** - [Resolves #70] Rake tasks define methods on main - - Add database and schema to active record log. Configurable, defaults to false to keep current behavior - +**Fixed bugs:** + - [Fixes #61] Fix database create in mysql - +**Closed issues:** + - Remove deprecated tld_length config option: tld_length was removed in influitive#309, this configuration option doesn't have any effect now. - - Using [diffend.io proxy](https://diffend.io) to safely check required gems - Added [story branch](https://github.com/story-branch/story_branch) to the configuration - Using travis-ci to run rubocop as well, replacing github actions: github actions do not work in fork's PRs -# 2.6.1 +# v2.6.1 +**Implemented enhancements:** - N/a + +**Fixed bugs:** - [Resolves influitive#607] Avoid early connection - - @@ -438,69 +456,90 @@ - [Resolves #52] Rake db:setup tries to seed non existent tenant - - [Resolves #56] DB rollback uses second last migration - +#**Closed issues:** - N/a -# 2.6.0 +# v2.6.0 +**Implemented enhancements:** - [Resolves #26] Support configuration for skip checking of schema existence before switching - [Resolves #41] Add tenant info to console boot + +**Fixed bugs:** - [Resolves #37] Custom Console deprecation warning - [Resolves #42] After switch callback not working with nil argument +#**Closed issues:** - Updated github actions configuration to run on PRs as well -# 2.5.0 +# v2.5.0 +**Implemented enhancements:** - [Resolves #6] Adds support for rails 6.1 - [Resolves #27] Adds support to not rely on set search path, but instead prepends the schema name to the table name when using postgresql with schemas. - [Resolves #35] Cache keys are now tenant dependent + +**Fixed bugs:** - [Resolves #27] Manually switching connection between read and write forgets the schema +#**Closed issues:** - [Resolves #31] Add latest ruby versions to test matrix -# 2.4.0 +# v2.4.0 +**Implemented enhancements:** - [Resolves #14] Add console info about tenants and fast switches #17 - Skip init if we're running webpacker:compile #18 + +**Fixed bugs:** - Don't crash when no database connection is present #16 - Rescuing ActiveRecord::NoDatabaseError when dropping tenants #19 +#**Closed issues:** - Rakefile should use mysql port from configuration #5 - [Resolves #9] Cleanup rubocop todo #8 - Cleanup travis matrix #23 -# 2.3.0 +# v2.3.0 * January 3, 2020 +**Implemented enhancements:** - Basic support for rails 6 - Released different gem name, with same API as apartment -# 2.2.1 +# v2.2.1 * June 19, 2019 +**Implemented enhancements:** - #566: IGNORE_EMPTY_TENANTS environment variable to ignore empty tenants warning. [Pysis868] +**Fixed bugs:** - #586: Ignore `CREATE SCHEMA public` statement in pg dump [artemave] - #549: Fix Postgres schema creation with dump SQL [ancorcruz] -# 2.2.0 +# v2.2.0 * April 14, 2018 +**Implemented enhancements:** - #523: Add Rails 5.2 support [IngusSkaistkalns] - #504: Test against Ruby 2.5.0 [ahorek] - #528: Test against Rails 5.2 [meganemura] +**Removed:** - #504: Remove Rails 4.0/4.1 support [ahorek] - #545: Stop supporting for JRuby + Rails 5.0 [meganemura] +**Fixed bugs:** - #537: Fix PostgresqlSchemaFromSqlAdapter for newer PostgreSQL [shterrett] - #532: Issue is reported by [aldrinmartoq] - #519: Fix exception when main database doesn't exist [mayeco] +**Closed issues:** + - #514: Fix typo [menorval] -# 2.1.0 +# v2.1.0 * December 15, 2017 - Add `parallel_migration_threads` configuration option for running migrations @@ -512,7 +551,7 @@ - "Host" elevator [shrmnk] - Enhance db:drop task to act on all tenants [kuzukuzu] -# 2.0.0 +# v2.0.0 * July 26, 2017 - Raise FileNotFound rather than abort when loading files [meganemura] @@ -530,30 +569,30 @@ - Skip initialization for assets:clean and assets:precompile tasks [frank-west-iii] -# 1.2.0 +# v1.2.0 * July 28, 2016 - Official Rails 5 support -# 1.1.0 +# v1.1.0 * May 26, 2016 - Reset tenant after each request - [Support callbacks](https://github.com/influitive/apartment/commit/ff9c9d092a781026502f5997c0bbedcb5748bc83) on switch [cbeer] - Preliminary support for [separate database hosts](https://github.com/influitive/apartment/commit/abdffbf8cd9fba87243f16c86390da13e318ee1f) [apneadiving] -# 1.0.2 +# v1.0.2 * July 2, 2015 - Fix pg_dump env vars - pull/208 [MitinPavel] - Allow custom seed data file - pull/234 [typeoneerror] -# 1.0.1 +# v1.0.1 * April 28, 2015 - Fix `Apartment::Deprecation` which was rescuing all exceptions -# 1.0.0 +# v1.0.0 * Feb 3, 2015 - [BREAKING CHANGE] `Apartment::Tenant.process` is deprecated in favour of `Apartment::Tenant.switch` @@ -561,27 +600,27 @@ - Raise proper `TenantNotFound`, `TenantExists` exceptions - Deprecate old `SchemaNotFound`, `DatabaseNotFound` exceptions -# 0.26.1 +# v0.26.1 * Jan 13, 2015 - Fixed [schema quoting bug](https://github.com/influitive/apartment/issues/198#issuecomment-69782651) [jonsgreen] -# 0.26.0 +# v0.26.0 * Jan 5, 2015 - Rails 4.2 support -# 0.25.2 +# v0.25.2 * Sept 8, 2014 - Heroku fix on `assets:precompile` - pull/169 [rabbitt] -# 0.25.1 +# v0.25.1 * July 17, 2014 - Fixed a few vestiges of Apartment::Database -# 0.25.0 +# v0.25.0 * July 3, 2014 - [BREAKING CHANGE] - `Apartment::Database` is not deprecated in favour of @@ -589,56 +628,58 @@ - ActiveRecord (and Rails) 4.1 now supported - A new sql based adapter that dumps the schema using sql -# 0.24.3 - * March 5, 201 - - Rake Added weren't removed from the generator template +# v0.24.3 + * March 5, 2014 -# 0.24.2 + - Rake enhancements weren't removed from the generator template + +# v0.24.2 * February 24, 2014 - Better warnings if `apartment:migrate` is run -# 0.24.1 - * February 21, 201 - - requiring `apartment/tasks/Added` in an initializer doesn't work +# v0.24.1 + * February 21, 2014 + + - requiring `apartment/tasks/enhancements` in an initializer doesn't work - One can disable tenant migrations using `Apartment.db_migrate_tenants = false` in the Rakefile -# 0.24 +# v0.24 * February 21, 2014 (In honour of the Women's Gold Medal in Hockey at Sochi) - - [BREAKING CHANGE] `apartment:migrate` task no long - - Instead, you can `require 'apartment/tasks/Added'` in your Apartment initializer + - [BREAKING CHANGE] `apartment:migrate` task no longer depends on `db:migrate` + - Instead, you can `require 'apartment/tasks/enhancements'` in your Apartment initializer - This will enhance `rake db:migrate` to also run `apartment:migrate` - You can now forget about ever running `apartment:migrate` again - Numerous deprecations for things referencing the word 'database' - This is an ongoing effort to completely replace 'database' with 'tenant' as a better abstraction - Note the obvious `Apartment::Database` still exists but will hopefully become `Apartment::Tenant` soon -# 0.23.2 +# v0.23.2 * January 9, 2014 - Increased visibility of #parse_database_name warning -# 0.23.1 +# v0.23.1 * January 8, 2014 - Schema adapters now initialize with default and persistent schemas - Deprecated Apartment::Elevators#parse_database_name -# 0.23.0 +# v0.23.0 * August 21, 2013 - Subdomain Elevator now allows for exclusions - Delayed::Job has been completely removed -# 0.22.1 +# v0.22.1 * August 21, 2013 - Fix bug where if your ruby process importing the database schema is run from a directory other than the app root, Apartment wouldn't know what schema_migrations to insert into the database (Rails only) -# 0.22.0 +# v0.22.0 * June 9, 2013 - Numerous bug fixes: @@ -649,42 +690,42 @@ - Official Sidekiq support with the [apartment-sidekiq gem](https://github.com/influitive/apartment-sidekiq) -# 0.21.1 +# v0.21.1 * May 31, 2013 - Clearing the AR::QueryCache after switching databases. - Fixes issue with stale model being loaded for schema adapters -# 0.21.0 +# v0.21.0 * April 24, 2013 - JDBC support!! [PetrolMan] -# 0.20.0 +# v0.20.0 * Feb 6, 2013 - Mysql now has a 'schema like' option to perform like Postgresql (default) - This should be significantly more performant than using connections - Psych is now supported for Delayed::Job yaml parsing -# 0.19.2 +# v0.19.2 * Jan 30, 2013 - Database schema file can now be set manually or skipped altogether -# 0.19.1 +# v0.19.1 * Jan 30, 2013 - Allow schema.rb import file to be specified in config or skip schema.rb import altogether -# 0.19.0 +# v0.19.0 * Dec 29, 2012 - Apartment is now threadsafe - New postgis adapter [zonpantli] - Removed ActionDispatch dependency for use with Rack apps (regression) -# 0.18.0 +# v0.18.0 * Nov 27, 2012 - Added `append_environment` config option [virtualstaticvoid] @@ -692,19 +733,19 @@ - Added `connection_class` config option [smashtank] - Fixed a [bug](https://github.com/influitive/apartment/issues/17#issuecomment-10758327) in pg adapter when missing schema -# 0.17.1 +# v0.17.1 * Oct 30, 2012 - Fixed a bug where switching to an unknown db in mysql2 would crash the app [Frodotus] -# 0.17.0 +# v0.17.0 * Sept 26, 2012 - Apartment has [a new home!](https://github.com/influitive/apartment) - Support Sidekiq hooks to switch dbs [maedhr] - Allow VERSION to be used on apartment:migrate [Bhavin Kamani] -# 0.16.0 +# v0.16.0 * June 1, 2012 - Apartment now supports a default_schema to be set, rather than relying on ActiveRecord's default schema_search_path @@ -713,50 +754,50 @@ - There is now a full domain based elevator to switch dbs based on the whole domain [lcowell] - There is now a generic elevator that takes a Proc to switch dbs based on the return value of that proc. -# 0.15.0 +# v0.15.0 * March 18, 2012 - Remove Rails dependency, Apartment can now be used with any Rack based framework using ActiveRecord -# 0.14.4 +# v0.14.4 * March 8, 2012 - Delayed::Job Hooks now return to the previous database, rather than resetting -# 0.14.3 +# v0.14.3 * Feb 21, 2012 - Fix yaml serialization of non DJ models -# 0.14.2 +# v0.14.2 * Feb 21, 2012 - Fix Delayed::Job yaml encoding with Rails > 3.0.x -# 0.14.1 +# v0.14.1 * Dec 13, 2011 - Fix ActionDispatch::Callbacks deprecation warnings -# 0.14.0 +# v0.14.0 * Dec 13, 2011 - Rails 3.1 Support -# 0.13.1 +# v0.13.1 * Nov 8, 2011 - Reset prepared statement cache for rails 3.1.1 before switching dbs when using postgresql schemas - Only necessary until the next release which will be more schema aware -# 0.13.0 +# v0.13.0 * Oct 25, 2011 - `process` will now rescue with reset if the previous schema/db is no longer available - `create` now takes an optional block which allows you to process within the newly created db - Fixed Rails version >= 3.0.10 and < 3.1 because there have been significant testing problems with 3.1, next version will hopefully fix this -# 0.12.0 +# v0.12.0 * Oct 4, 2011 - Added a `drop` method for removing databases/schemas @@ -764,7 +805,7 @@ - Excluded models now take string references so they are properly reloaded in development - Better silencing of `schema.rb` loading using `verbose` flag -# 0.11.1 +# v0.11.1 * Sep 22, 2011 - Better use of Railties for initializing apartment @@ -772,88 +813,88 @@ - Added reloader middleware in development to init Apartment on each request - Override `reload!` in console to also init Apartment -# 0.11.0 +# v0.11.0 * Sep 20, 2011 - Excluded models no longer use a different connection when using postgresql schemas. Instead their table_name is prefixed with `public.` -# 0.10.3 +# v0.10.3 * Sep 20, 2011 - Fix improper raising of exceptions on create and reset -# 0.10.2 +# v0.10.2 * Sep 15, 2011 - Remove all the annoying logging for loading db schema and seeding on create -# 0.10.1 +# v0.10.1 * Aug 11, 2011 - Fixed bug in DJ where new objects (that hadn't been pulled from the db) didn't have the proper database assigned -# 0.10.0 +# v0.10.0 * July 29, 2011 - Added better support for Delayed Job - New config option that enables Delayed Job wrappers - Note that DJ support uses a work-around in order to get queues stored in the public schema, not sure why it doesn't work out of the box, will look into it, until then, see documentation on queue'ng jobs -# 0.9.2 +# v0.9.2 * July 4, 2011 - Migrations now run associated rails migration fully, fixes schema.rb not being reloaded after migrations -# 0.9.1 +# v0.9.1 * June 24, 2011 - Hooks now take the payload object as an argument to fetch the proper db for DJ hooks -# 0.9.0 +# v0.9.0 * June 23, 2011 - Added module to provide delayed job hooks -# 0.8.0 +# v0.8.0 * June 23, 2011 - Added #current_database which will return the current database (or schema) name -# 0.7.0 +# v0.7.0 * June 22, 2011 - Added apartment:seed rake task for seeding all dbs -# 0.6.0 +# v0.6.0 * June 21, 2011 - Added #process to connect to new db, perform operations, then ensure a reset -# 0.5.1 +# v0.5.1 * June 21, 2011 - Fixed db migrate up/down/rollback - added db:redo -# 0.5.0 +# v0.5.0 * June 20, 2011 - Added the concept of an "Elevator", a rack based strategy for db switching - Added the Subdomain Elevator middleware to enabled db switching based on subdomain -# 0.4.0 +# v0.4.0 * June 14, 2011 - Added `configure` method on Apartment instead of using yml file, allows for dynamic setting of db names to migrate for rake task - Added `seed_after_create` config option to import seed data to new db on create -# 0.3.0 +# v0.3.0 * June 10, 2011 - Added full support for database migration - Added in method to establish new connection for excluded models on startup rather than on each switch -# 0.2.0 +# v0.2.0 * June 6, 2011 * - Refactor to use more rails/active_support functionality @@ -861,7 +902,7 @@ - Remove OStruct and just use hashes for fetching methods - Added schema load on create instead of migrating from scratch -# 0.1.3 +# v0.1.3 * March 30, 2011 * - Original pass from Ryan diff --git a/HISTORY.md b/HISTORY.md index 43165b28..0167efa5 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,42 +1,42 @@ -# 2.7.1 +# v2.7.1 -# Enhancements +**Implemented enhancements:** - N/a -# Bugfixes +**Fixed bugs:** - [Resolves #82] Enhanced db:create breaks plugin compatibility - -# Chores +**Closed issues:** - Update rake version in development - Renamed gemspec to match gem name -# 2.7.0 +# v2.7.0 -# Enhancements +**Implemented enhancements:** - [Resolves #70] Rake tasks define methods on main - - Add database and schema to active record log. Configurable, defaults to false to keep current behavior - -# Bugfixes +**Fixed bugs:** - [Fixes #61] Fix database create in mysql - -# Chores +**Closed issues:** - Remove deprecated tld_length config option: tld_length was removed in influitive#309, this configuration option doesn't have any effect now. - - Using [diffend.io proxy](https://diffend.io) to safely check required gems - Added [story branch](https://github.com/story-branch/story_branch) to the configuration - Using travis-ci to run rubocop as well, replacing github actions: github actions do not work in fork's PRs -# 2.6.1 +# v2.6.1 -## Enhancements +**Implemented enhancements:** - N/a -## Bugfixes +**Fixed bugs:** - [Resolves influitive#607] Avoid early connection - - @@ -44,89 +44,90 @@ - [Resolves #52] Rake db:setup tries to seed non existent tenant - - [Resolves #56] DB rollback uses second last migration - -## Chores +#**Closed issues:** - N/a -# 2.6.0 +# v2.6.0 -## Enhancements +**Implemented enhancements:** - [Resolves #26] Support configuration for skip checking of schema existence before switching - [Resolves #41] Add tenant info to console boot -## Bugfixes +**Fixed bugs:** - [Resolves #37] Custom Console deprecation warning - [Resolves #42] After switch callback not working with nil argument -## Chores +#**Closed issues:** - Updated github actions configuration to run on PRs as well -# 2.5.0 +# v2.5.0 -## Enhancements +**Implemented enhancements:** - [Resolves #6] Adds support for rails 6.1 - [Resolves #27] Adds support to not rely on set search path, but instead prepends the schema name to the table name when using postgresql with schemas. - [Resolves #35] Cache keys are now tenant dependent -## Bugfixes +**Fixed bugs:** - [Resolves #27] Manually switching connection between read and write forgets the schema -## Chores +#**Closed issues:** - [Resolves #31] Add latest ruby versions to test matrix -# 2.4.0 +# v2.4.0 -## Enhancements +**Implemented enhancements:** - [Resolves #14] Add console info about tenants and fast switches #17 - Skip init if we're running webpacker:compile #18 -## Bugfixes +**Fixed bugs:** - Don't crash when no database connection is present #16 - Rescuing ActiveRecord::NoDatabaseError when dropping tenants #19 -## Chores +#**Closed issues:** - Rakefile should use mysql port from configuration #5 - [Resolves #9] Cleanup rubocop todo #8 - Cleanup travis matrix #23 -# 2.3.0 +# v2.3.0 * January 3, 2020 -## Added +**Implemented enhancements:** - Basic support for rails 6 - Released different gem name, with same API as apartment -# 2.2.1 +# v2.2.1 * June 19, 2019 -## Added +**Implemented enhancements:** - #566: IGNORE_EMPTY_TENANTS environment variable to ignore empty tenants warning. [Pysis868] -## Fixed +**Fixed bugs:** - #586: Ignore `CREATE SCHEMA public` statement in pg dump [artemave] - #549: Fix Postgres schema creation with dump SQL [ancorcruz] -# 2.2.0 +# v2.2.0 * April 14, 2018 -## Added +**Implemented enhancements:** - #523: Add Rails 5.2 support [IngusSkaistkalns] - #504: Test against Ruby 2.5.0 [ahorek] - #528: Test against Rails 5.2 [meganemura] -## Removed +**Removed:** - #504: Remove Rails 4.0/4.1 support [ahorek] - #545: Stop supporting for JRuby + Rails 5.0 [meganemura] -## Fixed +**Fixed bugs:** - #537: Fix PostgresqlSchemaFromSqlAdapter for newer PostgreSQL [shterrett] - #532: Issue is reported by [aldrinmartoq] - #519: Fix exception when main database doesn't exist [mayeco] -## Changed +**Closed issues:** + - #514: Fix typo [menorval] -# 2.1.0 +# v2.1.0 * December 15, 2017 - Add `parallel_migration_threads` configuration option for running migrations @@ -138,7 +139,7 @@ - "Host" elevator [shrmnk] - Enhance db:drop task to act on all tenants [kuzukuzu] -# 2.0.0 +# v2.0.0 * July 26, 2017 - Raise FileNotFound rather than abort when loading files [meganemura] @@ -156,30 +157,30 @@ - Skip initialization for assets:clean and assets:precompile tasks [frank-west-iii] -# 1.2.0 +# v1.2.0 * July 28, 2016 - Official Rails 5 support -# 1.1.0 +# v1.1.0 * May 26, 2016 - Reset tenant after each request - [Support callbacks](https://github.com/influitive/apartment/commit/ff9c9d092a781026502f5997c0bbedcb5748bc83) on switch [cbeer] - Preliminary support for [separate database hosts](https://github.com/influitive/apartment/commit/abdffbf8cd9fba87243f16c86390da13e318ee1f) [apneadiving] -# 1.0.2 +# v1.0.2 * July 2, 2015 - Fix pg_dump env vars - pull/208 [MitinPavel] - Allow custom seed data file - pull/234 [typeoneerror] -# 1.0.1 +# v1.0.1 * April 28, 2015 - Fix `Apartment::Deprecation` which was rescuing all exceptions -# 1.0.0 +# v1.0.0 * Feb 3, 2015 - [BREAKING CHANGE] `Apartment::Tenant.process` is deprecated in favour of `Apartment::Tenant.switch` @@ -187,27 +188,27 @@ - Raise proper `TenantNotFound`, `TenantExists` exceptions - Deprecate old `SchemaNotFound`, `DatabaseNotFound` exceptions -# 0.26.1 +# v0.26.1 * Jan 13, 2015 - Fixed [schema quoting bug](https://github.com/influitive/apartment/issues/198#issuecomment-69782651) [jonsgreen] -# 0.26.0 +# v0.26.0 * Jan 5, 2015 - Rails 4.2 support -# 0.25.2 +# v0.25.2 * Sept 8, 2014 - Heroku fix on `assets:precompile` - pull/169 [rabbitt] -# 0.25.1 +# v0.25.1 * July 17, 2014 - Fixed a few vestiges of Apartment::Database -# 0.25.0 +# v0.25.0 * July 3, 2014 - [BREAKING CHANGE] - `Apartment::Database` is not deprecated in favour of @@ -215,23 +216,23 @@ - ActiveRecord (and Rails) 4.1 now supported - A new sql based adapter that dumps the schema using sql -# 0.24.3 +# v0.24.3 * March 5, 2014 - Rake enhancements weren't removed from the generator template -# 0.24.2 +# v0.24.2 * February 24, 2014 - Better warnings if `apartment:migrate` is run -# 0.24.1 +# v0.24.1 * February 21, 2014 - requiring `apartment/tasks/enhancements` in an initializer doesn't work - One can disable tenant migrations using `Apartment.db_migrate_tenants = false` in the Rakefile -# 0.24 +# v0.24 * February 21, 2014 (In honour of the Women's Gold Medal in Hockey at Sochi) - [BREAKING CHANGE] `apartment:migrate` task no longer depends on `db:migrate` @@ -242,31 +243,31 @@ - This is an ongoing effort to completely replace 'database' with 'tenant' as a better abstraction - Note the obvious `Apartment::Database` still exists but will hopefully become `Apartment::Tenant` soon -# 0.23.2 +# v0.23.2 * January 9, 2014 - Increased visibility of #parse_database_name warning -# 0.23.1 +# v0.23.1 * January 8, 2014 - Schema adapters now initialize with default and persistent schemas - Deprecated Apartment::Elevators#parse_database_name -# 0.23.0 +# v0.23.0 * August 21, 2013 - Subdomain Elevator now allows for exclusions - Delayed::Job has been completely removed -# 0.22.1 +# v0.22.1 * August 21, 2013 - Fix bug where if your ruby process importing the database schema is run from a directory other than the app root, Apartment wouldn't know what schema_migrations to insert into the database (Rails only) -# 0.22.0 +# v0.22.0 * June 9, 2013 - Numerous bug fixes: @@ -277,42 +278,42 @@ - Official Sidekiq support with the [apartment-sidekiq gem](https://github.com/influitive/apartment-sidekiq) -# 0.21.1 +# v0.21.1 * May 31, 2013 - Clearing the AR::QueryCache after switching databases. - Fixes issue with stale model being loaded for schema adapters -# 0.21.0 +# v0.21.0 * April 24, 2013 - JDBC support!! [PetrolMan] -# 0.20.0 +# v0.20.0 * Feb 6, 2013 - Mysql now has a 'schema like' option to perform like Postgresql (default) - This should be significantly more performant than using connections - Psych is now supported for Delayed::Job yaml parsing -# 0.19.2 +# v0.19.2 * Jan 30, 2013 - Database schema file can now be set manually or skipped altogether -# 0.19.1 +# v0.19.1 * Jan 30, 2013 - Allow schema.rb import file to be specified in config or skip schema.rb import altogether -# 0.19.0 +# v0.19.0 * Dec 29, 2012 - Apartment is now threadsafe - New postgis adapter [zonpantli] - Removed ActionDispatch dependency for use with Rack apps (regression) -# 0.18.0 +# v0.18.0 * Nov 27, 2012 - Added `append_environment` config option [virtualstaticvoid] @@ -320,19 +321,19 @@ - Added `connection_class` config option [smashtank] - Fixed a [bug](https://github.com/influitive/apartment/issues/17#issuecomment-10758327) in pg adapter when missing schema -# 0.17.1 +# v0.17.1 * Oct 30, 2012 - Fixed a bug where switching to an unknown db in mysql2 would crash the app [Frodotus] -# 0.17.0 +# v0.17.0 * Sept 26, 2012 - Apartment has [a new home!](https://github.com/influitive/apartment) - Support Sidekiq hooks to switch dbs [maedhr] - Allow VERSION to be used on apartment:migrate [Bhavin Kamani] -# 0.16.0 +# v0.16.0 * June 1, 2012 - Apartment now supports a default_schema to be set, rather than relying on ActiveRecord's default schema_search_path @@ -341,50 +342,50 @@ - There is now a full domain based elevator to switch dbs based on the whole domain [lcowell] - There is now a generic elevator that takes a Proc to switch dbs based on the return value of that proc. -# 0.15.0 +# v0.15.0 * March 18, 2012 - Remove Rails dependency, Apartment can now be used with any Rack based framework using ActiveRecord -# 0.14.4 +# v0.14.4 * March 8, 2012 - Delayed::Job Hooks now return to the previous database, rather than resetting -# 0.14.3 +# v0.14.3 * Feb 21, 2012 - Fix yaml serialization of non DJ models -# 0.14.2 +# v0.14.2 * Feb 21, 2012 - Fix Delayed::Job yaml encoding with Rails > 3.0.x -# 0.14.1 +# v0.14.1 * Dec 13, 2011 - Fix ActionDispatch::Callbacks deprecation warnings -# 0.14.0 +# v0.14.0 * Dec 13, 2011 - Rails 3.1 Support -# 0.13.1 +# v0.13.1 * Nov 8, 2011 - Reset prepared statement cache for rails 3.1.1 before switching dbs when using postgresql schemas - Only necessary until the next release which will be more schema aware -# 0.13.0 +# v0.13.0 * Oct 25, 2011 - `process` will now rescue with reset if the previous schema/db is no longer available - `create` now takes an optional block which allows you to process within the newly created db - Fixed Rails version >= 3.0.10 and < 3.1 because there have been significant testing problems with 3.1, next version will hopefully fix this -# 0.12.0 +# v0.12.0 * Oct 4, 2011 - Added a `drop` method for removing databases/schemas @@ -392,7 +393,7 @@ - Excluded models now take string references so they are properly reloaded in development - Better silencing of `schema.rb` loading using `verbose` flag -# 0.11.1 +# v0.11.1 * Sep 22, 2011 - Better use of Railties for initializing apartment @@ -400,88 +401,88 @@ - Added reloader middleware in development to init Apartment on each request - Override `reload!` in console to also init Apartment -# 0.11.0 +# v0.11.0 * Sep 20, 2011 - Excluded models no longer use a different connection when using postgresql schemas. Instead their table_name is prefixed with `public.` -# 0.10.3 +# v0.10.3 * Sep 20, 2011 - Fix improper raising of exceptions on create and reset -# 0.10.2 +# v0.10.2 * Sep 15, 2011 - Remove all the annoying logging for loading db schema and seeding on create -# 0.10.1 +# v0.10.1 * Aug 11, 2011 - Fixed bug in DJ where new objects (that hadn't been pulled from the db) didn't have the proper database assigned -# 0.10.0 +# v0.10.0 * July 29, 2011 - Added better support for Delayed Job - New config option that enables Delayed Job wrappers - Note that DJ support uses a work-around in order to get queues stored in the public schema, not sure why it doesn't work out of the box, will look into it, until then, see documentation on queue'ng jobs -# 0.9.2 +# v0.9.2 * July 4, 2011 - Migrations now run associated rails migration fully, fixes schema.rb not being reloaded after migrations -# 0.9.1 +# v0.9.1 * June 24, 2011 - Hooks now take the payload object as an argument to fetch the proper db for DJ hooks -# 0.9.0 +# v0.9.0 * June 23, 2011 - Added module to provide delayed job hooks -# 0.8.0 +# v0.8.0 * June 23, 2011 - Added #current_database which will return the current database (or schema) name -# 0.7.0 +# v0.7.0 * June 22, 2011 - Added apartment:seed rake task for seeding all dbs -# 0.6.0 +# v0.6.0 * June 21, 2011 - Added #process to connect to new db, perform operations, then ensure a reset -# 0.5.1 +# v0.5.1 * June 21, 2011 - Fixed db migrate up/down/rollback - added db:redo -# 0.5.0 +# v0.5.0 * June 20, 2011 - Added the concept of an "Elevator", a rack based strategy for db switching - Added the Subdomain Elevator middleware to enabled db switching based on subdomain -# 0.4.0 +# v0.4.0 * June 14, 2011 - Added `configure` method on Apartment instead of using yml file, allows for dynamic setting of db names to migrate for rake task - Added `seed_after_create` config option to import seed data to new db on create -# 0.3.0 +# v0.3.0 * June 10, 2011 - Added full support for database migration - Added in method to establish new connection for excluded models on startup rather than on each switch -# 0.2.0 +# v0.2.0 * June 6, 2011 * - Refactor to use more rails/active_support functionality @@ -489,7 +490,7 @@ - Remove OStruct and just use hashes for fetching methods - Added schema load on create instead of migrating from scratch -# 0.1.3 +# v0.1.3 * March 30, 2011 * - Original pass from Ryan From c05abbdf140aece95905c6f2d64404cf84cd8ebf Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 11:47:48 +0800 Subject: [PATCH 181/282] using official rubocop version and ran auto-correct --- .rubocop.yml | 6 ---- .rubocop_todo.yml | 29 ------------------- Gemfile | 2 +- Rakefile | 8 +++-- lib/apartment.rb | 8 +++-- .../active_record/internal_metadata.rb | 2 -- lib/apartment/active_record/log_subscriber.rb | 4 ++- .../active_record/schema_migration.rb | 2 -- lib/apartment/adapters/abstract_adapter.rb | 8 +++-- .../adapters/jdbc_postgresql_adapter.rb | 4 ++- lib/apartment/adapters/postgresql_adapter.rb | 12 ++++++-- lib/apartment/console.rb | 10 ++----- lib/apartment/custom_console.rb | 2 -- lib/apartment/tasks/task_helper.rb | 2 -- lib/apartment/tenant.rb | 4 ++- spec/adapters/postgresql_adapter_spec.rb | 6 +++- 16 files changed, 44 insertions(+), 65 deletions(-) delete mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 2c505894..4d999ea2 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,9 +1,3 @@ -inherit_from: .rubocop_todo.yml - -inherit_gem: - perx-rubocop: - - default.yml - AllCops: Exclude: - 'gemfiles/**/*.gemfile' diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index dd9305f8..00000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,29 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config` -# on 2020-02-16 15:36:55 +0800 using RuboCop version 0.77.0. -# The point is for the user to remove these configuration records -# one by one as the offenses are removed from the code base. -# Note that changes in the inspected code, or installation of new -# versions of RuboCop, may require this file to be generated again. - -# Offense count: 5 -Metrics/AbcSize: - Max: 33 - -# Offense count: 11 -# Configuration parameters: CountComments, ExcludedMethods. -# ExcludedMethods: refine -Metrics/BlockLength: - Max: 176 - -# Offense count: 18 -# Cop supports --auto-correct. -# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. -# URISchemes: http, https -Metrics/LineLength: - Max: 200 - -# Offense count: 4 -# Configuration parameters: CountComments, ExcludedMethods. -Metrics/MethodLength: - Max: 24 diff --git a/Gemfile b/Gemfile index c17fcbee..fa74281e 100644 --- a/Gemfile +++ b/Gemfile @@ -4,8 +4,8 @@ source 'https://my.diffend.io/protect/gems' gemspec -gem 'perx-rubocop', '~> 0.0.3' gem 'rails', '>= 3.1.2' +gem 'rubocop' group :local do gem 'guard-rspec', '~> 4.2' diff --git a/Rakefile b/Rakefile index 735d192c..59c5fbc9 100644 --- a/Rakefile +++ b/Rakefile @@ -46,8 +46,12 @@ namespace :db do apartment_db_file = 'spec/config/database.yml' rails_db_file = 'spec/dummy/config/database.yml' - FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, verbose: true) unless File.exist?(apartment_db_file) - FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) unless File.exist?(rails_db_file) + unless File.exist?(apartment_db_file) + FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, verbose: true) + end + unless File.exist?(rails_db_file) + FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) + end end end diff --git a/lib/apartment.rb b/lib/apartment.rb index b0371297..c04b0cc7 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -9,7 +9,9 @@ # require_relative 'apartment/arel/visitors/postgresql' require_relative 'apartment/active_record/log_subscriber' -require_relative 'apartment/active_record/connection_handling' if ActiveRecord.version.release >= Gem::Version.new('6.0') +if ActiveRecord.version.release >= Gem::Version.new('6.0') + require_relative 'apartment/active_record/connection_handling' +end if ActiveRecord.version.release >= Gem::Version.new('6.1') require_relative 'apartment/active_record/schema_migration' @@ -106,7 +108,9 @@ def pg_excluded_names # Reset all the config for Apartment def reset (ACCESSOR_METHODS + WRITER_METHODS).each do |method| - remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") + if instance_variable_defined?(:"@#{method}") + remove_instance_variable(:"@#{method}") + end end end diff --git a/lib/apartment/active_record/internal_metadata.rb b/lib/apartment/active_record/internal_metadata.rb index 2c494990..4febd0cf 100644 --- a/lib/apartment/active_record/internal_metadata.rb +++ b/lib/apartment/active_record/internal_metadata.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -# rubocop:disable Rails/ApplicationRecord class InternalMetadata < ActiveRecord::Base # :nodoc: class << self def table_exists? @@ -8,4 +7,3 @@ def table_exists? end end end -# rubocop:enable Rails/ApplicationRecord diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb index ca090264..a0e4bea5 100644 --- a/lib/apartment/active_record/log_subscriber.rb +++ b/lib/apartment/active_record/log_subscriber.rb @@ -7,7 +7,9 @@ def apartment_log database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) schema = nil - schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", ActiveSupport::LogSubscriber::YELLOW, true) unless Apartment.connection.schema_search_path.nil? + unless Apartment.connection.schema_search_path.nil? + schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", ActiveSupport::LogSubscriber::YELLOW, true) + end "#{database}#{schema}" end diff --git a/lib/apartment/active_record/schema_migration.rb b/lib/apartment/active_record/schema_migration.rb index 7bc07360..cbad3648 100644 --- a/lib/apartment/active_record/schema_migration.rb +++ b/lib/apartment/active_record/schema_migration.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true module ActiveRecord - # rubocop:disable Rails/ApplicationRecord class SchemaMigration < ActiveRecord::Base # :nodoc: class << self def table_exists? @@ -9,5 +8,4 @@ def table_exists? end end end - # rubocop:enable Rails/ApplicationRecord end diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ce18f396..544e58b6 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -123,7 +123,9 @@ def reset # def seed_data # Don't log the output of seeding the db - silence_warnings { load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file + if Apartment.seed_data_file + silence_warnings { load_or_raise(Apartment.seed_data_file) } + end end alias seed seed_data @@ -194,7 +196,9 @@ def connect_to_new(tenant) def import_database_schema ActiveRecord::Schema.verbose = false # do not log schema load output. - load_or_raise(Apartment.database_schema_file) if Apartment.database_schema_file + if Apartment.database_schema_file + load_or_raise(Apartment.database_schema_file) + end end # Return a new config that is multi-tenanted diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 16113b27..f9477fd0 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -39,7 +39,9 @@ def connect_to_new(tenant = nil) return reset if tenant.nil? tenant = tenant.to_s - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) + unless tenant_exists?(tenant) + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" + end @current = tenant Apartment.connection.schema_search_path = full_search_path diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index a2ca1163..9d3f7a4a 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -7,7 +7,9 @@ module Tenant def self.postgresql_adapter(config) adapter = Adapters::PostgresqlAdapter adapter = Adapters::PostgresqlSchemaAdapter if Apartment.use_schemas - adapter = Adapters::PostgresqlSchemaFromSqlAdapter if Apartment.use_sql && Apartment.use_schemas + if Apartment.use_sql && Apartment.use_schemas + adapter = Adapters::PostgresqlSchemaFromSqlAdapter + end adapter.new(config) end end @@ -74,7 +76,9 @@ def connect_to_new(tenant = nil) return reset if tenant.nil? tenant = tenant.to_s - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) + unless tenant_exists?(tenant) + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" + end @current = tenant Apartment.connection.schema_search_path = full_search_path @@ -127,7 +131,9 @@ def reset_sequence_names .each do |c| # NOTE: due to this https://github.com/rails-on-services/apartment/issues/81 # unreproduceable error we're checking before trying to remove it - c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) + if c.instance_variable_defined?(:@sequence_name) + c.remove_instance_variable :@sequence_name + end end end end diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 7fcb1d61..1398fe72 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -5,9 +5,7 @@ # reloads the environment def reload!(print = true) - # rubocop:disable Rails/Output puts 'Reloading...' if print - # rubocop:enable Rails/Output # This triggers the to_prepare callbacks ActionDispatch::Callbacks.new(proc {}).call({}) @@ -18,15 +16,13 @@ def reload!(print = true) def st(schema_name = nil) if schema_name.nil? - # rubocop:disable Rails/Output tenant_list.each { |t| puts t } - # rubocop:enable Rails/Output + elsif tenant_list.include? schema_name Apartment::Tenant.switch!(schema_name) else - # rubocop:disable Rails/Output puts "Tenant #{schema_name} is not part of the tenant list" - # rubocop:enable Rails/Output + end end @@ -37,8 +33,6 @@ def tenant_list end def tenant_info_msg - # rubocop:disable Rails/Output puts "Available Tenants: #{tenant_list}\n" puts "Use `st 'tenant'` to switch tenants & `tenant_list` to see list\n" - # rubocop:enable Rails/Output end diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index eae9f4bb..bc3d0902 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -7,9 +7,7 @@ module CustomConsole begin require 'pry-rails' rescue LoadError - # rubocop:disable Rails/Output puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' - # rubocop:enable Rails/Output end desc = "Includes the current Rails environment and project folder name.\n" \ diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index aefa8dd4..84257b9a 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -19,7 +19,6 @@ def self.tenants def self.warn_if_tenants_empty return unless tenants.empty? && ENV['IGNORE_EMPTY_TENANTS'] != 'true' - # rubocop:disable Rails/Output puts <<-WARNING [WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things: @@ -29,7 +28,6 @@ def self.warn_if_tenants_empty Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. WARNING - # rubocop:enable Rails/Output end end end diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 17560b27..72a222ff 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -51,7 +51,9 @@ def adapter raise "The adapter `#{adapter_method}` is not yet supported" end - raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter" unless respond_to?(adapter_method) + unless respond_to?(adapter_method) + raise AdapterNotFound, "database configuration specifies nonexistent #{config[:adapter]} adapter" + end send(adapter_method, config) end diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index 71366c59..a32e9ccf 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -44,7 +44,11 @@ def tenant_names expect { Apartment::Tenant.create('has-dashes') }.to_not raise_error end - after { Apartment::Tenant.drop('has-dashes') if Apartment.connection.schema_exists? 'has-dashes' } + after do + if Apartment.connection.schema_exists? 'has-dashes' + Apartment::Tenant.drop('has-dashes') + end + end end context 'using connections' do From 53eae0496b88bf4fb886bb030a4d5452abf99d24 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 11:50:37 +0800 Subject: [PATCH 182/282] updated rubocop version --- Rakefile | 4 +--- lib/apartment.rb | 4 +--- lib/apartment/adapters/abstract_adapter.rb | 8 ++------ lib/apartment/adapters/jdbc_postgresql_adapter.rb | 4 +--- lib/apartment/adapters/postgresql_adapter.rb | 12 +++--------- spec/adapters/postgresql_adapter_spec.rb | 4 +--- spec/dummy/config.ru | 2 +- spec/dummy_engine/test/dummy/config.ru | 2 +- 8 files changed, 11 insertions(+), 29 deletions(-) diff --git a/Rakefile b/Rakefile index 59c5fbc9..948bd059 100644 --- a/Rakefile +++ b/Rakefile @@ -49,9 +49,7 @@ namespace :db do unless File.exist?(apartment_db_file) FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, verbose: true) end - unless File.exist?(rails_db_file) - FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) - end + FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) unless File.exist?(rails_db_file) end end diff --git a/lib/apartment.rb b/lib/apartment.rb index c04b0cc7..e49285c4 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -108,9 +108,7 @@ def pg_excluded_names # Reset all the config for Apartment def reset (ACCESSOR_METHODS + WRITER_METHODS).each do |method| - if instance_variable_defined?(:"@#{method}") - remove_instance_variable(:"@#{method}") - end + remove_instance_variable(:"@#{method}") if instance_variable_defined?(:"@#{method}") end end diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 544e58b6..ce18f396 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -123,9 +123,7 @@ def reset # def seed_data # Don't log the output of seeding the db - if Apartment.seed_data_file - silence_warnings { load_or_raise(Apartment.seed_data_file) } - end + silence_warnings { load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file end alias seed seed_data @@ -196,9 +194,7 @@ def connect_to_new(tenant) def import_database_schema ActiveRecord::Schema.verbose = false # do not log schema load output. - if Apartment.database_schema_file - load_or_raise(Apartment.database_schema_file) - end + load_or_raise(Apartment.database_schema_file) if Apartment.database_schema_file end # Return a new config that is multi-tenanted diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index f9477fd0..16113b27 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -39,9 +39,7 @@ def connect_to_new(tenant = nil) return reset if tenant.nil? tenant = tenant.to_s - unless tenant_exists?(tenant) - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" - end + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) @current = tenant Apartment.connection.schema_search_path = full_search_path diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 9d3f7a4a..a2ca1163 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -7,9 +7,7 @@ module Tenant def self.postgresql_adapter(config) adapter = Adapters::PostgresqlAdapter adapter = Adapters::PostgresqlSchemaAdapter if Apartment.use_schemas - if Apartment.use_sql && Apartment.use_schemas - adapter = Adapters::PostgresqlSchemaFromSqlAdapter - end + adapter = Adapters::PostgresqlSchemaFromSqlAdapter if Apartment.use_sql && Apartment.use_schemas adapter.new(config) end end @@ -76,9 +74,7 @@ def connect_to_new(tenant = nil) return reset if tenant.nil? tenant = tenant.to_s - unless tenant_exists?(tenant) - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" - end + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) @current = tenant Apartment.connection.schema_search_path = full_search_path @@ -131,9 +127,7 @@ def reset_sequence_names .each do |c| # NOTE: due to this https://github.com/rails-on-services/apartment/issues/81 # unreproduceable error we're checking before trying to remove it - if c.instance_variable_defined?(:@sequence_name) - c.remove_instance_variable :@sequence_name - end + c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) end end end diff --git a/spec/adapters/postgresql_adapter_spec.rb b/spec/adapters/postgresql_adapter_spec.rb index a32e9ccf..d7689d26 100644 --- a/spec/adapters/postgresql_adapter_spec.rb +++ b/spec/adapters/postgresql_adapter_spec.rb @@ -45,9 +45,7 @@ def tenant_names end after do - if Apartment.connection.schema_exists? 'has-dashes' - Apartment::Tenant.drop('has-dashes') - end + Apartment::Tenant.drop('has-dashes') if Apartment.connection.schema_exists? 'has-dashes' end end diff --git a/spec/dummy/config.ru b/spec/dummy/config.ru index 989f7c64..4f079dd4 100644 --- a/spec/dummy/config.ru +++ b/spec/dummy/config.ru @@ -2,5 +2,5 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('config/environment', __dir__) run Dummy::Application diff --git a/spec/dummy_engine/test/dummy/config.ru b/spec/dummy_engine/test/dummy/config.ru index 61c04e13..667e328d 100644 --- a/spec/dummy_engine/test/dummy/config.ru +++ b/spec/dummy_engine/test/dummy/config.ru @@ -2,5 +2,5 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('config/environment', __dir__) run Rails.application From ab15ca73e0281e962d38209027b4bfabc2d40d24 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 11:54:33 +0800 Subject: [PATCH 183/282] ran autocorrect --- .rubocop.yml | 73 +++++++++++++++++++ lib/apartment/active_record/log_subscriber.rb | 3 +- .../adapters/abstract_jdbc_adapter.rb | 2 +- .../adapters/jdbc_postgresql_adapter.rb | 2 +- spec/examples/schema_adapter_examples.rb | 3 - 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 4d999ea2..8416df2e 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -14,3 +14,76 @@ Style/NumericLiterals: Layout/EmptyLineAfterMagicComment: Exclude: - spec/schemas/**/*.rb + +Metrics/BlockLength: + Exclude: + - spec/**/*.rb + +Layout/EmptyLinesAroundAttributeAccessor: + Enabled: true + +Layout/SpaceAroundMethodCallOperator: + Enabled: true + +Lint/DeprecatedOpenSSLConstant: + Enabled: true + +Lint/DuplicateElsifCondition: + Enabled: true + +Lint/MixedRegexpCaptureTypes: + Enabled: true + +Lint/RaiseException: + Enabled: true + +Lint/StructNewOverride: + Enabled: true + +Style/AccessorGrouping: + Enabled: true + +Style/ArrayCoercion: + Enabled: true + +Style/BisectedAttrAccessor: + Enabled: true + +Style/CaseLikeIf: + Enabled: true + +Style/ExponentialNotation: + Enabled: true + +Style/HashAsLastArrayItem: + Enabled: true + +Style/HashEachMethods: + Enabled: true + +Style/HashLikeCase: + Enabled: true + +Style/HashTransformKeys: + Enabled: true + +Style/HashTransformValues: + Enabled: true + +Style/RedundantAssignment: + Enabled: true + +Style/RedundantFetchBlock: + Enabled: true + +Style/RedundantFileExtensionInRequire: + Enabled: true + +Style/RedundantRegexpCharacterClass: + Enabled: true + +Style/RedundantRegexpEscape: + Enabled: true + +Style/SlicingWithRange: + Enabled: true diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb index a0e4bea5..5860928b 100644 --- a/lib/apartment/active_record/log_subscriber.rb +++ b/lib/apartment/active_record/log_subscriber.rb @@ -17,8 +17,7 @@ def payload_binds(binds, type_casted_binds) return unless (binds || []).empty? casted_params = type_casted_binds(type_casted_binds) - binds = ' ' + binds.zip(casted_params).map { |attr, value| render_bind(attr, value) }.inspect - binds + ' ' + binds.zip(casted_params).map { |attr, value| render_bind(attr, value) }.inspect end def sql(event) diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index d37aa79d..6881071e 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -8,7 +8,7 @@ class AbstractJDBCAdapter < AbstractAdapter private def multi_tenantify_with_tenant_db_name(config, tenant) - config[:url] = "#{config[:url].gsub(%r{(\S+)\/.+$}, '\1')}/#{environmentify(tenant)}" + config[:url] = "#{config[:url].gsub(%r{(\S+)/.+$}, '\1')}/#{environmentify(tenant)}" end def rescue_from diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 16113b27..7f6aed67 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -19,7 +19,7 @@ class JDBCPostgresqlAdapter < PostgresqlAdapter private def multi_tenantify_with_tenant_db_name(config, tenant) - config[:url] = "#{config[:url].gsub(%r{(\S+)\/.+$}, '\1')}/#{environmentify(tenant)}" + config[:url] = "#{config[:url].gsub(%r{(\S+)/.+$}, '\1')}/#{environmentify(tenant)}" end def create_tenant_command(conn, tenant) diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index e172d613..447322e3 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -1,8 +1,6 @@ # frozen_string_literal: true require 'spec_helper' - -# rubocop:disable Metrics/BlockLength shared_examples_for 'a schema based apartment adapter' do include Apartment::Spec::AdapterRequirements @@ -254,4 +252,3 @@ end end end -# rubocop:enable Metrics/BlockLength From 5566b8f2262d4bc70213deca7ac14351903b8135 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 12:16:13 +0800 Subject: [PATCH 184/282] addressed some of the rubocop offenses and added todo --- .rubocop.yml | 2 + .rubocop_todo.yml | 73 +++++++++++++++++++ Guardfile | 15 ---- Rakefile | 2 + lib/apartment.rb | 4 +- .../active_record/connection_handling.rb | 3 + lib/apartment/active_record/log_subscriber.rb | 4 +- lib/apartment/adapters/abstract_adapter.rb | 6 +- .../adapters/abstract_jdbc_adapter.rb | 1 + .../adapters/jdbc_postgresql_adapter.rb | 1 + lib/apartment/adapters/mysql2_adapter.rb | 3 + 11 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 8416df2e..b0a4cc6c 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,3 +1,5 @@ +inherit_from: .rubocop_todo.yml + AllCops: Exclude: - 'gemfiles/**/*.gemfile' diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 00000000..85e144ed --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,73 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2020-07-16 04:15:41 UTC using RuboCop version 0.88.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +Lint/MixedRegexpCaptureTypes: + Exclude: + - 'lib/apartment/elevators/domain.rb' + +# Offense count: 2 +# Cop supports --auto-correct. +Lint/NonDeterministicRequireOrder: + Exclude: + - 'spec/spec_helper.rb' + +# Offense count: 7 +# Configuration parameters: IgnoredMethods. +Metrics/AbcSize: + Max: 33 + +# Offense count: 3 +# Configuration parameters: CountComments, CountAsOne, ExcludedMethods. +# ExcludedMethods: refine +Metrics/BlockLength: + Max: 102 + +# Offense count: 1 +# Configuration parameters: CountComments, CountAsOne. +Metrics/ClassLength: + Max: 151 + +# Offense count: 6 +# Configuration parameters: CountComments, CountAsOne, ExcludedMethods. +Metrics/MethodLength: + Max: 24 + +# Offense count: 17 +Style/Documentation: + Exclude: + - 'spec/**/*' + - 'test/**/*' + - 'lib/apartment/adapters/jdbc_mysql_adapter.rb' + - 'lib/apartment/adapters/postgis_adapter.rb' + - 'lib/apartment/adapters/postgresql_adapter.rb' + - 'lib/apartment/adapters/sqlite3_adapter.rb' + - 'lib/apartment/custom_console.rb' + - 'lib/apartment/deprecation.rb' + - 'lib/apartment/migrator.rb' + - 'lib/apartment/model.rb' + - 'lib/apartment/railtie.rb' + - 'lib/apartment/reloader.rb' + - 'lib/apartment/tasks/enhancements.rb' + - 'lib/apartment/tasks/task_helper.rb' + - 'lib/generators/apartment/install/install_generator.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +Style/IfUnlessModifier: + Exclude: + - 'Rakefile' + - 'lib/apartment.rb' + - 'lib/apartment/tenant.rb' + +# Offense count: 12 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Layout/LineLength: + Max: 171 diff --git a/Guardfile b/Guardfile index ffec03ce..335bab54 100644 --- a/Guardfile +++ b/Guardfile @@ -8,19 +8,4 @@ guard :rspec do watch(%r{^lib/apartment/(.+)\.rb$}) { |m| "spec/unit/#{m[1]}_spec.rb" } watch(%r{^lib/apartment/(.+)\.rb$}) { |m| "spec/integration/#{m[1]}_spec.rb" } watch('spec/spec_helper.rb') { 'spec' } - - # # Rails example - # watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } - # watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" } - # watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] } - # watch(%r{^spec/support/(.+)\.rb$}) { "spec" } - # watch('config/routes.rb') { "spec/routing" } - # watch('app/controllers/application_controller.rb') { "spec/controllers" } - - # # Capybara features specs - # watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$}) { |m| "spec/features/#{m[1]}_spec.rb" } - - # # Turnip features and steps - # watch(%r{^spec/acceptance/(.+)\.feature$}) - # watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' } end diff --git a/Rakefile b/Rakefile index 948bd059..62e89b26 100644 --- a/Rakefile +++ b/Rakefile @@ -1,5 +1,6 @@ # frozen_string_literal: true +# rubocop:disable Metrics/BlockLength begin require 'bundler' rescue StandardError @@ -117,6 +118,7 @@ namespace :mysql do `mysqladmin #{params.join(' ')} drop #{my_config['database']} --force` end end +# rubocop:enable Metrics/BlockLength # TODO: clean this up def config diff --git a/lib/apartment.rb b/lib/apartment.rb index e49285c4..6bca1cc8 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,9 +6,8 @@ require 'active_record' require 'apartment/tenant' -# require_relative 'apartment/arel/visitors/postgresql' - require_relative 'apartment/active_record/log_subscriber' + if ActiveRecord.version.release >= Gem::Version.new('6.0') require_relative 'apartment/active_record/connection_handling' end @@ -18,6 +17,7 @@ require_relative 'apartment/active_record/internal_metadata' end +# Apartment main definitions module Apartment class << self extend Forwardable diff --git a/lib/apartment/active_record/connection_handling.rb b/lib/apartment/active_record/connection_handling.rb index c9c1056f..f306258e 100644 --- a/lib/apartment/active_record/connection_handling.rb +++ b/lib/apartment/active_record/connection_handling.rb @@ -1,6 +1,9 @@ # frozen_string_literal: true module ActiveRecord + # This is monkeypatching activerecord to ensure that whenever a new connection is established it + # switches to the same tenant as before the connection switching. This problem is more evident when + # using read replica in Rails 6 module ConnectionHandling def connected_to_with_tenant(database: nil, role: nil, prevent_writes: false, &blk) current_tenant = Apartment::Tenant.current diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb index 5860928b..da5430d1 100644 --- a/lib/apartment/active_record/log_subscriber.rb +++ b/lib/apartment/active_record/log_subscriber.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true module ActiveRecord + # Supports the logging configuration to prepend the database and schema in the ActiveRecord log class LogSubscriber def apartment_log return unless Apartment.active_record_log @@ -8,7 +9,8 @@ def apartment_log database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) schema = nil unless Apartment.connection.schema_search_path.nil? - schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", ActiveSupport::LogSubscriber::YELLOW, true) + schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", + ActiveSupport::LogSubscriber::YELLOW, true) end "#{database}#{schema}" end diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index ce18f396..8ca4f308 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -2,7 +2,7 @@ module Apartment module Adapters - # rubocop:disable Metrics/ClassLength + # Abstract adapter from which all the Apartment DB related adapters will inherit the base logic class AbstractAdapter include ActiveSupport::Callbacks define_callbacks :create, :switch @@ -240,7 +240,8 @@ def db_connection_config(tenant) def with_neutral_connection(tenant, &_block) if Apartment.with_multi_server_setup # neutral connection is necessary whenever you need to create/remove a database from a server. - # example: when you use postgresql, you need to connect to the default postgresql database before you create your own. + # example: when you use postgresql, you need to connect to the default postgresql database before you create + # your own. SeparateDbConnectionHandler.establish_connection(multi_tenantify(tenant, false)) yield(SeparateDbConnectionHandler.connection) SeparateDbConnectionHandler.connection.close @@ -269,5 +270,4 @@ class SeparateDbConnectionHandler < ::ActiveRecord::Base end end end - # rubocop:enable Metrics/ClassLength end diff --git a/lib/apartment/adapters/abstract_jdbc_adapter.rb b/lib/apartment/adapters/abstract_jdbc_adapter.rb index 6881071e..4dd0748c 100644 --- a/lib/apartment/adapters/abstract_jdbc_adapter.rb +++ b/lib/apartment/adapters/abstract_jdbc_adapter.rb @@ -4,6 +4,7 @@ module Apartment module Adapters + # JDBC Abstract adapter class AbstractJDBCAdapter < AbstractAdapter private diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 7f6aed67..70dbadf3 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -3,6 +3,7 @@ require 'apartment/adapters/postgresql_adapter' module Apartment + # JDBC helper to decide wether to use JDBC Postgresql Adapter or JDBC Postgresql Adapter with Schemas module Tenant def self.jdbc_postgresql_adapter(config) if Apartment.use_schemas diff --git a/lib/apartment/adapters/mysql2_adapter.rb b/lib/apartment/adapters/mysql2_adapter.rb index 71adbe60..ca9b1a7f 100644 --- a/lib/apartment/adapters/mysql2_adapter.rb +++ b/lib/apartment/adapters/mysql2_adapter.rb @@ -3,6 +3,7 @@ require 'apartment/adapters/abstract_adapter' module Apartment + # Helper module to decide wether to use mysql2 adapter or mysql2 adapter with schemas module Tenant def self.mysql2_adapter(config) if Apartment.use_schemas @@ -14,6 +15,7 @@ def self.mysql2_adapter(config) end module Adapters + # Mysql2 Adapter class Mysql2Adapter < AbstractAdapter def initialize(config) super @@ -28,6 +30,7 @@ def rescue_from end end + # Mysql2 Schemas Adapter class Mysql2SchemaAdapter < AbstractAdapter def initialize(config) super From ff648f1744e06692dd60741625f82496b09c78d4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 12:28:56 +0800 Subject: [PATCH 185/282] cleanup line length --- .rubocop_todo.yml | 7 ------- Rakefile | 2 -- lib/apartment/adapters/postgresql_adapter.rb | 21 ++++++++++++------- lib/apartment/custom_console.rb | 2 ++ .../apartment/install/templates/apartment.rb | 3 ++- spec/adapters/jdbc_mysql_adapter_spec.rb | 4 +++- spec/adapters/mysql2_adapter_spec.rb | 4 +++- .../dummy/config/initializers/secret_token.rb | 3 +++ spec/dummy/script/rails | 3 ++- spec/dummy_engine/bin/rails | 3 ++- .../config/initializers/apartment.rb | 3 ++- ...ic_adapter_custom_configuration_example.rb | 8 +++++-- 12 files changed, 38 insertions(+), 25 deletions(-) diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 85e144ed..c72ac883 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -64,10 +64,3 @@ Style/IfUnlessModifier: - 'Rakefile' - 'lib/apartment.rb' - 'lib/apartment/tenant.rb' - -# Offense count: 12 -# Cop supports --auto-correct. -# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. -# URISchemes: http, https -Layout/LineLength: - Max: 171 diff --git a/Rakefile b/Rakefile index 62e89b26..948bd059 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,5 @@ # frozen_string_literal: true -# rubocop:disable Metrics/BlockLength begin require 'bundler' rescue StandardError @@ -118,7 +117,6 @@ namespace :mysql do `mysqladmin #{params.join(' ')} drop #{my_config['database']} --force` end end -# rubocop:enable Metrics/BlockLength # TODO: clean this up def config diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index a2ca1163..17cbb892 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -121,14 +121,17 @@ def reset_sequence_names # There is `reset_sequence_name`, but that method actually goes to the database # to find out the new name. Therefore, we do this hack to only unset the name, # and it will be dynamically found the next time it is needed - ActiveRecord::Base.descendants - .select { |c| c.instance_variable_defined?(:@sequence_name) } - .reject { |c| c.instance_variable_defined?(:@explicit_sequence_name) && c.instance_variable_get(:@explicit_sequence_name) } - .each do |c| - # NOTE: due to this https://github.com/rails-on-services/apartment/issues/81 - # unreproduceable error we're checking before trying to remove it - c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) - end + descendants_to_unset = ActiveRecord::Base.descendants + .select { |c| c.instance_variable_defined?(:@sequence_name) } + .reject do |c| + c.instance_variable_defined?(:@explicit_sequence_name) && + c.instance_variable_get(:@explicit_sequence_name) + end + descendants_to_unset.each do |c| + # NOTE: due to this https://github.com/rails-on-services/apartment/issues/81 + # unreproduceable error we're checking before trying to remove it + c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) + end end end @@ -197,9 +200,11 @@ def pg_dump_schema # # @return {String} raw SQL contaning inserts with data from schema_migrations # + # rubocop:disable Layout/LineLength def pg_dump_schema_migrations_data with_pg_env { `pg_dump -a --inserts -t #{default_tenant}.schema_migrations -t #{default_tenant}.ar_internal_metadata #{dbname}` } end + # rubocop:enable Layout/LineLength # Temporary set Postgresql related environment variables if there are in @config # diff --git a/lib/apartment/custom_console.rb b/lib/apartment/custom_console.rb index bc3d0902..7b32a5b5 100644 --- a/lib/apartment/custom_console.rb +++ b/lib/apartment/custom_console.rb @@ -7,7 +7,9 @@ module CustomConsole begin require 'pry-rails' rescue LoadError + # rubocop:disable Layout/LineLength puts '[Failed to load pry-rails] If you want to use Apartment custom prompt you need to add pry-rails to your gemfile' + # rubocop:enable Layout/LineLength end desc = "Includes the current Rails environment and project folder name.\n" \ diff --git a/lib/generators/apartment/install/templates/apartment.rb b/lib/generators/apartment/install/templates/apartment.rb index ece13534..17f73c60 100644 --- a/lib/generators/apartment/install/templates/apartment.rb +++ b/lib/generators/apartment/install/templates/apartment.rb @@ -23,7 +23,8 @@ # You can make this dynamic by providing a Proc object to be called on migrations. # This object should yield either: # - an array of strings representing each Tenant name. - # - a hash which keys are tenant names, and values custom db config (must contain all key/values required in database.yml) + # - a hash which keys are tenant names, and values custom db config + # (must contain all key/values required in database.yml) # # config.tenant_names = lambda{ Customer.pluck(:tenant_name) } # config.tenant_names = ['tenant1', 'tenant2'] diff --git a/spec/adapters/jdbc_mysql_adapter_spec.rb b/spec/adapters/jdbc_mysql_adapter_spec.rb index 764893b3..2d0fb975 100644 --- a/spec/adapters/jdbc_mysql_adapter_spec.rb +++ b/spec/adapters/jdbc_mysql_adapter_spec.rb @@ -9,7 +9,9 @@ subject { Apartment::Tenant.jdbc_mysql_adapter config.symbolize_keys } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row['schema_name'] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect do |row| + row['schema_name'] + end end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } diff --git a/spec/adapters/mysql2_adapter_spec.rb b/spec/adapters/mysql2_adapter_spec.rb index ca3e577f..505b7d6b 100644 --- a/spec/adapters/mysql2_adapter_spec.rb +++ b/spec/adapters/mysql2_adapter_spec.rb @@ -9,7 +9,9 @@ subject(:adapter) { Apartment::Tenant.mysql2_adapter config } def tenant_names - ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect { |row| row[0] } + ActiveRecord::Base.connection.execute('SELECT schema_name FROM information_schema.schemata').collect do |row| + row[0] + end end let(:default_tenant) { subject.switch { ActiveRecord::Base.connection.current_database } } diff --git a/spec/dummy/config/initializers/secret_token.rb b/spec/dummy/config/initializers/secret_token.rb index 2c7f52bd..1ba0d52f 100644 --- a/spec/dummy/config/initializers/secret_token.rb +++ b/spec/dummy/config/initializers/secret_token.rb @@ -6,4 +6,7 @@ # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. + +# rubocop:disable Layout/LineLength Dummy::Application.config.secret_token = '7d33999a86884f74c897c98ecca4277090b69e9f23df8d74bcadd57435320a7a16de67966f9b69d62e7d5ec553bd2febbe64c721e05bc1bc1e82c7a7d2395201' +# rubocop:enable Layout/LineLength diff --git a/spec/dummy/script/rails b/spec/dummy/script/rails index e1068b28..6c919a61 100755 --- a/spec/dummy/script/rails +++ b/spec/dummy/script/rails @@ -1,7 +1,8 @@ #!/usr/bin/env ruby # frozen_string_literal: true -# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. +# This command will automatically be run when you run "rails" with Rails 3 gems installed +# from the root of your application. APP_PATH = File.expand_path('../config/application', __dir__) require File.expand_path('../config/boot', __dir__) diff --git a/spec/dummy_engine/bin/rails b/spec/dummy_engine/bin/rails index 800e13a6..397f409e 100755 --- a/spec/dummy_engine/bin/rails +++ b/spec/dummy_engine/bin/rails @@ -1,7 +1,8 @@ #!/usr/bin/env ruby # frozen_string_literal: true -# This command will automatically be run when you run "rails" with Rails 4 gems installed from the root of your application. +# This command will automatically be run when you run "rails" with Rails 4 gems installed +# from the root of your application. ENGINE_ROOT = File.expand_path('..', __dir__) ENGINE_PATH = File.expand_path('../lib/dummy_engine/engine', __dir__) diff --git a/spec/dummy_engine/config/initializers/apartment.rb b/spec/dummy_engine/config/initializers/apartment.rb index 466f3d87..a65748eb 100644 --- a/spec/dummy_engine/config/initializers/apartment.rb +++ b/spec/dummy_engine/config/initializers/apartment.rb @@ -36,7 +36,8 @@ # supply list of database names for migrations to run on # config.tenant_names = lambda{ ToDo_Tenant_Or_User_Model.pluck :database } - # Specify a connection other than ActiveRecord::Base for apartment to use (only needed if your models are using a different connection) + # Specify a connection other than ActiveRecord::Base for apartment to use + # (only needed if your models are using a different connection) # config.connection_class = ActiveRecord::Base end diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index 07e2c719..5abe5029 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -25,7 +25,9 @@ describe '#create' do it 'should establish_connection with the separate connection with expected args' do - expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to receive(:establish_connection).with(expected_args).and_call_original + expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to( + receive(:establish_connection).with(expected_args).and_call_original + ) # because we dont have another server to connect to it errors # what matters is establish_connection receives proper args @@ -35,7 +37,9 @@ describe '#drop' do it 'should establish_connection with the separate connection with expected args' do - expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to receive(:establish_connection).with(expected_args).and_call_original + expect(Apartment::Adapters::AbstractAdapter::SeparateDbConnectionHandler).to( + receive(:establish_connection).with(expected_args).and_call_original + ) # because we dont have another server to connect to it errors # what matters is establish_connection receives proper args From a8c646bebd99979366835331bc3904bb05c1b835 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 12:39:22 +0800 Subject: [PATCH 186/282] diffend was causing some trouble updating the gems --- .travis.yml | 2 +- Gemfile | 2 +- gemfiles/rails_5_0.gemfile | 2 +- gemfiles/rails_5_1.gemfile | 2 +- gemfiles/rails_5_2.gemfile | 2 +- gemfiles/rails_6_0.gemfile | 2 +- gemfiles/rails_master.gemfile | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.travis.yml b/.travis.yml index ef952b31..784d4b5c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,7 +36,7 @@ env: jobs: include: - name: Rubocop Lint - script: gem install perx-rubocop && rubocop + script: gem install rubocop allow_failures: - rvm: ruby-head diff --git a/Gemfile b/Gemfile index fa74281e..0949319d 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,6 @@ # frozen_string_literal: true -source 'https://my.diffend.io/protect/gems' +source 'http://rubygems.org' gemspec diff --git a/gemfiles/rails_5_0.gemfile b/gemfiles/rails_5_0.gemfile index e963b5b3..37dc042b 100644 --- a/gemfiles/rails_5_0.gemfile +++ b/gemfiles/rails_5_0.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "perx-rubocop", "~> 0.0.3" gem "rails", "~> 5.0.0" +gem "rubocop" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_5_1.gemfile b/gemfiles/rails_5_1.gemfile index 8785b959..59af05f8 100644 --- a/gemfiles/rails_5_1.gemfile +++ b/gemfiles/rails_5_1.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "perx-rubocop", "~> 0.0.3" gem "rails", "~> 5.1.0" +gem "rubocop" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_5_2.gemfile b/gemfiles/rails_5_2.gemfile index 1afc645b..18d8952a 100644 --- a/gemfiles/rails_5_2.gemfile +++ b/gemfiles/rails_5_2.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "perx-rubocop", "~> 0.0.3" gem "rails", "~> 5.2.0" +gem "rubocop" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_6_0.gemfile b/gemfiles/rails_6_0.gemfile index 6c3d3968..6d23e4aa 100644 --- a/gemfiles/rails_6_0.gemfile +++ b/gemfiles/rails_6_0.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "perx-rubocop", "~> 0.0.3" gem "rails", "~> 6.0.0" +gem "rubocop" group :local do gem "guard-rspec", "~> 4.2" diff --git a/gemfiles/rails_master.gemfile b/gemfiles/rails_master.gemfile index f2add08a..82ad9191 100644 --- a/gemfiles/rails_master.gemfile +++ b/gemfiles/rails_master.gemfile @@ -2,8 +2,8 @@ source "http://rubygems.org" -gem "perx-rubocop", "~> 0.0.3" gem "rails", git: "https://github.com/rails/rails.git" +gem "rubocop" group :local do gem "guard-rspec", "~> 4.2" From 97ec6c3d956d9d18a4d33cdcbdfa368cd8ef131d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 16 Jul 2020 17:44:05 +0800 Subject: [PATCH 187/282] [#92] calling reload to ensure the adatper is re-evaluated --- lib/apartment/railtie.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 101c8b43..e3324bb4 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -27,7 +27,7 @@ class Railtie < Rails::Railtie # Make sure Apartment is reconfigured when the code is reloaded config.to_prepare do - Apartment::Tenant.reinitialize + Apartment::Tenant.reload! end # From 029e174927344cb08adc036f777f208ff3f9044e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 00:13:06 +0800 Subject: [PATCH 188/282] [#92] added test coverage for bug report --- spec/examples/generic_adapter_examples.rb | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 525e0b77..9af74646 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -24,6 +24,12 @@ expect(num_available_connections).to eq(0) end + + it 'ensures apartment_adapter is properly set during init' do + Thread.current[:apartment_adapter] = Apartment::Adapters::AbstractAdapter.new(config) + Apartment::Railtie.config.to_prepare_blocks.map(&:call) + expect(Apartment::Tenant.adapter.class.name).to eq 'Apartment::Adapters::PostgresqlAdapter' + end end # From bb584b5382c85b318ec83a98f49d4f4314c5ee83 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 00:15:19 +0800 Subject: [PATCH 189/282] [#92] added comment on test --- spec/examples/generic_adapter_examples.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 9af74646..e8bf796f 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -25,6 +25,8 @@ expect(num_available_connections).to eq(0) end + # NOTE: Bug report #92 - when the adapter is set before the railtie is actually run, the adapter class might be + # incorrect. This tests intends to assure that the railtie init resets the adapter to the correct one it 'ensures apartment_adapter is properly set during init' do Thread.current[:apartment_adapter] = Apartment::Adapters::AbstractAdapter.new(config) Apartment::Railtie.config.to_prepare_blocks.map(&:call) From 661173181f55f2c52f55d966bc0551da8e2b3ca3 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 00:19:17 +0800 Subject: [PATCH 190/282] [#92] relying on subject to ensure correct class in test --- spec/examples/generic_adapter_examples.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index e8bf796f..a81c26bf 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -30,7 +30,7 @@ it 'ensures apartment_adapter is properly set during init' do Thread.current[:apartment_adapter] = Apartment::Adapters::AbstractAdapter.new(config) Apartment::Railtie.config.to_prepare_blocks.map(&:call) - expect(Apartment::Tenant.adapter.class.name).to eq 'Apartment::Adapters::PostgresqlAdapter' + expect(Apartment::Tenant.adapter.class.name).to eq subject.class.name end end From 143fa4b54d88df25cc1110c1a5f64a03c09ea260 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 09:40:55 +0800 Subject: [PATCH 191/282] [Chore] Update github actions to generate changelog to development branch - using automated changelog generator github action - using github actions for pushing to development branch --- .github/workflows/changelog.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 27a5f690..9b61f51c 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -15,26 +15,26 @@ jobs: runs-on: ubuntu-latest name: Generate changelog for master branch steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 + with: + fetch-depth: 0 # otherwise, you will failed to push refs to dest repo - name: Generate changelog uses: charmixer/auto-changelog-action@v1 with: - token: ${{ secrets.YOUR_GITHUB_TOKEN or GITHUB_TOKEN }} + token: ${{ secrets.GITHUB_TOKEN }} - name: Commit files env: - CI_USER: ${{ secrets.YOUR_GITHUB_USER }} - CI_EMAIL: ${{ secrets.YOUR_GITHUB_EMAIL }} + ACTION_EMAIL: action@github.com + ACTION_USERNAME: GitHub Action run: | - git config --local user.email "$CI_EMAIL" - git config --local user.name "$CI_USER" + git config --local user.email "$ACTION_EMAIL" + git config --local user.name "$ACTION_USERNAME" git add CHANGELOG.md && git commit -m 'Updated CHANGELOG.md' && echo ::set-env name=push::1 || echo "No changes to CHANGELOG.md" - name: Push changes - if: env.push == 1 - env: - CI_USER: ${{ secrets.YOUR_GITHUB_USER }} - CI_TOKEN: ${{ secrets.YOUR_GITHUB_TOKEN or GITHUB_TOKEN }} - run: | - git push "https://$CI_USER:$CI_TOKEN@github.com/$GITHUB_REPOSITORY.git" HEAD:master + uses: ad-m/github-push-action@master + with: + github_token: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} + branch: development From dad34d42912a266e5382dd48a6e5b012dfb3aaee Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 10:52:55 +0800 Subject: [PATCH 192/282] only push if there is something to commit --- .github/workflows/changelog.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 9b61f51c..0726d2ec 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -34,6 +34,7 @@ jobs: git add CHANGELOG.md && git commit -m 'Updated CHANGELOG.md' && echo ::set-env name=push::1 || echo "No changes to CHANGELOG.md" - name: Push changes + if: env.push == 1 uses: ad-m/github-push-action@master with: github_token: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} From c1fd6823a7c44ba1206a28b9d3a69027bab4352b Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 17 Jul 2020 03:40:09 +0000 Subject: [PATCH 193/282] Updated CHANGELOG.md --- CHANGELOG.md | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ef09db3..b867de6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,22 +4,28 @@ [Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.1...HEAD) +**Implemented enhancements:** + +- Deprecate History.md [\#80](https://github.com/rails-on-services/apartment/issues/80) + +**Fixed bugs:** + +- Tenant.switch! raises exception on first call / Postgresql [\#92](https://github.com/rails-on-services/apartment/issues/92) +- NameError: instance variable @sequence\_name not defined [\#81](https://github.com/rails-on-services/apartment/issues/81) + **Closed issues:** - Error creating tenant with uuid column [\#85](https://github.com/rails-on-services/apartment/issues/85) - enhanced db:create task breaks plugins compatibility [\#82](https://github.com/rails-on-services/apartment/issues/82) - Support disabling of full\_migration\_on\_create [\#30](https://github.com/rails-on-services/apartment/issues/30) -**Merged pull requests:** - -- \[Resolves \#81\] check for var existence before [\#89](https://github.com/rails-on-services/apartment/pull/89) ([rpbaltazar](https://github.com/rpbaltazar)) - ## [v2.7.1](https://github.com/rails-on-services/apartment/tree/v2.7.1) (2020-06-27) [Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.0...v2.7.1) **Merged pull requests:** +- \[Resolves \#80\] added changelog action [\#90](https://github.com/rails-on-services/apartment/pull/90) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare Release 2.7.1 [\#84](https://github.com/rails-on-services/apartment/pull/84) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#82\] Enhanced db create task breaks plugins compatibility [\#83](https://github.com/rails-on-services/apartment/pull/83) ([rpbaltazar](https://github.com/rpbaltazar)) - \[ci\] update rake [\#79](https://github.com/rails-on-services/apartment/pull/79) ([ahorek](https://github.com/ahorek)) @@ -61,7 +67,6 @@ - db:rollback uses second latest migration for tenants [\#56](https://github.com/rails-on-services/apartment/issues/56) - rake db:setup tries to seed non existing tenant [\#52](https://github.com/rails-on-services/apartment/issues/52) -- Custom Console deprecation warning [\#37](https://github.com/rails-on-services/apartment/issues/37) **Merged pull requests:** @@ -71,6 +76,8 @@ - \[\#52\] enhance after db create [\#54](https://github.com/rails-on-services/apartment/pull/54) ([rpbaltazar](https://github.com/rpbaltazar)) - fix init after reload on development [\#53](https://github.com/rails-on-services/apartment/pull/53) ([fsateler](https://github.com/fsateler)) - fix: reset sequence\_name after tenant switch [\#51](https://github.com/rails-on-services/apartment/pull/51) ([fsateler](https://github.com/fsateler)) +- Add console welcome message [\#47](https://github.com/rails-on-services/apartment/pull/47) ([JeremiahChurch](https://github.com/JeremiahChurch)) +- Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) ## [v2.6.0](https://github.com/rails-on-services/apartment/tree/v2.6.0) (2020-05-14) @@ -81,13 +88,13 @@ - Error Dropping Tenant [\#46](https://github.com/rails-on-services/apartment/issues/46) - After switch callback not working with nil argument [\#42](https://github.com/rails-on-services/apartment/issues/42) - Add tenant info to console boot? [\#41](https://github.com/rails-on-services/apartment/issues/41) +- Custom Console deprecation warning [\#37](https://github.com/rails-on-services/apartment/issues/37) - Support configuration for skip checking of schema existence before switching [\#26](https://github.com/rails-on-services/apartment/issues/26) **Merged pull requests:** - \[Resolves \#37\] Custom console deprecation warning [\#49](https://github.com/rails-on-services/apartment/pull/49) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare Release 2.6.0 [\#48](https://github.com/rails-on-services/apartment/pull/48) ([rpbaltazar](https://github.com/rpbaltazar)) -- Add console welcome message [\#47](https://github.com/rails-on-services/apartment/pull/47) ([JeremiahChurch](https://github.com/JeremiahChurch)) - \[Resolves \#26\] Support configuration for skip checking of schema existence before switching [\#45](https://github.com/rails-on-services/apartment/pull/45) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#42\] After switch callback not working with nil argument [\#43](https://github.com/rails-on-services/apartment/pull/43) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -114,9 +121,9 @@ - Prepare Release 2.5.0 [\#44](https://github.com/rails-on-services/apartment/pull/44) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] Added before hook to connected to to try to set the tenant [\#40](https://github.com/rails-on-services/apartment/pull/40) ([rpbaltazar](https://github.com/rpbaltazar)) -- Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) - \[Resolves \#35\] update cache key to use a string or an array [\#36](https://github.com/rails-on-services/apartment/pull/36) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Hotfix \#27\] Some errors were being thrown due to caching issues [\#33](https://github.com/rails-on-services/apartment/pull/33) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Chore\] refactored files to their names [\#29](https://github.com/rails-on-services/apartment/pull/29) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] When manually switching the connection it resets the search path [\#28](https://github.com/rails-on-services/apartment/pull/28) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -139,7 +146,6 @@ **Merged pull requests:** -- \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - Fix gemspec open versions and updated version [\#25](https://github.com/rails-on-services/apartment/pull/25) ([rpbaltazar](https://github.com/rpbaltazar)) - Fix gemspec open versions and updated version [\#24](https://github.com/rails-on-services/apartment/pull/24) ([rpbaltazar](https://github.com/rpbaltazar)) - Cleanup travis matrix [\#23](https://github.com/rails-on-services/apartment/pull/23) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -264,15 +270,15 @@ ## [v0.20.0](https://github.com/rails-on-services/apartment/tree/v0.20.0) (2013-02-06) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.2...v0.20.0) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/rm...v0.20.0) -## [v0.19.2](https://github.com/rails-on-services/apartment/tree/v0.19.2) (2013-01-30) +## [rm](https://github.com/rails-on-services/apartment/tree/rm) (2013-01-30) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/rm...v0.19.2) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.2...rm) -## [rm](https://github.com/rails-on-services/apartment/tree/rm) (2013-01-30) +## [v0.19.2](https://github.com/rails-on-services/apartment/tree/v0.19.2) (2013-01-30) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.0...rm) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.19.0...v0.19.2) ## [v0.19.0](https://github.com/rails-on-services/apartment/tree/v0.19.0) (2012-12-30) @@ -384,15 +390,15 @@ ## [v0.7.0](https://github.com/rails-on-services/apartment/tree/v0.7.0) (2011-06-22) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/0.6.0...v0.7.0) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.6.0...v0.7.0) -## [0.6.0](https://github.com/rails-on-services/apartment/tree/0.6.0) (2011-06-21) +## [v0.6.0](https://github.com/rails-on-services/apartment/tree/v0.6.0) (2011-06-21) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.6.0...0.6.0) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/0.6.0...v0.6.0) -## [v0.6.0](https://github.com/rails-on-services/apartment/tree/v0.6.0) (2011-06-21) +## [0.6.0](https://github.com/rails-on-services/apartment/tree/0.6.0) (2011-06-21) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.5.1...v0.6.0) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v0.5.1...0.6.0) ## [v0.5.1](https://github.com/rails-on-services/apartment/tree/v0.5.1) (2011-06-21) From 1c65772066f08f1364c986bb35a10da7c29f0656 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 11:43:42 +0800 Subject: [PATCH 194/282] Version Bump - 2.7.2 --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 215a1191..8191b485 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.7.1' + VERSION = '2.7.2' end From 41327f508f75a6b3668ba16f4478a017a9a1bab6 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 17 Jul 2020 04:17:39 +0000 Subject: [PATCH 195/282] Updated CHANGELOG.md --- CHANGELOG.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b867de6d..fbc6eed3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,13 +19,21 @@ - enhanced db:create task breaks plugins compatibility [\#82](https://github.com/rails-on-services/apartment/issues/82) - Support disabling of full\_migration\_on\_create [\#30](https://github.com/rails-on-services/apartment/issues/30) +**Merged pull requests:** + +- \[Chore\] Fix Changelog github action [\#97](https://github.com/rails-on-services/apartment/pull/97) ([rpbaltazar](https://github.com/rpbaltazar)) +- Prepare release - 2.7.2 [\#96](https://github.com/rails-on-services/apartment/pull/96) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#92\] tenant switch raises exception on first call [\#95](https://github.com/rails-on-services/apartment/pull/95) ([rpbaltazar](https://github.com/rpbaltazar)) +- Dont use custom rubocop [\#94](https://github.com/rails-on-services/apartment/pull/94) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#80\] added changelog action [\#90](https://github.com/rails-on-services/apartment/pull/90) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#81\] check for var existence before [\#89](https://github.com/rails-on-services/apartment/pull/89) ([rpbaltazar](https://github.com/rpbaltazar)) + ## [v2.7.1](https://github.com/rails-on-services/apartment/tree/v2.7.1) (2020-06-27) [Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.0...v2.7.1) **Merged pull requests:** -- \[Resolves \#80\] added changelog action [\#90](https://github.com/rails-on-services/apartment/pull/90) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare Release 2.7.1 [\#84](https://github.com/rails-on-services/apartment/pull/84) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#82\] Enhanced db create task breaks plugins compatibility [\#83](https://github.com/rails-on-services/apartment/pull/83) ([rpbaltazar](https://github.com/rpbaltazar)) - \[ci\] update rake [\#79](https://github.com/rails-on-services/apartment/pull/79) ([ahorek](https://github.com/ahorek)) @@ -67,6 +75,7 @@ - db:rollback uses second latest migration for tenants [\#56](https://github.com/rails-on-services/apartment/issues/56) - rake db:setup tries to seed non existing tenant [\#52](https://github.com/rails-on-services/apartment/issues/52) +- Custom Console deprecation warning [\#37](https://github.com/rails-on-services/apartment/issues/37) **Merged pull requests:** @@ -76,7 +85,6 @@ - \[\#52\] enhance after db create [\#54](https://github.com/rails-on-services/apartment/pull/54) ([rpbaltazar](https://github.com/rpbaltazar)) - fix init after reload on development [\#53](https://github.com/rails-on-services/apartment/pull/53) ([fsateler](https://github.com/fsateler)) - fix: reset sequence\_name after tenant switch [\#51](https://github.com/rails-on-services/apartment/pull/51) ([fsateler](https://github.com/fsateler)) -- Add console welcome message [\#47](https://github.com/rails-on-services/apartment/pull/47) ([JeremiahChurch](https://github.com/JeremiahChurch)) - Avoid early connection [\#39](https://github.com/rails-on-services/apartment/pull/39) ([fsateler](https://github.com/fsateler)) ## [v2.6.0](https://github.com/rails-on-services/apartment/tree/v2.6.0) (2020-05-14) @@ -88,13 +96,13 @@ - Error Dropping Tenant [\#46](https://github.com/rails-on-services/apartment/issues/46) - After switch callback not working with nil argument [\#42](https://github.com/rails-on-services/apartment/issues/42) - Add tenant info to console boot? [\#41](https://github.com/rails-on-services/apartment/issues/41) -- Custom Console deprecation warning [\#37](https://github.com/rails-on-services/apartment/issues/37) - Support configuration for skip checking of schema existence before switching [\#26](https://github.com/rails-on-services/apartment/issues/26) **Merged pull requests:** - \[Resolves \#37\] Custom console deprecation warning [\#49](https://github.com/rails-on-services/apartment/pull/49) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare Release 2.6.0 [\#48](https://github.com/rails-on-services/apartment/pull/48) ([rpbaltazar](https://github.com/rpbaltazar)) +- Add console welcome message [\#47](https://github.com/rails-on-services/apartment/pull/47) ([JeremiahChurch](https://github.com/JeremiahChurch)) - \[Resolves \#26\] Support configuration for skip checking of schema existence before switching [\#45](https://github.com/rails-on-services/apartment/pull/45) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#42\] After switch callback not working with nil argument [\#43](https://github.com/rails-on-services/apartment/pull/43) ([rpbaltazar](https://github.com/rpbaltazar)) @@ -126,7 +134,6 @@ - \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Chore\] refactored files to their names [\#29](https://github.com/rails-on-services/apartment/pull/29) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] When manually switching the connection it resets the search path [\#28](https://github.com/rails-on-services/apartment/pull/28) ([rpbaltazar](https://github.com/rpbaltazar)) -- \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) - Support rails 6.1 [\#7](https://github.com/rails-on-services/apartment/pull/7) ([jean-francois-labbe](https://github.com/jean-francois-labbe)) ## [2.4.0](https://github.com/rails-on-services/apartment/tree/2.4.0) (2020-04-01) @@ -151,6 +158,7 @@ - Cleanup travis matrix [\#23](https://github.com/rails-on-services/apartment/pull/23) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare v2.4.0 Release [\#22](https://github.com/rails-on-services/apartment/pull/22) ([rpbaltazar](https://github.com/rpbaltazar)) - Updated readme badges [\#21](https://github.com/rails-on-services/apartment/pull/21) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) - Rescuing ActiveRecord::NoDatabaseError when dropping tenants [\#19](https://github.com/rails-on-services/apartment/pull/19) ([rpbaltazar](https://github.com/rpbaltazar)) - Skip init if we're running webpacker:compile [\#18](https://github.com/rails-on-services/apartment/pull/18) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#14\] Add console info about tenants and fast switches [\#17](https://github.com/rails-on-services/apartment/pull/17) ([rpbaltazar](https://github.com/rpbaltazar)) From 3068d91bd26ad0e513951cd80e58b9e7a68f116c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 12:57:55 +0800 Subject: [PATCH 196/282] [#98] attempt to push to master the changelog and cherry pick it to development --- .github/workflows/changelog.yml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 0726d2ec..3c569d62 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -33,9 +33,23 @@ jobs: git config --local user.name "$ACTION_USERNAME" git add CHANGELOG.md && git commit -m 'Updated CHANGELOG.md' && echo ::set-env name=push::1 || echo "No changes to CHANGELOG.md" - - name: Push changes + - name: Push changelog to master if: env.push == 1 uses: ad-m/github-push-action@master with: github_token: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} - branch: development + branch: master + + - name: Cherry-pick changelog to development + if: env.push == 1 + env: + ACTION_EMAIL: action@github.com + ACTION_USERNAME: GitHub Action + run: | + git config --local user.email "$ACTION_EMAIL" + git config --local user.name "$ACTION_USERNAME" + commit_hash = git show HEAD | egrep commit\ .+$ | cut -d' ' -f2 + git checkout development + git pull + git cherry-pick $commit_hash + git push From ee676b0f8500b8e1e812475b627996229f2b56ee Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 12:59:04 +0800 Subject: [PATCH 197/282] [#98] fixed setting of commit_hash var --- .github/workflows/changelog.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 3c569d62..c23e4ea3 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -48,7 +48,7 @@ jobs: run: | git config --local user.email "$ACTION_EMAIL" git config --local user.name "$ACTION_USERNAME" - commit_hash = git show HEAD | egrep commit\ .+$ | cut -d' ' -f2 + commit_hash=`git show HEAD | egrep commit\ .+$ | cut -d' ' -f2` git checkout development git pull git cherry-pick $commit_hash From baa994c80d427369895ccf333cc28bb746b5f318 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 17 Jul 2020 05:04:31 +0000 Subject: [PATCH 198/282] Updated CHANGELOG.md --- CHANGELOG.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbc6eed3..8a0b7741 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,15 @@ ## [Unreleased](https://github.com/rails-on-services/apartment/tree/HEAD) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.1...HEAD) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.2...HEAD) + +**Closed issues:** + +- Improve changelog automatic generation [\#98](https://github.com/rails-on-services/apartment/issues/98) + +## [v2.7.2](https://github.com/rails-on-services/apartment/tree/v2.7.2) (2020-07-17) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.1...v2.7.2) **Implemented enhancements:** @@ -134,6 +142,7 @@ - \[Resolves \#31\] Add latest ruby verisons to test matrix [\#32](https://github.com/rails-on-services/apartment/pull/32) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Chore\] refactored files to their names [\#29](https://github.com/rails-on-services/apartment/pull/29) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#27\] When manually switching the connection it resets the search path [\#28](https://github.com/rails-on-services/apartment/pull/28) ([rpbaltazar](https://github.com/rpbaltazar)) +- \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) - Support rails 6.1 [\#7](https://github.com/rails-on-services/apartment/pull/7) ([jean-francois-labbe](https://github.com/jean-francois-labbe)) ## [2.4.0](https://github.com/rails-on-services/apartment/tree/2.4.0) (2020-04-01) @@ -158,7 +167,6 @@ - Cleanup travis matrix [\#23](https://github.com/rails-on-services/apartment/pull/23) ([rpbaltazar](https://github.com/rpbaltazar)) - Prepare v2.4.0 Release [\#22](https://github.com/rails-on-services/apartment/pull/22) ([rpbaltazar](https://github.com/rpbaltazar)) - Updated readme badges [\#21](https://github.com/rails-on-services/apartment/pull/21) ([rpbaltazar](https://github.com/rpbaltazar)) -- \[Resolves \#11\] Remove old ruby and rails versions from the supported versions [\#20](https://github.com/rails-on-services/apartment/pull/20) ([rpbaltazar](https://github.com/rpbaltazar)) - Rescuing ActiveRecord::NoDatabaseError when dropping tenants [\#19](https://github.com/rails-on-services/apartment/pull/19) ([rpbaltazar](https://github.com/rpbaltazar)) - Skip init if we're running webpacker:compile [\#18](https://github.com/rails-on-services/apartment/pull/18) ([rpbaltazar](https://github.com/rpbaltazar)) - \[Resolves \#14\] Add console info about tenants and fast switches [\#17](https://github.com/rails-on-services/apartment/pull/17) ([rpbaltazar](https://github.com/rpbaltazar)) From 0b624d6e8147ae0007041318045bb9f0d189abdd Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Mon, 26 Oct 2020 19:27:13 -0300 Subject: [PATCH 199/282] Revert unsafe initializer --- lib/apartment/railtie.rb | 39 ++++++++++++++++----------------------- lib/apartment/tenant.rb | 15 --------------- 2 files changed, 16 insertions(+), 38 deletions(-) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index e3324bb4..ff534e20 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -6,6 +6,7 @@ module Apartment class Railtie < Rails::Railtie + # # Set up our default config options # Do this before the app initializers run so we don't override custom settings @@ -25,28 +26,23 @@ class Railtie < Rails::Railtie ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a end - # Make sure Apartment is reconfigured when the code is reloaded + # Hook into ActionDispatch::Reloader to ensure Apartment is properly initialized + # Note that this doens't entirely work as expected in Development, because this is called before classes are reloaded + # See the middleware/console declarations below to help with this. Hope to fix that soon. + # config.to_prepare do - Apartment::Tenant.reload! - end + next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } + next if ARGV.any? { |arg| arg == 'webpacker:compile' } - # - # Ensure that Apartment::Tenant.init is called when - # a new connection is requested. - # - module ApartmentInitializer - def connection - super.tap do - Apartment::Tenant.init_once + begin + Apartment.connection_class.connection_pool.with_connection do + Apartment::Tenant.init end - end - - def arel_table - Apartment::Tenant.init_once - super + rescue ::ActiveRecord::NoDatabaseError + # Since `db:create` and other tasks invoke this block from Rails 5.2.0, + # we need to swallow the error to execute `db:create` properly. end end - ActiveRecord::Base.singleton_class.prepend ApartmentInitializer # # Ensure rake tasks are loaded @@ -57,10 +53,8 @@ def arel_table end # - # The following initializers are a workaround to the fact that I can't - # properly hook into the rails reloader - # Note this is technically valid for any environment where cache_classes - # is false, for us, it's just development + # The following initializers are a workaround to the fact that I can't properly hook into the rails reloader + # Note this is technically valid for any environment where cache_classes is false, for us, it's just development # if Rails.env.development? @@ -69,8 +63,7 @@ def arel_table app.config.middleware.use Apartment::Reloader end - # Overrides reload! to also call Apartment::Tenant.init as well so that the - # reloaded classes have the proper table_names + # Overrides reload! to also call Apartment::Tenant.init as well so that the reloaded classes have the proper table_names console do require 'apartment/console' end diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 72a222ff..32f69ca7 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -15,20 +15,6 @@ module Tenant attr_writer :config - def init_once - return if @already_initialized - - # To avoid infinite loops in work init is doing, - # we need to set @already_initialized to true - # before init is called - @already_initialized = true - init - end - - def reinitialize - @already_initialized = false - end - # Fetch the proper multi-tenant adapter based on Rails config # # @return {subclass of Apartment::AbstractAdapter} @@ -63,7 +49,6 @@ def adapter # def reload!(config = nil) Thread.current[:apartment_adapter] = nil - reinitialize @config = config end From 3c77ca2f5700c71cb7ccf630832b488780d43be4 Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Wed, 28 Oct 2020 14:11:30 -0300 Subject: [PATCH 200/282] Inherit from correct class --- lib/apartment/active_record/log_subscriber.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb index da5430d1..45d3772d 100644 --- a/lib/apartment/active_record/log_subscriber.rb +++ b/lib/apartment/active_record/log_subscriber.rb @@ -2,7 +2,7 @@ module ActiveRecord # Supports the logging configuration to prepend the database and schema in the ActiveRecord log - class LogSubscriber + class LogSubscriber < ActiveSupport::LogSubscriber def apartment_log return unless Apartment.active_record_log From e21ce12b5af17389e52d43df4c3c6d99817b9004 Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Wed, 28 Oct 2020 14:12:16 -0300 Subject: [PATCH 201/282] Fix test, remove unneeded test now that code was reverted --- spec/examples/generic_adapter_examples.rb | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index a81c26bf..b46e4da4 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -22,15 +22,7 @@ .instance_variable_get(:@queue) .size - expect(num_available_connections).to eq(0) - end - - # NOTE: Bug report #92 - when the adapter is set before the railtie is actually run, the adapter class might be - # incorrect. This tests intends to assure that the railtie init resets the adapter to the correct one - it 'ensures apartment_adapter is properly set during init' do - Thread.current[:apartment_adapter] = Apartment::Adapters::AbstractAdapter.new(config) - Apartment::Railtie.config.to_prepare_blocks.map(&:call) - expect(Apartment::Tenant.adapter.class.name).to eq subject.class.name + expect(num_available_connections).to eq(1) end end From baa99755b219eaacb05463790493067a9dca4b64 Mon Sep 17 00:00:00 2001 From: Pedro Nascimento Date: Wed, 28 Oct 2020 14:16:51 -0300 Subject: [PATCH 202/282] Allow rails to be initialized without connecting to the database --- README.md | 11 +++++++++++ lib/apartment/railtie.rb | 1 + spec/examples/generic_adapter_examples.rb | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/README.md b/README.md index b1adea78..f296892c 100644 --- a/README.md +++ b/README.md @@ -594,6 +594,17 @@ module Apartment end ``` +## Running rails console without a connection + +Before this fork, running rails with the gem installed would connect to the database +which is different than the default behavior. To disable this initial +connection, just run with `APARTMENT_DISABLE_INIT` set to something: + +```shell +$ APARTMENT_DISABLE_INIT=true DATABASE_URL=postgresql://localhost:1234/buk_development bin/rails runner 'puts 1' +# 1 +``` + ## Contributing * In both `spec/dummy/config` and `spec/config`, you will see `database.yml.sample` files diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index ff534e20..c7d8f6b5 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -33,6 +33,7 @@ class Railtie < Rails::Railtie config.to_prepare do next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } next if ARGV.any? { |arg| arg == 'webpacker:compile' } + next if ENV["APARTMENT_DISABLE_INIT"] begin Apartment.connection_class.connection_pool.with_connection do diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index b46e4da4..767b122c 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -24,6 +24,24 @@ expect(num_available_connections).to eq(1) end + + it 'should not connect if env var is set' do + ENV["APARTMENT_DISABLE_INIT"] = "true" + begin + ActiveRecord::Base.connection_pool.disconnect! + + Apartment::Railtie.config.to_prepare_blocks.map(&:call) + + num_available_connections = Apartment.connection_class.connection_pool + .instance_variable_get(:@available) + .instance_variable_get(:@queue) + .size + + expect(num_available_connections).to eq(0) + ensure + ENV.delete("APARTMENT_DISABLE_INIT") + end + end end # From 6db829ef89c4e7d242991f82912b519cb5a3bcdc Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 13:16:54 +0800 Subject: [PATCH 203/282] [#98] new approach --- .github/workflows/changelog.yml | 42 ++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 17 deletions(-) diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index c23e4ea3..ecf5c1bf 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -33,23 +33,31 @@ jobs: git config --local user.name "$ACTION_USERNAME" git add CHANGELOG.md && git commit -m 'Updated CHANGELOG.md' && echo ::set-env name=push::1 || echo "No changes to CHANGELOG.md" - - name: Push changelog to master - if: env.push == 1 - uses: ad-m/github-push-action@master - with: - github_token: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} - branch: master - - - name: Cherry-pick changelog to development + - name: Push changes if: env.push == 1 env: - ACTION_EMAIL: action@github.com - ACTION_USERNAME: GitHub Action + # CI_USER: ${{ secrets.YOUR_GITHUB_USER }} + CI_TOKEN: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} run: | - git config --local user.email "$ACTION_EMAIL" - git config --local user.name "$ACTION_USERNAME" - commit_hash=`git show HEAD | egrep commit\ .+$ | cut -d' ' -f2` - git checkout development - git pull - git cherry-pick $commit_hash - git push + git push "https://$GITHUB_ACTOR:$CI_TOKEN@github.com/$GITHUB_REPOSITORY.git" HEAD:master + + # - name: Push changelog to master + # if: env.push == 1 + # uses: ad-m/github-push-action@master + # with: + # github_token: ${{ secrets.CHANGELOG_GITHUB_TOKEN }} + # branch: master + + # - name: Cherry-pick changelog to development + # if: env.push == 1 + # env: + # ACTION_EMAIL: action@github.com + # ACTION_USERNAME: GitHub Action + # run: | + # git config --local user.email "$ACTION_EMAIL" + # git config --local user.name "$ACTION_USERNAME" + # commit_hash=`git show HEAD | egrep commit\ .+$ | cut -d' ' -f2` + # git checkout development + # git pull + # git cherry-pick $commit_hash + # git push From 2087f7afaf040d041f672a35e1c452eda59c9aae Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 12 Jul 2020 15:37:58 +0800 Subject: [PATCH 204/282] [#86] ensure listed tenants are created before trying to migrate them or seed them --- lib/apartment/tasks/task_helper.rb | 8 ++++++++ lib/tasks/apartment.rake | 11 ++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index 84257b9a..3940e8cd 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -29,5 +29,13 @@ def self.warn_if_tenants_empty Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this. WARNING end + + def self.create_tenant(tenant_name) + begin + Apartment::Tenant.create(tenant_name) + rescue Apartment::TenantExists => e + puts 'Tried to create already existing tenant' + end + end end end diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index f4583074..1ea98fed 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -10,12 +10,7 @@ apartment_namespace = namespace :apartment do Apartment::TaskHelper.warn_if_tenants_empty Apartment::TaskHelper.tenants.each do |tenant| - begin - puts("Creating #{tenant} tenant") - Apartment::Tenant.create(tenant) - rescue Apartment::TenantExists => e - puts e.message - end + Apartment::TaskHelper.create_tenant(tenant) end end @@ -36,6 +31,7 @@ apartment_namespace = namespace :apartment do Apartment::TaskHelper.warn_if_tenants_empty Apartment::TaskHelper.each_tenant do |tenant| begin + Apartment::TaskHelper.create_tenant(tenant) puts("Migrating #{tenant} tenant") Apartment::Migrator.migrate tenant rescue Apartment::TenantNotFound => e @@ -45,11 +41,12 @@ apartment_namespace = namespace :apartment do end desc 'Seed all tenants' - task seed: :create do + task :seed do Apartment::TaskHelper.warn_if_tenants_empty Apartment::TaskHelper.each_tenant do |tenant| begin + Apartment::TaskHelper.create_tenant(tenant) puts("Seeding #{tenant} tenant") Apartment::Tenant.switch(tenant) do Apartment::Tenant.seed From c80e57a7eda6163f151e67e00180d91a6fca9032 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 17 Jul 2020 01:07:58 +0800 Subject: [PATCH 205/282] [#86] addressed rubocop --- lib/apartment/tasks/task_helper.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index 3940e8cd..95d1d236 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -31,11 +31,9 @@ def self.warn_if_tenants_empty end def self.create_tenant(tenant_name) - begin - Apartment::Tenant.create(tenant_name) - rescue Apartment::TenantExists => e - puts 'Tried to create already existing tenant' - end + Apartment::Tenant.create(tenant_name) + rescue Apartment::TenantExists => e + puts "Tried to create already existing tenant: #{e}" end end end From fa45a93f7496c23a645654bed445bca066f03b5b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Sun, 14 Jun 2020 15:40:50 +0800 Subject: [PATCH 206/282] using transaction --- lib/apartment/adapters/postgresql_adapter.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 17cbb892..c762fc30 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -97,7 +97,11 @@ def tenant_exists?(tenant) end def create_tenant_command(conn, tenant) - conn.execute(%(CREATE SCHEMA "#{tenant}")) + schema = %(BEGIN; + CREATE SCHEMA "#{tenant}"; + COMMIT;) + + conn.execute(schema) end # Generate the final search path to set including persistent_schemas From 6b58e19ed2fe6c902f3c36ad152a43924a23064d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Mon, 15 Jun 2020 09:15:14 +0800 Subject: [PATCH 207/282] indentation --- lib/apartment/adapters/postgresql_adapter.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index c762fc30..eb660282 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -98,8 +98,8 @@ def tenant_exists?(tenant) def create_tenant_command(conn, tenant) schema = %(BEGIN; - CREATE SCHEMA "#{tenant}"; - COMMIT;) + CREATE SCHEMA "#{tenant}"; + COMMIT;) conn.execute(schema) end From 547ee9e90a7466520108bb00d520b0395d4bc5ad Mon Sep 17 00:00:00 2001 From: Gabo Date: Thu, 8 Oct 2020 18:45:14 -0500 Subject: [PATCH 208/282] Add creating tenant message again --- lib/apartment/tasks/task_helper.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index 95d1d236..6065c953 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -31,6 +31,7 @@ def self.warn_if_tenants_empty end def self.create_tenant(tenant_name) + puts("Creating #{tenant_name} tenant") Apartment::Tenant.create(tenant_name) rescue Apartment::TenantExists => e puts "Tried to create already existing tenant: #{e}" From a5d47ad34414f2cf625e5409b9a0d7be7ed1e2b0 Mon Sep 17 00:00:00 2001 From: Gabo Date: Thu, 8 Oct 2020 18:47:39 -0500 Subject: [PATCH 209/282] Add rollback transaction for postgres, and use it when failed to create schema --- lib/apartment/adapters/abstract_adapter.rb | 4 ++++ lib/apartment/adapters/postgresql_adapter.rb | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 8ca4f308..1cbd5947 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -164,6 +164,10 @@ def create_tenant(tenant) create_tenant_command(conn, tenant) end rescue *rescuable_exceptions => e + # rollback if unable to create + with_neutral_connection(tenant) do |conn| + rollback_transaction(conn) + end raise_create_tenant_error!(tenant, e) end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index eb660282..f657ed99 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -104,6 +104,10 @@ def create_tenant_command(conn, tenant) conn.execute(schema) end + def rollback_transaction(conn) + conn.execute("ROLLBACK;") + end + # Generate the final search path to set including persistent_schemas # def full_search_path From 8612c51be99f003177f82d31df431c55ab6260a9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 10 Nov 2020 18:38:47 +0800 Subject: [PATCH 210/282] rollback only on postgresql --- lib/apartment/adapters/abstract_adapter.rb | 4 ---- lib/apartment/adapters/postgresql_adapter.rb | 3 +++ spec/examples/generic_adapter_custom_configuration_example.rb | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 1cbd5947..8ca4f308 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -164,10 +164,6 @@ def create_tenant(tenant) create_tenant_command(conn, tenant) end rescue *rescuable_exceptions => e - # rollback if unable to create - with_neutral_connection(tenant) do |conn| - rollback_transaction(conn) - end raise_create_tenant_error!(tenant, e) end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index f657ed99..7a223813 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -102,6 +102,9 @@ def create_tenant_command(conn, tenant) COMMIT;) conn.execute(schema) + rescue *rescuable_exceptions => e + rollback_transaction(conn) + raise e end def rollback_transaction(conn) diff --git a/spec/examples/generic_adapter_custom_configuration_example.rb b/spec/examples/generic_adapter_custom_configuration_example.rb index 5abe5029..2ad7ee20 100644 --- a/spec/examples/generic_adapter_custom_configuration_example.rb +++ b/spec/examples/generic_adapter_custom_configuration_example.rb @@ -29,7 +29,7 @@ receive(:establish_connection).with(expected_args).and_call_original ) - # because we dont have another server to connect to it errors + # because we don't have another server to connect to it errors # what matters is establish_connection receives proper args expect { subject.create(custom_tenant_name) }.to raise_error(Apartment::TenantExists) end From a219d58ed7a9a327a01c1561b027ecce1354e446 Mon Sep 17 00:00:00 2001 From: Thorben Starsy Date: Mon, 23 Nov 2020 23:07:47 +0100 Subject: [PATCH 211/282] Relaxes requirements on Rails to make it compatible with Rails 6.1 --- ros-apartment.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ros-apartment.gemspec b/ros-apartment.gemspec index 5c01be69..7c59a6ba 100644 --- a/ros-apartment.gemspec +++ b/ros-apartment.gemspec @@ -27,7 +27,7 @@ Gem::Specification.new do |s| s.homepage = 'https://github.com/rails-on-services/apartment' s.licenses = ['MIT'] - s.add_dependency 'activerecord', '>= 5.0.0', '< 6.1' + s.add_dependency 'activerecord', '>= 5.0.0', '< 6.2' s.add_dependency 'parallel', '< 2.0' s.add_dependency 'public_suffix', '>= 2.0.5', '< 5.0' s.add_dependency 'rack', '>= 1.3.6', '< 3.0' From 9a9308ede4e5aa1b2ffff9397c0feebf55c76465 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 15 Dec 2020 16:08:50 +0800 Subject: [PATCH 212/282] [#123] check if there is an open transaction and if yes, dont create a new one --- lib/apartment/adapters/postgresql_adapter.rb | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 7a223813..fd2ea683 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -97,11 +97,16 @@ def tenant_exists?(tenant) end def create_tenant_command(conn, tenant) - schema = %(BEGIN; - CREATE SCHEMA "#{tenant}"; - COMMIT;) - - conn.execute(schema) + # NOTE: This was causing some tests to fail because of the database strategy for rspec + if ActiveRecord::Base.connection.open_transactions > 0 + conn.execute(%(CREATE SCHEMA "#{tenant}")) + else + schema = %(BEGIN; + CREATE SCHEMA "#{tenant}"; + COMMIT;) + + conn.execute(schema) + end rescue *rescuable_exceptions => e rollback_transaction(conn) raise e From d6ba126eeb82919ed6c0de8a3142ecc02799c083 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Tue, 15 Dec 2020 17:57:53 +0800 Subject: [PATCH 213/282] copied active record logger to apartment and editing it instead of monkeypatch --- lib/apartment.rb | 2 +- lib/apartment/active_record/log_subscriber.rb | 44 ------ lib/apartment/log_subscriber.rb | 136 ++++++++++++++++++ lib/apartment/railtie.rb | 8 ++ 4 files changed, 145 insertions(+), 45 deletions(-) delete mode 100644 lib/apartment/active_record/log_subscriber.rb create mode 100644 lib/apartment/log_subscriber.rb diff --git a/lib/apartment.rb b/lib/apartment.rb index 6bca1cc8..59a61cd1 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -6,7 +6,7 @@ require 'active_record' require 'apartment/tenant' -require_relative 'apartment/active_record/log_subscriber' +require_relative 'apartment/log_subscriber' if ActiveRecord.version.release >= Gem::Version.new('6.0') require_relative 'apartment/active_record/connection_handling' diff --git a/lib/apartment/active_record/log_subscriber.rb b/lib/apartment/active_record/log_subscriber.rb deleted file mode 100644 index 45d3772d..00000000 --- a/lib/apartment/active_record/log_subscriber.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true - -module ActiveRecord - # Supports the logging configuration to prepend the database and schema in the ActiveRecord log - class LogSubscriber < ActiveSupport::LogSubscriber - def apartment_log - return unless Apartment.active_record_log - - database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) - schema = nil - unless Apartment.connection.schema_search_path.nil? - schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", - ActiveSupport::LogSubscriber::YELLOW, true) - end - "#{database}#{schema}" - end - - def payload_binds(binds, type_casted_binds) - return unless (binds || []).empty? - - casted_params = type_casted_binds(type_casted_binds) - ' ' + binds.zip(casted_params).map { |attr, value| render_bind(attr, value) }.inspect - end - - def sql(event) - self.class.runtime += event.duration - return unless logger.debug? - - payload = event.payload - - return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) - - name = "#{payload[:name]} (#{event.duration.round(1)}ms)" - name = "CACHE #{name}" if payload[:cached] - sql = payload[:sql] - binds = payload_binds(payload[:binds], payload[:type_casted_binds]) - - name = colorize_payload_name(name, payload[:name]) - sql = color(sql, sql_color(sql), true) if colorize_logging - - debug " #{apartment_log}#{name} #{sql}#{binds}" - end - end -end diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb new file mode 100644 index 00000000..38e3b412 --- /dev/null +++ b/lib/apartment/log_subscriber.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true + +module Apartment + class LogSubscriber < ActiveSupport::LogSubscriber + IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"] + + class_attribute :backtrace_cleaner, default: ActiveSupport::BacktraceCleaner.new + + def self.runtime=(value) + ActiveRecord::RuntimeRegistry.sql_runtime = value + end + + def self.runtime + ActiveRecord::RuntimeRegistry.sql_runtime ||= 0 + end + + def self.reset_runtime + rt, self.runtime = runtime, 0 + rt + end + + def sql(event) + self.class.runtime += event.duration + return unless logger.debug? + + payload = event.payload + + return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) + + name = "#{payload[:name]} (#{event.duration.round(1)}ms)" + name = "CACHE #{name}" if payload[:cached] + sql = payload[:sql] + binds = nil + + if payload[:binds]&.any? + casted_params = type_casted_binds(payload[:type_casted_binds]) + + binds = [] + payload[:binds].each_with_index do |attr, i| + binds << render_bind(attr, casted_params[i]) + end + binds = binds.inspect + binds.prepend(" ") + end + + name = colorize_payload_name(name, payload[:name]) + sql = color(sql, sql_color(sql), true) if colorize_logging + + debug " #{apartment_log}#{name} #{sql}#{binds}" + end + + private + + def apartment_log + database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) + schema = nil + unless Apartment.connection.schema_search_path.nil? + schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", + ActiveSupport::LogSubscriber::YELLOW, true) + end + "#{database}#{schema}" + end + + def type_casted_binds(casted_binds) + casted_binds.respond_to?(:call) ? casted_binds.call : casted_binds + end + + def render_bind(attr, value) + case attr + when ActiveModel::Attribute + if attr.type.binary? && attr.value + value = "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" + end + when Array + attr = attr.first + else + attr = nil + end + + [attr&.name, value] + end + + def colorize_payload_name(name, payload_name) + if payload_name.blank? || payload_name == "SQL" # SQL vs Model Load/Exists + color(name, MAGENTA, true) + else + color(name, CYAN, true) + end + end + + def sql_color(sql) + case sql + when /\A\s*rollback/mi + RED + when /select .*for update/mi, /\A\s*lock/mi + WHITE + when /\A\s*select/i + BLUE + when /\A\s*insert/i + GREEN + when /\A\s*update/i + YELLOW + when /\A\s*delete/i + RED + when /transaction\s*\Z/i + CYAN + else + MAGENTA + end + end + + def logger + ActiveRecord::Base.logger + end + + def debug(progname = nil, &block) + return unless super + + if ActiveRecord::Base.verbose_query_logs + log_query_source + end + end + + def log_query_source + source = extract_query_source_location(caller) + + if source + logger.debug(" ↳ #{source}") + end + end + + def extract_query_source_location(locations) + backtrace_cleaner.clean(locations.lazy).first + end + end +end diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index c7d8f6b5..18b47644 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -45,6 +45,14 @@ class Railtie < Rails::Railtie end end + config.after_initialize do |app| + # NOTE: Load the custom log subscriber if enabled + if Apartment.active_record_log + ActiveSupport::Notifications.unsubscribe 'sql.active_record' + Apartment::LogSubscriber.attach_to :active_record + end + end + # # Ensure rake tasks are loaded # From 4e8c13d5d9aa7e4019e1fbb839680f80c480d907 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 16 Dec 2020 09:39:00 +0800 Subject: [PATCH 214/282] inheriting and reducing overwritting --- lib/apartment/log_subscriber.rb | 123 ++------------------------------ 1 file changed, 7 insertions(+), 116 deletions(-) diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb index 38e3b412..cb733f3c 100644 --- a/lib/apartment/log_subscriber.rb +++ b/lib/apartment/log_subscriber.rb @@ -1,56 +1,19 @@ # frozen_string_literal: true module Apartment - class LogSubscriber < ActiveSupport::LogSubscriber - IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"] - - class_attribute :backtrace_cleaner, default: ActiveSupport::BacktraceCleaner.new - - def self.runtime=(value) - ActiveRecord::RuntimeRegistry.sql_runtime = value - end - - def self.runtime - ActiveRecord::RuntimeRegistry.sql_runtime ||= 0 - end - - def self.reset_runtime - rt, self.runtime = runtime, 0 - rt - end - + class LogSubscriber < ActiveRecord::LogSubscriber def sql(event) - self.class.runtime += event.duration - return unless logger.debug? - - payload = event.payload - - return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) - - name = "#{payload[:name]} (#{event.duration.round(1)}ms)" - name = "CACHE #{name}" if payload[:cached] - sql = payload[:sql] - binds = nil - - if payload[:binds]&.any? - casted_params = type_casted_binds(payload[:type_casted_binds]) + super(event) + end - binds = [] - payload[:binds].each_with_index do |attr, i| - binds << render_bind(attr, casted_params[i]) - end - binds = binds.inspect - binds.prepend(" ") - end + private - name = colorize_payload_name(name, payload[:name]) - sql = color(sql, sql_color(sql), true) if colorize_logging + def debug(progname = nil, &block) + progname = " #{apartment_log}#{progname}" unless progname.nil? - debug " #{apartment_log}#{name} #{sql}#{binds}" + super(progname, &block) end - private - def apartment_log database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) schema = nil @@ -60,77 +23,5 @@ def apartment_log end "#{database}#{schema}" end - - def type_casted_binds(casted_binds) - casted_binds.respond_to?(:call) ? casted_binds.call : casted_binds - end - - def render_bind(attr, value) - case attr - when ActiveModel::Attribute - if attr.type.binary? && attr.value - value = "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" - end - when Array - attr = attr.first - else - attr = nil - end - - [attr&.name, value] - end - - def colorize_payload_name(name, payload_name) - if payload_name.blank? || payload_name == "SQL" # SQL vs Model Load/Exists - color(name, MAGENTA, true) - else - color(name, CYAN, true) - end - end - - def sql_color(sql) - case sql - when /\A\s*rollback/mi - RED - when /select .*for update/mi, /\A\s*lock/mi - WHITE - when /\A\s*select/i - BLUE - when /\A\s*insert/i - GREEN - when /\A\s*update/i - YELLOW - when /\A\s*delete/i - RED - when /transaction\s*\Z/i - CYAN - else - MAGENTA - end - end - - def logger - ActiveRecord::Base.logger - end - - def debug(progname = nil, &block) - return unless super - - if ActiveRecord::Base.verbose_query_logs - log_query_source - end - end - - def log_query_source - source = extract_query_source_location(caller) - - if source - logger.debug(" ↳ #{source}") - end - end - - def extract_query_source_location(locations) - backtrace_cleaner.clean(locations.lazy).first - end end end From cef40ecf271a2cdba32246f87a92bc1e37489eba Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 16 Dec 2020 10:49:41 +0800 Subject: [PATCH 215/282] added missing information to the change log --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a0b7741..a2d9fc78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,19 @@ [Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.2...HEAD) +**Implemented enhancements:** + +- Uses a transaction to create a tenant [\#66](https://github.com/rails-on-services/apartment/issues/66) + +**Fixed bugs:** + +- Fix seeding errors [\#86](https://github.com/rails-on-services/apartment/issues/86) +- When tests run in a transaction, new tenants in tests fail to create [\#123](https://github.com/rails-on-services/apartment/issues/123) + **Closed issues:** - Improve changelog automatic generation [\#98](https://github.com/rails-on-services/apartment/issues/98) +- Relaxes dependencies to allow rails 6.1 [\#121](https://github.com/rails-on-services/apartment/issues/121) ## [v2.7.2](https://github.com/rails-on-services/apartment/tree/v2.7.2) (2020-07-17) From 02044bc09cf0b1c66f2620badc4341c56d9b41e8 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 16 Dec 2020 21:53:20 +0800 Subject: [PATCH 216/282] Updated changelog and readme --- CHANGELOG.md | 6 ++++++ README.md | 7 +++---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2d9fc78..345ae68e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,12 @@ - Fix seeding errors [\#86](https://github.com/rails-on-services/apartment/issues/86) - When tests run in a transaction, new tenants in tests fail to create [\#123](https://github.com/rails-on-services/apartment/issues/123) +- Reverted unsafe initializer - introduces the possibility of disabling the initial connection to the database via +environment variable. Relates to the following tickets/PRs: + - [#113](https://github.com/rails-on-services/apartment/issues/113) + - [#39](https://github.com/rails-on-services/apartment/pull/39) + - [#53](https://github.com/rails-on-services/apartment/pull/53) + - [#118](https://github.com/rails-on-services/apartment/pull/118) **Closed issues:** diff --git a/README.md b/README.md index f296892c..5704b97e 100644 --- a/README.md +++ b/README.md @@ -594,11 +594,10 @@ module Apartment end ``` -## Running rails console without a connection +## Running rails console without a connection to the database -Before this fork, running rails with the gem installed would connect to the database -which is different than the default behavior. To disable this initial -connection, just run with `APARTMENT_DISABLE_INIT` set to something: +By default, once apartment starts, it establishes a connection to the database. It is possible to +disable this initial connection, by running with `APARTMENT_DISABLE_INIT` set to something: ```shell $ APARTMENT_DISABLE_INIT=true DATABASE_URL=postgresql://localhost:1234/buk_development bin/rails runner 'puts 1' From 344b039dc8e17b4b58440c70aef873f45c071059 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Wed, 16 Dec 2020 22:29:00 +0800 Subject: [PATCH 217/282] Version Bump --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 8191b485..398dd80a 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.7.2' + VERSION = '2.8.0' end From 99ae4d7367734834390d9ce1fdeba8932f731f27 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 09:09:57 +0800 Subject: [PATCH 218/282] [#128] added config spec coverage. added missing require --- lib/apartment/log_subscriber.rb | 2 ++ spec/unit/config_spec.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb index cb733f3c..237bebf4 100644 --- a/lib/apartment/log_subscriber.rb +++ b/lib/apartment/log_subscriber.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require 'active_record/log_subscriber' + module Apartment class LogSubscriber < ActiveRecord::LogSubscriber def sql(event) diff --git a/spec/unit/config_spec.rb b/spec/unit/config_spec.rb index cceaa7e4..9adaf84c 100644 --- a/spec/unit/config_spec.rb +++ b/spec/unit/config_spec.rb @@ -50,6 +50,20 @@ def tenant_names_from_array(names) expect(Apartment.seed_after_create).to be true end + it 'should set tenant_presence_check' do + Apartment.configure do |config| + config.tenant_presence_check = true + end + expect(Apartment.tenant_presence_check).to be true + end + + it 'should set active_record_log' do + Apartment.configure do |config| + config.active_record_log = true + end + expect(Apartment.active_record_log).to be true + end + context 'databases' do let(:users_conf_hash) { { port: 5444 } } From 0f1c28c1bbe5444d282b960d829e73b6d2b00998 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 09:37:34 +0800 Subject: [PATCH 219/282] [#128] added log example to readme and config explanation --- README.md | 15 +++++++++++++++ documentation/images/log_example.png | Bin 0 -> 33355 bytes 2 files changed, 15 insertions(+) create mode 100644 documentation/images/log_example.png diff --git a/README.md b/README.md index 5704b97e..134655e6 100644 --- a/README.md +++ b/README.md @@ -338,6 +338,21 @@ Apartment.configure do |config| end ``` +### Additional logging information + +Enabling this configuration will output the database that the process is currently connected to as well as which +schemas are in the search path. This can be enabled by setting to true the `active_record_log` configuration. + +**Example log output:** + + + +```ruby +Apartment.configure do |config| + active_record_log = true +end +``` + ### Excluding models If you have some models that should always access the 'public' tenant, you can specify this by configuring Apartment using `Apartment.configure`. This will yield a config object for you. You can set excluded models like so: diff --git a/documentation/images/log_example.png b/documentation/images/log_example.png new file mode 100644 index 0000000000000000000000000000000000000000..71b0e7c0a9ee1e6df73c1ca459ff0826bb7e2d11 GIT binary patch literal 33355 zcmagGWmFtdur4~dOK=Hp2`<4kA-D#&!6mqRfB}NLTae%|xD1241cEcT6P&>%_{+WT zoptV8>zs3c?C$E_UsqS{UAtFxRdq+HtIFYEQeXlA02~GR&l&&#GV~uUjgIzyfb{=5`KC2O9{`X7D182?<%4jNi)K0xgT3M<%Fxo`-(vfpy)WFJCuyEA2!ORf z;+J*dQ+AJM_V)IU@CE}gP-jKNP&c>yU1X$?)NNjH9TFW~3i8Xwr0-uQwLCF$c9e~c zus^<+ly}}i`|Iv!;v0|R`vSa;0S_3O?}F74eq?(11l1TiQ!}EWFX_29Q0{@-D{|R(aR{DpG zKRm+1qWNzI{XfC@h(>0V|NZRz2T-V#=^t{~<0dQ&@Bcne2sL#$|I?iRzg*wW5}+g0 zShPL#^+o&-2J-)j0MK1T{huxAe*xodF}?#9cz^+BThjld+5K;>AT|f2|C@cPBMvtq z6T~0R(1eE3te8~+SI^At(-*56u9=9L1OlEt`~&Z=(uTJK4m0Pco!+_@SuxuDJv<3< z@OQgNfp{$}`(!NmRw)!QL)2bxPge|g+Ws*An(vhH7A;#47N{GSl6;*mO*qNDIa};= z#IiSf)u;ZNJvH}WbKAmo_u8N`mS^o;6EHh^mrhep->l$hQRXEIQ$2AjpMa&i><$$U(}qWH)0b8`+~G+m30lw*nsW*3Dz<`OSmIIX@g%AZc2nfyFOhXNr^7#~serEAK?-Z20Xg=j)~U9#6f) z^=3;klJk~+-?c1WALg)&wr{F8zOJs(%po|kS7!156`vI9j9JzY9s8Q(z}4M0vF>9b z9eN611BU_K6x5FADzZK_vvTM``(G|5cOm|Fd6l7Zy)C%oqKlgXq1AG-cxV00wRsMd zm;z*e%U~<6s8O$+Eyz;qm!W_fLJ$SYI)r5fair5(2uPdHS5N}kg z&`;M8m4gqxvJjd>t7p?$wDjD3DsQ8x)*H~PvZ9@tisp*`r%%!FB~8nc649zA%ZN)` zheM7Atzi}Rw!%AjbzR{$hfY`7)FdgfQ{&|&JBE{>Av@TEMxu)e`pI5m&J@2P^hv`MuF)wPM_LETeti{1Snd zF4LglO$xXR{F{sJwNz#0z?bU!1tqF*27ZFf;k(6DfU7*3eEZcYeIp*8BJ(A`b3LkR6>~&Mvd5 zkXT*`KM}0@3u0 z|J8)B)2wwto^gPaCN zi2dUZGq8Iy>fA9Rs0)?aJXj zVnh2N;GmUe_xqQZt#VGc&afifWeANuIfwtso(kWMG22mRSr=AEuHAZv;}{D>$wFb6 zlg0PZq+^roX3g&XQK)i2FZE5ywBN>OFX_smjKZ}Q4;7`|#>vMbsn>&`TbQItB$cw!AoTne@drj4yS+6LZN-}WCH62^_rmpL}`~bUc}(azNv;2c#XF( z`yq}_SzQ9JExW}cYbf4AK{rD|*L%LI+~Ncs4v{;<`cRs_9KU+6159%lLj8#5ruAKl~Yq!$el}DqonE_q}!Wx+s(xuoRh?#uCVyH+wv<`gpMK~|%23=%=bb7%~BZMM4hVyQ}Y zthN@pNN+p!ZyN^k-fF|L#W2$AIswOQ12;E9CE}@OyWJZ6&1iK`4!>YlSXg?D=0?7 z`|HY2uaEgyCs5U4{g1Z6;~OFy9~q=>c0{S1i$r4GK=xtSKQ04yAzxPtg=T7=)kP6_ zc0^(uf5O8JCQjcjJbpE8zZJEY+yUrjV0b;(9Xs|yPzc-^*a-e2qkI1ayvk-TmKe%f zOWMQy5}BAvmCD@X6rSeCX++=6b%JQD=nq?%e*N&jjgiSC21~=R{$i_AvMTyj=^Mxf~9L)U~DFJ4Kp1@G@FXb%^#(^w`fsrs1bUK49Dv4 zs7yO8_6ga+`;2HecxXMal4J7uqB9xDXIV}xK<8tijAJL5vhzmaU6D4;p=Rp?>_$h6 zdJ!*fF33^@zr}Ml;;0PmFaKaH(u^;`^OvQ(Z)0OXIv^ZkqI=i~p1E~IMCs^Ogy2#o z)XHSAb#&X;UL{F%9|bv>&5F3q3v8j&zaFa~*Qqer(ge?91pTIDwRQfK4@a z$`4`yqXWCMzzo|T5c?! zk4DAN_!s9mO2KKPQnP0>beDk9o2Acb(jkr?Y{uRqnXeHy@lefHuULbnt|u0dHiO!)S9gAKbb)upX|+0p@SQLfpRm-gD#BZGcb z=;&ifjPVR|$q4n2tAb|>GZ-e{NqqkJQx^Y%-A4;@luoNTpy;&$xeH8p;@Iz92Ig2p zwV~39Bv(!SJ(l;w?$!SO^1P#`n#9rQozw)sbDkwlkW27*Zp$oZ=LybA!|u5lslXyD z0*CjD2PEL)q(;EiTrNmAQ_-yQeQ<`c&}_8g?Q$p{r^lYwINOm#gV&lS`%@jjO#VugS^baw>3Md|_oDw5x6->~f| z_Od2$D)6|xSxf#*xzMNntZ~M*)H<1Gh?7~P#Ce^ve@uJBoX+EYgm7xKz?XgWL%xZPdLT* zQv8@p6}Cmfoi^e;fhL(WeWzPr)V2u4xFeI*E(DbVxP4#O&I~q!O`1s##Rp#$-XzX_ z&R5BmAy%f|@ZYyK?Dlfww^r9ecw!qeW2t{P6yI&wlcHmIhs1j&d0)LKH7W9SaNr(F zcsgzVu|6-wfpWfkD`n0TY&`Sbvp_`*Zsu<@+6=L~@BXnX;I^9J>DX2MMyR*={JSP~ z!@c`ybArwDKrbelcEF>Fm9OtumCDMSY%%Y1VU!adOLaQ^Q%&Jp^hLzqW5l2(`l9wY z$qPYV%VCV3D*UfP{Yz@~XM|_YM^$Ca3%}lH3Hbb#&AB{+1{DaI5CZTq2C{njVvcB|8G@89UYp z6zy`jzqfzRt|ttnLp`)J6gs0jUcVAMJR0Zs@cq@-?PG$W>Ap=KlmH%U=U?x!7Tt{v z`uy-z-bKsu$YI!ZO|!m#FKvHMTn#?DX6N~tWtrnjMrvi}d;Ui3?a|R2A}6HA__>ev z;|Rr#*(`74i4It+`iHWIsSYw{7+YIgo$Or|?d*RU&{|?!bNaF~TTV^=Z$G4nBG9?t z|Muk4#?kh42Fip^VbT;_XIO)pz!CU6E*#fQ5&)`XGkZH|D1$~6I+&JBw!uUvL+B}0 z^Qrpe$!92GZ7TZi$MPj!%`R2p7|mPBANgXTZUagemSksbZSjL$NXqS5!hE^aJL9woar@{Avv#@BgQZoEJ`o!ugT!8)`H zF*)mPzYJ`*Uv~pdAaCGuLiTAWk>QLUKA-k6(pf|IV6a+&uOFF=yXv1+vUK)eyEe~m zx1&kn?Bqgsd49D(;d4cQ@8|a0kkuwVbfHw_Dmo-zNv@ z-L?r9r|ud6C*46if1~b1W1L{4He&gXc4as!XWi~#j=z8IIETMjye_B;!ST}X&Ppb< zz<7Ty?=)cWQA4JwOHRX&{pT%+BQc2e# zGSp8^*pKMk$CBrEX*N*Gbqor;oUf;R=Bs!pu`2Zv&$Wr|TL5Q!koFBzcr9lAAz*>E zm~_`IU{#Y-s>?bB%mqIG7u#WA4eqong9;)M^>?inNi_DY`5p(I7`F!YcLi5#WX%l` zBA?98GhiY2T5`5s*k7v$#dBV9<#F!#<5tZ#%i z^ehkVLc6pybz|t;D4Y>BOsu!=)e+^?5rb=ZOY3~x3oJ&Bm#Vl+$%m(Jc;hna>XC57 zLu6imH^v|Rl(=em%I5@71=I+VXa28zI}Jn|#BTa`HV3jG-7x~P$|BK~NRA_^%bX?k`q~&IO+vH>*VeGgTZ2(?YY}rdKvek;UeC- zDzN{!IB(ncq_Qfuih|cqc8HXxJ#o54Hef7#B!hxLncmAL9dE%9iUfpin=8jJnX zd9rbP-Vssl4DPxuYkaZPj~1TNdp-T(QntqZgt}6t$FtB880W~kSUhny;uWNz5La!o zf!%&TL`Mx~6BnN*;as*2dVS>ehu_>7+^{uLi_gGWB&n@fau=t8uP^6Q^!~fVgSpe) zgv=gwG#fmMRe40@AsB8N9TgfbAbzxNGCL-SS)oCENrtu2lJp!@FD>{)V`<^SEHI z!XpNSn(X6+Gsv&X?)>L(@i^qGqo>c~7wIq#6#&Q=7{rdZ^YvKw~()@KPIb)+OMs^)JP(@vP|Kf_+cUMFQG4d@s` zUi>|Vr(fV=Y0h#pWk_tmu`@~Z)po>d~lVjzsMaDojpp(f2zNPIAgzt1Lw}@ z&#=^ejYto@4;F&1ww$r=>>p-bsfL$!k+=lSDiQ_wN6>fC|?+2en@EkUBxT3vguFJ^Ux1YgvD~&^)#bSlt>eG7&Y zXj0t67CsP}$$mD(Za-UWYa7OdUmn!FYBZ;57l%GYe-*D3&ha z%XFlGo{0t}%DaM7U^qo%k}ZRGE^M@Q=wg;d+|kwzMG0S&0%8{2V~}a)F8PqQkBem5 zljy9s;A9i2zxc~5QdltP)_IlK>q(*eLgd$*f>zspkM6t&lNgM>$<8HeY-7?E;&T~IkHU4Diwg7fu zQw_d7+8jQ9Oe?-aDyI_qW01p&50S@KT_*9}dP(oLF9A%T#p>BwsQqpAJax;K>Y?v^ zWrO(L^Fe^7uI__$KYaFzAm=HMD64j-?|mWD-)skf+ z@P*pW8J~7>liQ~x*=P;dekG?r78~El;0RDY?KorOgvr`u(uKz7s%rc$&xL$F4NY%+ zaa?e0kVy!S>w+B@wC+I%Ua*W3gw=j`@C>iLr#(6{b z>yfBCssfqtHV@CkLb=^h@+_{Q1(zmHOKS2Y4mS*b-zSj-9wgif zuQYQ4!(5WsCQD?nUbKD{%j)`~k%V}iMoz;|vwNjLBF7c7u~`cSmf2r8Bm+v_I4qOP*wVrb{N^<4!-Dov$uV z{tN%5jo4fZh9j7cFNsgw`WOKy20Gj1123z#)%?7Yd#ft&d;sdpI%pNQ?9H&NXx9{F8@AKE>BnnUYkk zw=NScDX;m)Y{1)m*ehyB6lzA3^7_Xz&J7E_Zy)&H9=T z6$^|ux&xzMf88=cYD{w%Sb~p|g5Q6Dyv3(V-ewlzMlOV2h&A-fcRL-mRp6#0_`TtajY6;b zaI|!6kdmUtpz>fY*uIzj;`QVT=daUV9M!&`FZ0G4JIXt)D))jTSFO7LP!apt318H= z>-0R$Yagz-+OTIMI*x{_20U0UR%*Au&7=@3NDFvA3bZTQ+f>d1#nY}6_9zF^eT=w! zN3GW?qSS~>rGe68dDObvElnG{yf>vBtQ>Xw@@VKd!D7hatXp9&K@82YDvPi1I(na5 z1#B<9eV{zn-g{WHJ4)H{?h>DyAoYQjwE)7B-3-Bi8zeMKJsq7kJvNNn?pM)1Rnd~h zP_>oaqa_HiVKl>fO!veC7&UAFKFjL8C*epI6CgfovUUHtZj+zu^9k*kZR#Q+$iN}! z{+IymJ}_wG0+CEqsAr)vpfccon>t!D{ls++02SKk4q`Ke`b3z|oqTaDBLbF)^7^wqQU^HGYHjgF>dgOt%ViFLHFQXrTpH%ecPz} z2vY}|u1YWYNv}JUG2F}uBmGCY?T$5Rr|&%%{D$IazsOy`PqF&iS$~UD6a=4ch~OYZ z|3u?ohrxg@O14CW?s)yC*Sx;(4lp_8`2V#_7tD4{S+XMeH}rNN1W zX}OL@I?EuQ8wlOuIgKzef33H^Lv5}d$9-|hYtUw5lnQEljSRwgDQ{z47X%@^yK7qN z=-B1Iyp!5*la2oz&C&Q#|DBKf7Anx>lu&kc7;{%-BeBW4St>VgAFJ5ENCc_hd0rHG zcaQIHm*mbZ70U=fe=p?@$ZB)_$cM0tcBgD^)$AayTwo;EO?az`|2I!TgwTVz)&4^; zoQ0eHi+fslNHX+ONo0LSje=)l^qetIm4XFEVr$ioAAuYJHKu{mVERfWmJYtpRn!Tz$CcRv&tiuC2GO-dmaAsNp zm{Rc;=6?$mIkay>;H#~lpH0|!u2A0%!BijyF>3dS&JmHW^M)U1Fw$|(lb0&H+ta(A zPHfFnaOR906NdAUt_N}OtbsAH61?nkO1HMu3l1^c(PoVNN%eCTV-*7Cb9avI0+Dnj zztRM>c?JbyqB8Tl4J=0W5a#YhRe7X7C5Z!Vhx#VnNMEEQ7Lf-I|*-Om5D(yX+&>ot)F{P0ijLFQt4J zyoPwB=!@gW4d%{K?XyiutLUl96aq&&T<#SlEZ&$xh?_k^(Wh9Ey92_RDUSRR6#h@* zcJ5eA?YpN(%SCsC)M$3#bso(tSPDud-A=$GMTIIVxQ&1q6rhSj?g-;qRtCOTapa@# ze}#yR2e(A;E-Ldl^AMR)o0a2{-#fPU8yDZ+r1PPp;k`m8m@2y;VitPOzihaJqDAzW z)Dj?Y*_evu37TWxxBd~!ztWr-1$5T~h>ok%wvT@MJo+IR-wQbW#{1SEI-adYQX$Dk z$cG8BNrc$WzFXcg$d2rdo(lV#=rll1_`l{O>AW zwP{dHC9V4=-&!*Ef7qKv^aw@1f@FaH2vFq6KmHL(7_+EL`smnZR34Zwfkbt%bZ2f~ z5?A-t{~DO%ZasP)xX_!tDSRPOH zD|nJF71IxnX-Vr6*J77av@L(BPnL~)PU>vCe|tl2>v_ZqPn22#nXdWe*^45d_nnHr zZ5tIrjUmq%Pa1xfZ}W3atEn6>EpDoqgUuh57#&58M;^EYfR%KWtZW!(RBuCH=5X3D z0Ve_fe2&w(A1rN>tEDJi%N}WdTr;Iy*EZ6!tA&Agj)%bKfA?lg_~#CncY}et5$`{I z(z)YmtAU)k{4laVo`?N2k}3x`SI_2r4}QKvFmXe>TpXI1=*KF!E>PEQR(ptO*$$Se zai1yD{fFRXWPj72YD8uM>xwu=3*wqQ)LhUVlWxY%Oe;+SHs$l4L1h&-ct?l3_b<3T zz3y}WE!aKan;<3fokc_}{-w*e1&%z-IB&mo);Kw^Wr&x& z)HMI$`8{0Fk*oCF<&<4im!uv{Qc1QEk1GgwRMm5WA-deGxi?i?Wnzy{#=FnX=E`TiOA`jkPqnn*XX(4GD= z)?2!f|Kg8U;FRaqNUe}DE zxCvB-O+OkH>igbz44uuV9R8Ls4D;QdL60xcGtm@GQ!E`s)Ybg`m!&Szy>?@rcvoBt zaMx#}^4YdrYm6iHpueYhI3#2ZtyU)-fou+Cghc8Iv=7JwHga52U8>_EzUO<&wIQ*wI>Pz+Qpy$qP|6F){>^)xjq@8#wT`B!3t8(^9I@o z9~d{E4ed7?^2o)hHjxth6URAzd8VVa8zYKn+;Uz24LOUBa>z5fEM6115nw?X2mRk2c8h3`h>#AxFhd8sw(&0@IM@^JA{(2cKcgLfq zI7FH&VlBf{Tw-%8OtB6)TH{Fx>EwJ*#{zYbd5QRIABD;_>vfIQe5ZeQx5e!PV*4ZM z$)1+=zRA?u%W=axB6*9D)ctwUn8Phgs~1c=z@b>r5(5!ds3|KOeO9AKn=zer=Gbs} z=F~vU)&$NLAQ4(7Y-ebol{)wKqWP|(NJGgO`}4QfpyJeiYxaPb^U~T{46l@RJ(g8;;$<}x8jD^O}Cg$0q+2$_uGYn{_{Z0 z@86OAsC^LG&5R7`lWap!M${pPZza_I%q`F{Oe!>Lwuk_&R zLH>RT(9KDC`}2-4Zc)3*xpTV0UXJwb!{$e|T!vAij&GAl7)D*gSg zK0w4yRqFgYoH-LnzU=APDA4@=i@INI5^epJ#YV91NP)y`^kB#Y(N1{5qxhpS{nW*` zxI6!owH7D!AYe21_s4aw;F7pOdPQB)-VyLbAG%xZ3kKMBWW?}C7V!^#$blI`UgMM6 zYL4G^$JA&$u`oWw^_ge|dLfP$XzDC8hR@KV5uPjw=%+?OV?OtimE|(*KJ|t^wT4%g2i`w&9fqdKixMKFJo~K8hT-g@$)}#RD zkSPI#z%Vu9Cov+vHr2qkLpPPXbW;uij`?gKsNLp_Y5?Es7Gv zye{3_yR~PeoE9k2gjnaxs%OnQ>|rE`=NcL-l}z_aeI&n-*gdQZ2!O|bL>9xY*JoO<> zwmaAytQ>AGSlph?JtN3GrWDDnM(Zcb%dobwouUm;t-?H)P-u9dE>2GnpddRcX_%Re zah*=2cdicwTG3-guz5H1!`n#q2?*u{t48(8w2ypU(v?zHS_4l93B0(1ojpTKImwhQ{56NKlyqX@}*z_2xxel#El z7hCi}<_R7P`>((Rz?u(jwy0*$L z1aVFclawFHrw#E3M`JUvA9ih+WK`D?Cy@pjHP*E`?56Iei!HUfw>CJ_+Uq3}K=|SX z@;Lu`eZqj&@$$37P5Z*XU;|wA?b+F2txwystS89Kwt@s0MvaR zbeH#r?e^87ti#?C>j^UB8p@NmYdZZ#PdNkYuOf%`M;;nJs{0FdN!;9fAV#|5IA1 zLXF&|43+?i)@A?wL!KJpJvdd=QE{Yxtf+h$C7xcPjc7!{GYVLTW(@d_PAjr0{)ze$ zUWzd1iaT{&(wFh$O_+nJKyPwCPSSTQt2Pm!kz3>!)XiC-{D%SxS=shd_>aR)(uKGou|nah+O9@sI!P4yP^;rgw8M0vm`Z%g zNjK;4ILohEI@$S8C=i=2ZN}UAzCqF4rG7pQcYQT6F(kG( zhE}1|FiodqxX6cQgl7ZaM0X=nL-12X_VO=yy{C0U`!t8f(xN^=52rkLnyEy+w1pCI z0k~_bE2WnvdXg#i5+c5uoSD^qA)sh5R*C0b)M*ui$Tb60*RdaC0(P0*Ux*plACnJiUm8Y@Y%WqV-g17&MMGKD=g z1{SV*aaK=P4I&qo!D+o0;_r8}g-pJ{)gC&zql!ZH*}m0FfNO%^~>>N<(YC zpE=&nxBF9E7pu}L02)y@(yz_VwV?pANpf@4_9UoT__ERfi2guqD3=e)*vLz+1JbI~ zph(UHInLI^DmRe}0j!}LEOsJ&Bx?Y)2+>~N;NYGCN&V+<<3v1U&(LM;D2$(h_jgG5 zD94T~=?TqVkvskIcSXTiJ&AmG+dp{i$9N z2Opsz#9z_9b#>a1JY0mousEax9%H_*CxU)ML=uBOERTQ-v|7U>x^P^G{{6fJIaZoem5 zzwuHS*843E45)PrxE<&tI>~dg6K&t^5;h3%i9UKSjTO{>jhhun%s#MZhvrBu$SqSq z(-8ji<0B)&yDP$CP&367aDnBS=Y(S$(Hzv!$U%t@H|=75wB#~P;gt%sM|SHIqq9Q) zhV&hiz|pEvPj01|_R}^sAYcBKs>*3SG2J!4kTN%DO10xa%8M{wKg7AXSeC8Osnu| z0FEN~;*Ef-AkUVI)yeeZr#J(z zuoxpBN!uAg6CO-?V#MFytm zA}vnu{u0DKdHX-3=ty8I@DVsp6d82#hVLCueSPSs!1};mH+uYU0T9|6PprS-;B znPwLD;FFJkZvrknXQ?FP_RZ3U_~!+lkof%e$oOT=XVzAnM9>K-R^j0en5VpCey#RLKs<- zZ0ttb;WlpHR4gF=(Bm!j%}WgXf#HE|=sT?p->=2#iw&h$_>NpUv#G9k+p>QBz*gbL zPm^fX-u6V6S6sP1=mxVix?m36P1|(19ReRl|30|a>)@x18;P>0^~BuBOo=42vg*w3(!sHF5g@3aCKhp3om2fiW3 z7F9PMMQ!1leh!-KbV{^ar8N^HsQs5_au&fSaQyRt^6x48E<{{5Put*aE7=fk4K{RR zb5yFw8*^4ms&C>%#_iCzcT8Pr-dr2zRl4Uo+U|5ShA6aNDTYx%5cNu^|I@g0d!y^h za>dKyhhwlmS;~VRd0#ew_ER`91%ugitJvVCVTqTN9n7!JILuY3kDaxaaP!iT;wh%> z{fG(MLTC41aWaiKe#yuYX;4mlda6TX-wh@5Ta0tkgHJzFmBV}iZ%2rCkWEJfwWkIj zJ>-TtmkGLNk;!4^NCUGGTqDgC&He#>OHoG z5w|VYzz~89;y~~DdqSapS2C1UB=y9Ojq{yWP!zvmHi@j3fRR^{oHSX`2w4Wr_g{S6 zc1iUwQ}qE78SL7tU2(j;N=i|_x{ck@>0bhPKhBRNdNXb;{@M48Z}=Shfk%c3YZL2%~@h}YVjZU&cc7q%5E-zk?^e$~uojK5+VM`OP5*}yiDyJHDRa;xVN0{d9#_^+}F zP%Lc?^{LSk>kDrRJFt0sa3`gk!TC+A1#zOTU_r~d|8c$sOx33Bad+^IW2A)$Ur$>~#%?#Jp<$p4CY{Oi{5LycHF3z1V0&|1n zBWqCMMr}$9VQacAHFjT=q|WK#GfRncdXR);jexewdc3Ku?-K$>x|G8U+QH+&H8W0T z*@)>7C(#*^$_)uJpjF46-xQ0V{2H}U^awW@;X%T`YQqYup1?hF_D>EoMlpkL_6&Yw zW!qOpIJW#t>6;LJ@+Q;{VvPk1Ku(j_Aa&&B6YWqQYxb&St=O~$*WKx*mi#kALHGdOa zJz;Aw0GTC-<&jDfb(1)k8{}ojkGDryMMvNi2@vV!E3C!qBD4rA=<~3yOG4k2PzU3Z zX>;SxN4`)2?0Ur`u2LGR2^I0`W|gQurt4h3Qv&>Tp(a(DKmv)^|Hbg0X22z7Qy$0< zPUH7KcA%U#``#|2`g`V7+d$tSzk9vG+e(x#n#`(heqHxRhI99gV}d>kdXsbwIrpl( z7#2g~KAI;8+xL`HMPla{`aLbnQOp%`rtAw;4{@~@TKHDl5U*O>VUFr-q_HCAtm_%* z-9J!Xtb(s*Z?x|UJGDvHvM4NOgLWsx5@edChT8j}{qbg;O|KqIX9J)KXuWok<1(kE zVs0wUDMA2vpwwK^(I#_svtt3GMcr-*?c5_{l}d`S=IVjvCgvKsfhnv}eSSyG__~LZ zOzfN(artllgA4-l`m;MM6s{;wgUZN9VD#05?gtT~U z>Bx~0OE8Vo*nwa~^h&l~YgT*^O#AHPNqu}YhU`)zLJvugT#^z0FG-;3tW+!T^fy~G zOTK}vv)Z^TspMtExIo|!uPn-S#gtX?TV0fL$;7{=ejGSbDoryhTEX`#U#*0Gxsm=^ z9)o`}%LTod@9Ek?w!7A&>%633@ zN9MjuB;dxQt`E$arq|q7$ixyg>dG7Gm3vK$0nYqx5 z|1utdD^7vbz&Tov{LH=9v(}*yp*nMm@`J0rIX^X0EU_B%tMZ?1^1(-}se%OYqelHs z^8j=(^U|$sGSSo~tD<`1hIS_&JcRB})NO7!#IY!-_ho9XNhledYOzMco5E>!}qiAE{f7 zEJ3zUY74$VJ|M;;19M1U_Ux8>Z`2AkqAXO=*Z+0pqEGbBA|bO?B0osFM2igd49|Ic z%0K*kFF4YyQUznvL@#dkXC3${jesePa z{PuW#|I;z-P6H*ROKlQw(KPT7;k8grF=-l;uST8cSR&6iB2IEQaPUAF_^b!}t8FsW z#0F|Ocp=#l>)Wep6V=Ix8e=Y*Lzz+N&abEIWA#i_@l_vU$Z#=Pc#?C(C{+ixvG#Rx z7(Hfl^~I7shGw_13c4C)Ps4PoA4WaFW^G55mF00$&ZXezx2nJ}6$%IFC(&v(UCm|? zU`$rS7F2VpZRk|>blk#I_}E_(^I8)YM~VloLFFy({+FI}En|VO>^LcLkj>cEjyfR{`8RueO}Cu+Vav*qRx&I$sPpNYAo$h2%4}TV(f`_UrCZPD~mL zmIcl4DP{*d_oSBwy<62FZ$eeg%wT475@dk)agyC2IE+AXYD}flWGG%psgp zkSwwZ%YXa}0HMgHTIZRYeaP#r{RZWoxMirQug6{io%(4e`M5|e*T)x${?m+Yf8FpAib-4<9m=3R6!e8n$3P;zEj9WLSh z;{M_UJr--&e6taSzl0RBWv!s^Oyv#EUElH8D7k=pI=4Ssijlv`K?TK=0l8Vw2@*Pn zyeZDAu%v#=@DefG_9;fEzj529q5UJGG9)=4&zAa})JSvTW;)XFv1e8(&kK^iQG0Bm znaDC6wUNfpIJVO3nw#JbNbuUMsms2ms`&iG1R&_a@Y?b}j&naj;t71XQD_;?GuSm9 ztc2Y|d=7C3Lr0rP^CidD&_%r!n_oMi6Kgo34ceV}Gas#!XeN+w>vy)A7p@y0n~Jub z5cnF2R&3K(;UQX{K`x)!A`qPf9N%jVvkv`WHXBC<@C1LSlHDf%NWZQb98#JwDEC90K6;0({$PR=AB?y-Vyhd4c@i`+w?s%cwY) zZc(?fG_Jwj-66OJ4GY|2cas*z-9I zn}du%xJgb{wld-Cp^;%jS#b^vgI;LH;k%zuUbgfk8Y(J|EyvY5B(7HdW0;=X8^-m{ zo>k5`hVScl^7O}c%K!t{^6>@h;gp?+)6~j2i0jce(-0_VXe(_ueOFV9wo8lpGq;Dj ziklzuwaDc-+$tl04px8^-__&L^Jw{oGwrUe9|CA5tIPL zxenc|XGUFlK+j^eryO-?FH+S}iLDBGA8h0dVBN!gXP88jP0u`jJfKKq-)3+v^HSmI zb^okIa3Vky*RB3-X>DTgE>mYuV!jv}N)MD|=0DUW#`Sqvdvpg{;hX2pCdqId(itNDX`6MxChi7Jy-U>QvzdRm zKDO-8&$qj`MNru*nwp^|Pn&IzCEsbF=Q1;uvOQ(P{yaHBl>w-40lr(u zIH@6o$)fC=-!McW->!n>d$GQ#MAmDUrnEdEmgefP%$SEEYi&|i@khw{;Wku089*e1+Xpt%CV)30YA!>j}V}OZM5VyN+{)X(BQ)GVBcUkBG5OJebVau+7A^elmuk z-h|8b4!wO(-!2rsHdJkaeh2-5L#3D?g}v*6X{FE(+SP;JYB2K&K1CsNin?}6E&rI0 zN|_CNUTOcrbu@p&MOYApK>@X6yltCPDp|f`Bk_J}#QF9J2gMHk^pka8vmj1tsKX{e z$iqigAZKOs)Etm#98>$!r1VG`bhs zb4V*mEfiK&o?TGzh4UZtoI^a7EtjUK3hk$oE+EsbHrY}p`{J#ImR&~v&ep)9e9~+MwV%M&))M$f$c34m~_=yI%1MbAcw46 z8b?@7Q{0jl4ed#{f2LA(;?`t;BR z)27CKmtp>;TLg)y*%`8!cW*(*3*nvlqWQZMZ4$<&!4ItDvPp@J>-uh8tZ+G2roO46??DX;ulNkKK>wX*%Od*oBV;l#{+9r5J!qBAzW)Sc^v6E=^& z!Pm*0>d)5R&FK`uO2q@{tukKP3K#AnHH15ei|Xu!`e)yV0%m5whpg`agD;VzaS()& zqs6qwPJ~Hm{&RwcN;d$dYY~n{jYn4L9sPCt0jsK|sz!6CLzJ9vprwjX#j9l~ealdkQp)Kx5yetioF&@$wYzVMp&wrWxVETCM@nl~&GZ=F^CsQK#b^6|m~unRyw zIA7Iys#iE;Uy1qzUFmqb8guIW8+N>DuiF#ZwTBU?bAZh2@;$H@@B^7LIxrJZW3n^i zP>J>dE|+3`9%)$joY%C9L!;HZN+jn={{Uk;7*_9Q7|rK^5Xnw37Q-fJAW}_WAR&ih za#CMj>t%7~b|MYUU7m9@*B({%i!Y}rKR@c`-MMgOo0%M5!K770QL^xk03&8)whMq0 zxgpKk$}Hg7u;P7(M@Wy`3VG4sT?+TzDWH~f3CHJ}_PNuv_G3Yh z%)Qp^eWvJBp={Hv(!$k8KVgY1yT`#j64Eydgl>+}dL(l_eObOmiW^wE$F8 zFTqp1K3GPZX5@#8#29$-6Jd%!(o$?W_j-PtNjR#GGH}`%PGXheTw62xfelMqKlh$= zV>QqAJUy!Zl`Y5aF5;^omT%16+n}~1GTGT->65$OGZf-6>J~EoHvKyPS%4;$-_-*G zrT~V|Q}UhlrDb?p0oiqs!DnKtFF3s1I-RGoN7xOAxOXFUb2{U*77=uP(AVInKBuR> zHN{Dmmzh?{RQ~;75CnC zvG`rOup@reE#Rv#=Fuzp!MP0lN$WYB5*H2;hza;kmwE#vI+@hAagJ=f|I zH9C;CAm}@*#IctN<8?s3CEz|9TwcCPd2>ggU0bW7Hcvg7K4N_$Z?fI+jw3d9CJj3Rtok@! z+Ij)|R8=6GguWfZ0*O66a3)`3R&mWZ{d`ahs?!_EJ;Pgm8$|?(jgX6m>a?+9W4}%f z^;aRb*^EYfGCWjBw>X{LzJ@L*()s3|&B`XN<9Q+2=Ie5Y0rTtXRdg(~8&8L|9!pFk zY!G%vSg!LGh}JUr!E#R^J8Wqn+*lDFkKPFe6UOIEm|dBw8%7q^)|3Jst9UK9;%QuX zM`SO+vsU}I-D|V)C)ntClWX@r$1;-<({b~w>kJH07k5A-J|(PLv}&#@@}BZ=&gDIm zyzs-XR+1bk#Cj=T;)KI8sXbmoDmu%8XA5ZtIVMf>op{>Xu4lNmw>PuP^kcApr?(f& z_e$4gcs8Fu`DtfnMZBYup{3*-KXtx5le_F5E&5!m-`98 zdt$>77qya0cdZKEyYbg`mYW(+I3KU?0@5pB(=I#Bjdf!xl~E7PicjrIdeMZ62Hb29 zw0#Iw(a9`cYVuhXW+9M>@^%0XX3L^I^No56auW{OWx&B&4MLG%?kBf89KKMjG|J#5 zjk;grK;6(B%nUu+4MceKh|;seq;dX61V@{wWrcbRQ)$ed_q12g@iptKoK5xGWtBsD zeL;-XE}5^qu@~sk`t|fU6He1V5K2Ki)}+|0Y~6J5&u3Enwv}(n^0U^O!c%ME%q7i{ zfR%08W3djAL;DJ?R1zok8^UX4Kcls%5f~#g8|7s@1OBGgzn?biIEP>Yuy8ZxVPTLP zTGa4Szlj>T2vM(#NO9!$JWaPBao`C*0vUcZr5d$Qet`RtWK4xKI%2*yd!Jz;^yIzp zNadway+-}{nUekYYzs1i4#d2f>013lt%Ld6{N@z3U%<>Sw2$ z?z>v3j{TK)zgq{FfcoZT!zVCUN29RRVxU&Y31C+&tS$LkX(3JeRzuLN@vDj`_gc@% zxdktk$|=o-{~}Vl#7X%Ky}Xoj6*4Fl{qhUP*oQhRas=i*_+>ucT>yu1c891=+4^3& zxHJ-K#yP1y;1#{2g++UXGOd@!DXEto=Z687HHIiE{wca1?)Cc?e-m)$qgRx9gGMOy z$}%GxHk$LY#P3`u;Z2gUjxLkq^6pY>RK?;!)iw_4cu&-4q513k;+Vm_3L^Of<^Xr^ z8nSeV%Y4SVN_mfGq5XWRUePNk`Y`z(tt;@;M^2jH=%w0w8Xds4otn}xk2CU`C6dgy z@K{$75hbj(=O9$j6AuTf_Ct)A&~{|w_ulZ%@1?b~&w>w!^LbBnJ%(SuQt^xJ5 zmZ?Q6m;%#3VQlC z>o!27NH-;_NQ_kNWw~|dNc`m)z#ld{J3gZ%l8KSd_&+pVZN6-M@#nA?X~FoE(gNo|nXQ2C`l0?a=SiPLhx@jS&+>R% zD=h~Fd5%l?u=s?lZv~NcSb8ZhsvokUaSu2ZVDVpc4p(U}gGnr#KT0lIQc$meb!dF3 zl1{;`rfo&O0YdkyEdIRcIKB@IBWSCnWD!sP{A7yYUu_dOjnNV$c&&}{6tvsY>Ww5S z`1YWC)QI!?s)mJa?u3))J%V};yUvG|lOuz9(nM!yZ>=T`OE^Jk; zM(wv__9|yPW0+@hQ7?48Hf6b{m%1-g1=V3d0-zeb@`QuSs@Vd^pkFR@ZzTl;%kRh- z&5T3+)cssglwkRTz&bSDIU`85xTQZSY-1YYU7|vB-Ea#08TQq~x;%YISXC^_O8p`(NgW%52w%}PzDS0HFQHOwz z>nPwUhwwvF={iV9qjW_Qak=emIOY0U^qjS=wvWWeC~efuHep`X+Ir|H;W<6dFz4p3 z_;n;5gu(RM%4)oz?HY|SUqAGEZ)y!sevWE_-=YSM6K6+hJ^i~F<|o@sXg}P&6mjP{ z1)h(TRNl5?>;ebKB@WO>CWYtz4cK!mF6FEL&;na~`1+m(W7Xj0`e)@W1n$$*)(OG- ztwsvV=<#NR2cnauE$DIB;Ax8#mya{b%U?p9obnL*1L28p7T@lOG^^kYR za~*Y!aLs-FeV941)_bxQc$sAg)*9V!;q4V2hfWSjh%aodR=} zeniCqBpTV+-JL$m-zaP@$nQ4=%W{zsV(Gg0Q1J@ybae!KL)pPEg?H?F!U5dKG{%F< zAp!@&%%L)U^5Ov!M3HgO+8(zpBgWNYU>?R4OH~u=(9c~fXn>D;VPT(c#LH4ck}4X>mDjiuFKH~8`poFDkbJ}3oi+u7BhQHbTo5(I!heV& z#B%_Q6v!)cj9i&YLw8z!Mw_7*+fEw+(r?bD?}9z>ZYGfv*VBW2l%y8*3#{4BilJZp z1?hBq=qLfKTNRsJC4zr>&QL4;?SnIPVX1!nftlf{W}P64P37)U5nNADq0Rdb!0lHRQ0}G9>%$|xJNQTsREl9skKZ7W&DJ~&m#CnOj zy4#~qy!Rz72vjl16Yehc1t?w3J$BJOb3a~77`1|95j+S7;MZYO=)p1j!Cf+c-t>4x zz))JhNGQhjpuX78bD@PpNQK0t=dC&Fvu;$D&L*EIV%~5W1H|#Y0UN_OZ{0`bUxF1F zjYD@ zEcHQQCdH0e521f@Pc7KsSb%H$%qZs9wETnlNT_+pK$1tE4WJIH6~={TU1&tuR|?O# zRnsa51y7c*iB?_gO>XPZA*=!Wkp9*OhkD;N00o=iQuqSQr_~(JWHyJP9aB^qo>j~* zp-S283*P-B)8kRz){ZnZlG@oe(31Y{K5dt-KtfYe)!&!wtC10~J~{b2T%>J+4|>mS zv5(^o8DssqrkeuByhG(N>nl2JW-tiss5ora*gxUfN26>edBx#8lf8+mdb8`bvtZeld{OOX5s}e0 z&J4g065x4Uo4^aNbzF`*INKaVH+N8&7>hS%omzu^q3(YmKP7V{SIeXFRqi9lF~)nt zZ%A!t2a?@`iXR#JupiMbi%1JbIvY>Yem+sJEUb}Mx6nEivdFwA>Dt2dfMXO^#}D-i zsQa@~-h?SI8(sG6Zm+^b?!w4|VLt%Yd#;9a8t@5Ccsp+15jg+FsyJAx0@{RKAO=)H zxpkWY#_WheS7?Sn(E_j_fRC4SxIX-@b>0w9R4_&MWJ3nFjka$X&{j?TzCP`Q zwAbp6J}NIi`R~o$$v(J=@GzlPlW2YQke)ZF4M5PQnHQp6H7vjV(f@-RpImCLv{bha zDW|;>Lh=c3FIc z6$@97wRQVi)dC)79B23II*Gmox=E2-VD4;%9MSIuA`n~Us;RO?lu!$`e=Do%&rt)1 z=_u<|aoqQ=7@iCiU^r3<5~>-(F$?MH^H{gvT3S>$ z;80MpyOU$h$a_9Ab%F!TWw}OHKar~GwLjjp^82v^q*jsmdWO&z;^7lXJy{-CilrAB zIABLw-dy{i1bpaR`xURF*(NzOsOF1{oU2wB`L0yk(@b68yrN+&CLely&=!IH`AhIN z`6BnL@JB1sSmrO5WqaKco^tFXEbY(ClsLi{x|7a@@Xi%jJ$Iv}Z3pxMKbs zQ{zP8*}w;)5!y?nWup8iKGAc+;59v-=+;Tsf)_Q$1hjGQc^#dXYF04ONR35H$Y4cy z)mr77)o*5b6@=&^i7CIhfMZ8XPw8kZwE9hUn!@py&Xo&a>k`{0I`2&z~2Q&j`ffIewyFIJXA0^&8UWOMxm6fxx%l&MU$d$Qa59tHIQwL?{Kf~GM-*UkAwr`=H!d24l&t<}$pFVmPky`0g*8Y#zl_;@t#{JpG zV)8x;0J(^Bp_?5(lU zg9CbcF2P_;|MmH#-UOu+J>V;ZA%LT*-A*L(Ytz7w@s4CCm~)Za4t zFYSwMD^LehxK6t-&O$B(crOrI}Sm3r<2gr;I8%BnG|D%G1-O7QrW(DVe&WnO^} z3h%Qhwl%t^PFN8=BHzTb!n!g>Xe`y;?6gx*kl>!acSYhtAq*QkLvObS43SD^iKqOo3spA zkzm)gm3cDX()ztJZB4zm=RHJg{W6G)NJnqoQhf^Dt(bFcUA>@i`IfJABMqi529L>d z>4Ni(nIaSay2UsR<$}W`pI{3O$%*X?sLAW;Bc123{xz9+%P$@pJg$75=oPFOSdon^ zjby}Tk=2ivsNX*YgNe)vD9Q-Hb-f9^SA91D|_|6*b7(LAn*r zY)ib$eK!6sm49J>J%tT!F3o9i&fPW(Yz{>z5##vy<3rUBUu=7rwPYrX{}IfWo!x4= z?^Hlha$i=1@7y2f5wlTNKSNFye=nNAS-mkqk-9igq2hysTPf{3x<38~Ry#~m$A+{y zYAr0#tIYt3uF@#HzJmpax!foG3`!(-mGGR029K$8x&#`&uRY2#EC?Mo#VSv);ywz~ z7Zs!e;h})U0?HLxF^(&MNg*xb4Wu%l~X;hC4`J;x&XHN3 zqMV|g%E^+8`Y3OQ~X>si5+D`3c2!E!`8+rU^_Xx7)qK;?QmTasC~s z;KWk5a&pVZNa#_^?44;RB>=3QQyEIJluj|Zo#HI&8{Lv2G7^~EU4*hwiv%pF1^zmuSS^aFe<`ORC91chcZo6HiBnMMw(~@<^ zfSwKE4p*!z+HTXmpD+5QpVM;sU>@(zY)!M>e`onT9^4-3zAgS%$k^?eEV{7D7Sj}X zd%ik(JgR62A@LYk!m+>GEG#IXYPp`0vwpt6SiHHge>(3*JIPpk{+(slg&^IU_5JIj zy@f?dxkg<{wHv@Hi{E()HI|qm1{()wakDpqxL}j)uHJfS*4bpG*?FO(QMSj>(qbyRp+zQWFU!^Ha(nR8J5zGVG+6gPAo}f?WY$w*8W}!b z8M^96zrz*O1jwwMX}XFS%-Bi8!#^#6v*cq<=ZFtnq*~zS352~Gwe5Sc!^7$(AulJksyO!R9eysSO?!)BwApIz$hR}f zs@ley^;X~4A4puLWN8=I6^{W^a%HBMS@I z{&h2gwVvxhnW?n&a$_Uqf8UGn@3}(Mi^;nS04u?{YBg;mykiro*P{AeRUSXWA!}N# zl%&-4?mPKuw)Dyr3xsB6BtsH3dIpvoq-~T`z@xfD+u^^nFd4&_B`>Buf}*n&tKR`= zRb?c)9|w}Gx~11_0)kide(1Dl<*s}=;@NMv_N_0qohoQ*(cgsN;SGe8MsD|yx12#N zulC00z#hG*Qm_IVv#um_5|Qr9_)Q@>YCPa>ob{}S=hlMbV=JJ6j{6R_DROV~ zEb+k|>_lGFXd0)qp3|=uy4kytT$099nR-sZ=$ZGK=U6NBw@n}$3qMrlMF0`#VOW>{ zDav(|AD}&NVw&Zg%&cDBL*jk?-IN2`Z8V*G7>8M7d;OwjTv)TX-89Gh)1Mrm7AVM3+~;p~a0OICX}8AXmDEUbtV{yX)Mue56K%zMqFPu;yXUn&K6B9PW^ z%N>nVl+{$m9hvi$MJ$u}20DLHBfVNJ)gJw z!_FCUqLLbFR2?n=7E3ZMx<^ZI~5qY%59wMS&d zBFZevf_y`UgS)4`;GXk0MMpw}5-90_#)k3+HMMB%w z4PUgoD=jU?r`wYwtJ>3*mZz6YOBsqY*#w#g0f5W;D*O-g-H|jMl8*2&EZSy4J;ieM zn!c4&y&EFeWqTh~9IcMBO`-ef2)eTXOI;O}WEgtDkL{=DD>(t%w>NamtD@5k8eh{kY{tL`Fq7}s8CFCGmhgzdmQcC@p8)w*!W%N-PSgJ zk@yC-r&JOASR7)IM8E69(h7c<*lJjMjo`o1DJ>PtrQYV&g!>Vd!J5UkGJ~RjfanVY z+S}S{6Hrxs*Y#P9WdpN|T9i$k44th^OG`gUJ(W2He54}Q>>O^nWdFfZx(Ia!RAMM# zouq!3j959x=A9 z3ZGpbl?#hv*!`0BzJ#wv4YKa?7;M+sbQR>JQe~XMY4uHnfkBJ#s?J^^E6;^3e)TJO z0{uUnrB9?D3kK^CAPfA3(fy1f%})8Q0&}ZvPfrfr8!kGu;6L;q@jRB$kXYpYiVF33K@ zKo^KiwDTd&>1djEG%3l(K{90ZnrAeTaW<#CYFx0>s)AKoo{)D+V$}*O`Ln^2E(__< z(9koANWAav&H%0v;DFF*U?h$6Fg~Im;x{@U9-R zCZWq^qP30jx>Dio^$GK-@}5I1W*BlZ4d2R0@j4O>$*bmZkCcMHpwXwdcE7H72D~n( zks8DZTVw($5H@-*&?7==A>Ea&t;;!U+k*+(CMLhzX%b7i>dHHv^@J0NC^qI<`_aT{ zhhn!n+4y;FzkI-uyJ)Z3_aJ_W99gQfOvy3)`ZYSo@EMXS!n#dZ9rIxK5*t}5`mGC< zeDG#dFs@3=GTA)T7ycimqajR`i9awlJ@bu+#`|~EVaW;vwzAeJppg1@3FU--eA~$S zR|-YYlWx`aUzL`ylQRb<3@5m${%u*(qn)4M>jxvsg=q#4zn(S_f`v~RuynmoJo_fR z=InMGODnIxNiLYkxfwUo&oMP9@jm{zaVS#6_PlWTv+nHLGxc3zZ@dw~UBuoS@=?^e z4ydi%>!NDjf4T+=T&bkgO_ytqm86s&uTET0cpVH5K>`_0S)^DC%m=E3A!J&#;FB6T z5^XXJ*Ejo*>s*g+)G&`G@;L;buwKQ_z4#Y)mc*Pn6;hMVH=)&TCBQx%(i{8f{|>8X z&^)v2v^~blsh?*puA>aHv=;7P*>iyuQqP7Q?msclnx70$Z2Zv5rrxK?2#f?pjXuPI znvE=%F7K`qC9Jj@x24nW|_4Vn@^T0n>te#AGSF<`S5eXCKphuvZT0me)4u2a; z9C1NX9hW2An}PtHQieO8hg5CaNvB|d4)^mAnOCgB00E|6LA}fA@&O!S9@2%c9R*Y` zd#Zq=QO+RhHUUI z6cqHlp;UDX#;UVPe2q*0yvg<^hXRW^2Y;)Db~|d{4UgQf`6bGUxJ>3(kXSSQv(V%j zQ`y|4tJ}rW4u2l*|6H5( zPXYCX_gaCMz|`_yQRYLEC$V$$sl*_pl)yb}xL#@E2>eFNV|=)#A#PG5;I+=J zY84-qZD3NHm!XxMgF)NcC2GQs&Z1}-fNGhV@I^*GFcbvp_auYq=cnx?eyx2raxDSLL()MEoJ9(7w1a1^Gx;_ua zIiliJ@g(_7u^7goUg8jP$GmE$=Cys(+s$1{e|0#CP|aVPg$R|FkuIDqr)H8immTvZgEh^BhHYF4S6>-b zja~)_2;&towY>s|&sal=jK<%Wha=jMKnnaovRrvI@{ZiHXjm+zASYyVRw{VR;J@fc zlqPDdJUnxw89d{67Zf)^+xnG4NBwB9Q!r?P>u>Vu@b-P|=z1r_p-5EN6z1K*C_a#j zCq3co97ONhu2%FPUZ|AUDVqY~A&!b%GPvX|ygbpvPhN7J-^D|n#H%InVa1Zobf2Rx z#RKu5#C*tSV>L%mHY66bpG9ZwnfbnQg<-eraIEp!=*d7c!`B(rpNu)v+3!epML9~% z3q7BAXJgO7Mifygu#BWD6f6-`bi z0k2tNVK_rzL4jDUfmlEdJ%Q2 zL-Y^|edJPDZj8N4RV!|%Oy3U;`aISUN91joF8>}iPoSeHDtQpPwHQ;-3z==K&E1M? zj-pGscFSzV=Rxu#S0l39R7*N^5lwc^r36veZV;}{ zIdzeq6j zF~PqEg5uno0-f=@gjZt9bIveH&4jk8!=Gv|IY-4Joi?qsmzPZH0y8$nvp?yFZNlFr zNz3$8Y_wbEjMR|nJ^r?9yLzt3FR5(IO1lF6!D&yzhIY^3Y$;$Rh=3ssDWAd`4HTfvJ7q|+ai5KRg*UP78K zuy8diDx+MqqZiI{EhY6eug)TksVdP`6Fn}dB&Vc9alWj%A(CCfxCb`=@`_$n5%j)z zH>X8&D@xy!Nyg&;vgco-=0qn?lv3K1=6v=%ZR$@Uh~F2F)v{pY@!*`y2&aWzb>GYK z(S_%Xml;Xf#&?wP`L@{aTA=L-hdVlSkPyU0ZZ4S~8ZR`Zc%0)%j_ooq1jsLD5T0g5 zItc2ZNRu3b50kJ!dB7w%o2HDQC899a>&nD1D@GkliI)d6&V_UQh#s!n6U;+SVbwkT z;lt%=d!|-v7T2}4H2j4j8um~YBn z%P_jvYXKN0N=0tY4@+CvH0fg?t02P|_HPY!E>mAGkKf<(qgk^<4C8zOknFoGo8+9<>EDePIjMST+ak_V~G_$x-^6#Qg72}-vjBp8`iwVGW9)x`HfK}6>F zkKJbzLBVH8w}aB{cKzWZW}R%NT?Q=|iZxDJO-VAzlCBHC#tVCABbSGJ=ZzyyfV0>5 zmX=1*sfT@gFHN#dgeR@cRR%o6q3tC@C&Edtug~Tw84W!^8d_-*vm1wc}pwu7FEkSiJZk5?w+bo9i%E z%r9JO(xS0~c|4fZkpme5r;XjiB!O@UgwbL58$#cUiGfm;6RzRe%3Nsg8a`%NwiZ!N zw%jk=pC9RtCi4+7u9qFh`FfB?clmIZ*g=m5lSD5k4Qsd1C-qAcf9W*UK8-9q?%ZCzz4o<{T z%rhdhiRB!LJK+_HcMk1~EkQ&Ma5ECxCRmF589`bW@89W@Ver$)83Oc&(CSQuIx;!akUj8;~<1@Z{A5hqAv_N zO9eZiKGQs)ta%)jXTSZI^#$L>IG$<2@vq0fSGS2QScBhzN@7YsJVo65Xx(Ck3hKSK z?tT>N$Y3u{qbO=(-HRpX9q!0zaxW^F7vlcxj|TI^b?<#q)v8?`LXCO!(J@t2oqzhI zIoFdCHBB4Sn2zOnVsi3_ngO*be)C3$ggiBx_(fOlo!mZT7LThiz_EM&aKPaSt=Gm_ zXZY8>(?JqRs;&;$8i}uWwHfAXYz%VJonQ7?;wwNKb6H5nGd$n!(-wGLp_&wad+`rz zjB$M}DlJ|-lKeYwFH-G{d;cz@1m%7L#dU@>sfc$k4J)DV9xUUGYYMrZ*dm;+KYi(2 zMf~Z6SE?>V5s80onl}zNE(#ql^k3?532sC3D7oOM6>m-t8sS=?= zF$g-55obr6QY>)Z1UgbS^?DR|nK1~PL>3;)$CA0Es=B*3nV#=v*goELVFA-9pLQi> z2{}Hf_j_0k^TiVww98O^*mLY5Sh#Z45lo8jYy#`HuX38a78F9mjAgvU`Q+QGc!{v2 z#!89rlUdEv9#MA5P?4weqV3*J$+7n0T`sK?#A+E#2w2}9FT6Tllj4!z$HtGaPhRlh z?q-CNKlAPxN#AGLXWp;bYCh>{<6Q_ukUmE}*ppQLriwdzzLi0~)ZAzo(~`C9jHxA_ zOJ2i95SyhP?S1>z;k)MU)Wf>xiZ>etE*k&0?43K4O$^hR_gXUpU-He!6k%@3es>WJ zWcl0%evWucO)Y82*r>UE$kPs-F+2+>XF5%8U*1O5d;@=mYyT8?IhnH5r*c8s*hwMu zcWz4axP9_&toi!Y(E)S};XFCh>Wf9NISP5Rs4nj+ydkt1{fpa-pt@#4Ur2mfqX^oG z{s^{o?_h0@8hXqYl63f$!Rx*tIZSw1s_lMow(?1?ky;=f|F=6k-Z@05g3FMa??0Xqcxix zj3ahraBWU8*t57Bf9*+*(-uHc$^c-+Ymd?KJDNuVjFBOf`?1<1BFzw8@-UEiSLjI` zW@ru^5)RczEqL;R5ypyE%q332G?6YUok})SSfVTARlBby(F5`CPN=@3TA3Nxja+-X;K;ZZX1-W||qbp7;pNc#bF!QB(w4K%Wq;d^_(4>q|`v{r)pw z`?r@n9@;sTatGtvH##4_o$6;&P17mI1R?I9pJ63L|4|@cVGR(#`vvqXTS;aU@@>B$ zTTzMbi{y&mtZ)o*N&N`<0>35PJX(zJPrK&wH838Vuyse((ZZ^zp1HJn-Z;WcNw?4> z@Z5ab>wBEdL08kZZu2_~*9t4_*_2KwtRyJ=TP2jw9DK5%XjJl=oP&g6 z;<>h84yk7>9XOZLgJ6!8eU1CU{3E99S?g6aF8jqWJz+sv3})FFfegOR2rV+zk32u# zP+S=+ISrbm&Z_)=+9p__&LDCDc7;R$UqjI{%W;5ZPp%RAMT(3~Rpt$57 zu6QP(b+4&=IhWS|OLwjjfu}|Gp`qn_e!FRL&};n@>+;|tw4ClsCozkb;pipEmS<;> z8|G}JN!#b?(Aa@|dPh<7^eH>5Ovvm{a}1I}!0$D3W;jwK!~>@74`E64KYrJ$eQgeo zZ-|D^7>;?{5u(gSyuaUyX>ncio=bTox8-+?W!VgikV|H|Xsf*+TYsDu&C=2JLNzZK z6Lc{>iQwZ@^clYHdEa^(1Q~mdci6;BB7_~iPy=d-c8cMplyu)ae{GvcLoOodWncRr z((*1mEIiOF?<6hzA)q@VB?85xvh(P^aiJm1v1|zCF>etQhJkl}^Y>M!Q9knuiitK@ zv%HvnGVNLAys#-gSd2mD=+6W!1^vx;Rst?u>Fo)b;mPGLR*H*X{#}m*nKJYWL*xG1 zj5k6_tj0d%vgIdha6PWya1fw4=QLh{T>r0j{}EH)%HW@x-LjW|*dpH*zYd-x(FR1Y zErUc>%D>O!|NB|daSSt`R+VvLUFm<1>VJ>0Un0DWU16XiVZ{HdOyagZmjM7!zhx!F ze*U{gU-)Y-C` zG^Q5)#&qAm*XsZ8bSk7E>R(z^;Tz5RkK^k9c{~>L{UsC6%?ROQIK^eVG3I_{fAagOvApCLQBUu$8XsY0^UEel3yjj;(Gr74=fPmr2qf` literal 0 HcmV?d00001 From 3031dae1ce48ece93e8744426f1098fce8a9dc52 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 09:38:31 +0800 Subject: [PATCH 220/282] [#128] added note --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 134655e6..3b4a5112 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,8 @@ end Enabling this configuration will output the database that the process is currently connected to as well as which schemas are in the search path. This can be enabled by setting to true the `active_record_log` configuration. +Please note that our custom logger inherits from `ActiveRecord::LogSubscriber` so this will be required for the configuration to work. + **Example log output:** From f714c8a28e020887b7ce3497fd06e150fab86644 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 09:49:58 +0800 Subject: [PATCH 221/282] [#128] exclude documentation support folder from gem --- ros-apartment.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ros-apartment.gemspec b/ros-apartment.gemspec index 7c59a6ba..95a60c35 100644 --- a/ros-apartment.gemspec +++ b/ros-apartment.gemspec @@ -17,7 +17,7 @@ Gem::Specification.new do |s| s.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject do |f| # NOTE: ignore all test related - f.match(%r{^(test|spec|features)/}) + f.match(%r{^(test|spec|features|documentation)/}) end end s.executables = s.files.grep(%r{^bin/}).map { |f| File.basename(f) } From 5a06fffc215533dcb03a784e3a6dc23e551bbdf0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 11:20:05 +0800 Subject: [PATCH 222/282] updated changelog --- CHANGELOG.md | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 345ae68e..fb38ac55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,27 +2,40 @@ ## [Unreleased](https://github.com/rails-on-services/apartment/tree/HEAD) -[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.2...HEAD) +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.8.0...HEAD) **Implemented enhancements:** -- Uses a transaction to create a tenant [\#66](https://github.com/rails-on-services/apartment/issues/66) +**Fixed bugs:** + +- New version raises an error with ActiveSupport::LogSubscriber [#128](https://github.com/rails-on-services/apartment/issues/128) + +**Closed issues:** + +## [v2.8.0](https://github.com/rails-on-services/apartment/tree/v2.8.0) (2020-12-16) + +[Full Changelog](https://github.com/rails-on-services/apartment/compare/v2.7.2...v2.8.0) + +**Implemented enhancements:** + +- Uses a transaction to create a tenant [#66](https://github.com/rails-on-services/apartment/issues/66) **Fixed bugs:** -- Fix seeding errors [\#86](https://github.com/rails-on-services/apartment/issues/86) -- When tests run in a transaction, new tenants in tests fail to create [\#123](https://github.com/rails-on-services/apartment/issues/123) -- Reverted unsafe initializer - introduces the possibility of disabling the initial connection to the database via -environment variable. Relates to the following tickets/PRs: - - [#113](https://github.com/rails-on-services/apartment/issues/113) - - [#39](https://github.com/rails-on-services/apartment/pull/39) - - [#53](https://github.com/rails-on-services/apartment/pull/53) - - [#118](https://github.com/rails-on-services/apartment/pull/118) +- Fix seeding errors [#86](https://github.com/rails-on-services/apartment/issues/86) +- When tests run in a transaction, new tenants in tests fail to create [#123](https://github.com/rails-on-services/apartment/issues/123) +- Reverted unsafe initializer - introduces the possibility of disabling the initial connection to the database via + environment variable. Relates to the following tickets/PRs: + - [#113](https://github.com/rails-on-services/apartment/issues/113) + - [#39](https://github.com/rails-on-services/apartment/pull/39) + - [#53](https://github.com/rails-on-services/apartment/pull/53) + - [#118](https://github.com/rails-on-services/apartment/pull/118) **Closed issues:** -- Improve changelog automatic generation [\#98](https://github.com/rails-on-services/apartment/issues/98) -- Relaxes dependencies to allow rails 6.1 [\#121](https://github.com/rails-on-services/apartment/issues/121) +- Improve changelog automatic generation [#98](https://github.com/rails-on-services/apartment/issues/98) +- Relaxes dependencies to allow rails 6.1 [#121](https://github.com/rails-on-services/apartment/issues/121) + ## [v2.7.2](https://github.com/rails-on-services/apartment/tree/v2.7.2) (2020-07-17) From cea09a28cef7bca068e928b4a45d1371f1d6df4a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 11:20:13 +0800 Subject: [PATCH 223/282] preparing release candidate --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 398dd80a..7f3379e6 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.8.0' + VERSION = '2.8.1.rc1' end From 6adf7298b16db09f707fdeb69e1c7ded57f0acc6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 11:10:29 +0800 Subject: [PATCH 224/282] [#130] drafting circle config --- .circleci/config.yml | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .circleci/config.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 00000000..f3d93b3f --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,8 @@ +workflows: + workflow: + jobs: + - build: + matrix: + parameters: + ruby-versions: [] + rails-version: [] From 79d25e97a0b09d69b209066925b7ef31e0d3349a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 11:57:14 +0800 Subject: [PATCH 225/282] [#130] updated circle config --- .circleci/config.yml | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index f3d93b3f..481ede0d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,8 +1,36 @@ +version: 2.1 +orbs: + ruby: circleci/ruby@0.1.2 + +jobs: + build: + docker: + - image: circleci/ruby:2.6.3-stretch-node + executor: ruby/default + steps: + - checkout + - run: + name: Which bundler? + command: bundle -v + - ruby/bundle-install + workflows: workflow: jobs: - build: matrix: parameters: - ruby-versions: [] - rails-version: [] + ruby_versions: + - jruby-9.2.11.0 + - 2.4.10 + - 2.5.8 + - 2.6.6 + - 2.7.1 + - jruby-head + - ruby-head + gemfiles: + - gemfiles/rails_5_0.gemfile + - gemfiles/rails_5_1.gemfile + - gemfiles/rails_5_2.gemfile + - gemfiles/rails_6_0.gemfile + - gemfiles/rails_master.gemfile From 1cf24c563a360b30379d2f617b28ede62ee10ac3 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 11:59:48 +0800 Subject: [PATCH 226/282] [#130] commented some versions --- .circleci/config.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 481ede0d..4d815e16 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -21,16 +21,16 @@ workflows: matrix: parameters: ruby_versions: - - jruby-9.2.11.0 - - 2.4.10 - - 2.5.8 - - 2.6.6 + # - jruby-9.2.11.0 + # - 2.4.10 + # - 2.5.8 + # - 2.6.6 - 2.7.1 - - jruby-head - - ruby-head + # - jruby-head + # - ruby-head gemfiles: - - gemfiles/rails_5_0.gemfile - - gemfiles/rails_5_1.gemfile - - gemfiles/rails_5_2.gemfile + # - gemfiles/rails_5_0.gemfile + # - gemfiles/rails_5_1.gemfile + # - gemfiles/rails_5_2.gemfile - gemfiles/rails_6_0.gemfile - - gemfiles/rails_master.gemfile + # - gemfiles/rails_master.gemfile From 8d230a22306298ac227314f92f27dbd9b6151484 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:01:38 +0800 Subject: [PATCH 227/282] [#130] commented workflows --- .circleci/config.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 4d815e16..6976cb32 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -14,23 +14,23 @@ jobs: command: bundle -v - ruby/bundle-install -workflows: - workflow: - jobs: - - build: - matrix: - parameters: - ruby_versions: +# workflows: +# workflow: +# jobs: +# - build: +# matrix: +# parameters: +# ruby_versions: # - jruby-9.2.11.0 # - 2.4.10 # - 2.5.8 # - 2.6.6 - - 2.7.1 + # - 2.7.1 # - jruby-head # - ruby-head - gemfiles: + # gemfiles: # - gemfiles/rails_5_0.gemfile # - gemfiles/rails_5_1.gemfile # - gemfiles/rails_5_2.gemfile - - gemfiles/rails_6_0.gemfile + # - gemfiles/rails_6_0.gemfile # - gemfiles/rails_master.gemfile From e172a312d3fa83f746cee053329b0a9401453147 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:07:34 +0800 Subject: [PATCH 228/282] [#130] added parameters to matrix --- .circleci/config.yml | 28 ++++++++-------------------- 1 file changed, 8 insertions(+), 20 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 6976cb32..e0abf434 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -14,23 +14,11 @@ jobs: command: bundle -v - ruby/bundle-install -# workflows: -# workflow: -# jobs: -# - build: -# matrix: -# parameters: -# ruby_versions: - # - jruby-9.2.11.0 - # - 2.4.10 - # - 2.5.8 - # - 2.6.6 - # - 2.7.1 - # - jruby-head - # - ruby-head - # gemfiles: - # - gemfiles/rails_5_0.gemfile - # - gemfiles/rails_5_1.gemfile - # - gemfiles/rails_5_2.gemfile - # - gemfiles/rails_6_0.gemfile - # - gemfiles/rails_master.gemfile +workflows: + test_suite: + jobs: + - build: + matrix: + parameters: + ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] + gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] From b1c75c0b038de3de411aeef98875330779f1d6d0 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:11:50 +0800 Subject: [PATCH 229/282] [#130] added some parameters --- .circleci/config.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index e0abf434..eb3a9d73 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,6 +7,11 @@ jobs: docker: - image: circleci/ruby:2.6.3-stretch-node executor: ruby/default + parameters: + ruby_versions: + type: string + gemfiles: + type: string steps: - checkout - run: From 907cb7fdad1021529b73c4b008cf4b9ca270a85f Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:13:58 +0800 Subject: [PATCH 230/282] [#130] reduced matrix size --- .circleci/config.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index eb3a9d73..b085c020 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -25,5 +25,7 @@ workflows: - build: matrix: parameters: - ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] - gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] + # ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] + # gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] + ruby_versions: ["2.6.6", "2.7.1"] + gemfiles: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 9233de1fc5b362c7ec921fddc84875fb7c3bafa6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:16:38 +0800 Subject: [PATCH 231/282] [#130] trying to install specific gemfile --- .circleci/config.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b085c020..95dae6ab 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -8,16 +8,16 @@ jobs: - image: circleci/ruby:2.6.3-stretch-node executor: ruby/default parameters: - ruby_versions: + ruby_version: type: string - gemfiles: + gemfile: type: string steps: - checkout - run: name: Which bundler? command: bundle -v - - ruby/bundle-install + - ruby/bundle-install --gemfile=<< parameters.gemfile >> workflows: test_suite: @@ -27,5 +27,5 @@ workflows: parameters: # ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] # gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] - ruby_versions: ["2.6.6", "2.7.1"] - gemfiles: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] + ruby_version: ["2.6.6", "2.7.1"] + gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 0daf511521ec597cc49eb72560ecbc6de53db209 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:21:33 +0800 Subject: [PATCH 232/282] [#130] installing bundler and trying to install specific gemfile --- .circleci/config.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 95dae6ab..254402eb 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,6 +1,6 @@ version: 2.1 -orbs: - ruby: circleci/ruby@0.1.2 +# orbs: +# ruby: circleci/ruby@0.1.2 jobs: build: @@ -14,10 +14,15 @@ jobs: type: string steps: - checkout + - run: + name: Install bundler + command: gem install bundler - run: name: Which bundler? command: bundle -v - - ruby/bundle-install --gemfile=<< parameters.gemfile >> + - run: + name: Install gems + command: bundle install --gemfile=<< parameters.gemfile >> workflows: test_suite: From 0314eceb4a0f4e4b450c2ead67e8ea7a7986c7eb Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:22:35 +0800 Subject: [PATCH 233/282] [#130] commented ruby default --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 254402eb..a9ed24b6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -6,7 +6,7 @@ jobs: build: docker: - image: circleci/ruby:2.6.3-stretch-node - executor: ruby/default + # executor: ruby/default parameters: ruby_version: type: string From 66c26a5a84133bb7470fcd7d78a8c4d3718747e4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:28:00 +0800 Subject: [PATCH 234/282] [#130] added rspec --- .circleci/config.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index a9ed24b6..8bd36948 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -23,6 +23,9 @@ jobs: - run: name: Install gems command: bundle install --gemfile=<< parameters.gemfile >> + - run: + name: Run tests + command: bundle exec rspec workflows: test_suite: From 8393b1288a3fc960db9ec8f05ec2eb5f9044c10e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:36:14 +0800 Subject: [PATCH 235/282] [#130] trying to have different ruby versions --- .circleci/config.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 8bd36948..550c2e6e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,7 +5,7 @@ version: 2.1 jobs: build: docker: - - image: circleci/ruby:2.6.3-stretch-node + - image: circleci/ruby:<< matrix.ruby_version >>-stretch-node # executor: ruby/default parameters: ruby_version: @@ -20,12 +20,16 @@ jobs: - run: name: Which bundler? command: bundle -v + - run: + name: Which ruby? + command: ruby -v - run: name: Install gems command: bundle install --gemfile=<< parameters.gemfile >> - - run: - name: Run tests - command: bundle exec rspec + # TODO: copy config/database.yml.samples before tests start + # - run: + # name: Run tests + # command: bundle exec rspec workflows: test_suite: From e68c8f06c4b7d7e9aaf3d5bed048740c188a8fdf Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:37:51 +0800 Subject: [PATCH 236/282] [#130] using parameters instead of matrix --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 550c2e6e..0e2703a9 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,7 +5,7 @@ version: 2.1 jobs: build: docker: - - image: circleci/ruby:<< matrix.ruby_version >>-stretch-node + - image: circleci/ruby:<< parameters.ruby_version >>-stretch-node # executor: ruby/default parameters: ruby_version: From 2e190fb92f1da917c42981b09728c174897fbd11 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:43:48 +0800 Subject: [PATCH 237/282] [#130] pointing to different imags --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 0e2703a9..3758477b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,7 +5,7 @@ version: 2.1 jobs: build: docker: - - image: circleci/ruby:<< parameters.ruby_version >>-stretch-node + - image: << parameters.ruby_version >> # executor: ruby/default parameters: ruby_version: @@ -39,5 +39,5 @@ workflows: parameters: # ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] # gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] - ruby_version: ["2.6.6", "2.7.1"] + ruby_version: ["ruby:2.6-alpine", "ruby:2.7-alpine", "jruby:9.2"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 6c3d25e2e89fd58ce2b2803873d62081b11689fa Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:47:08 +0800 Subject: [PATCH 238/282] [#130] trying buster --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 3758477b..119ce5be 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -39,5 +39,5 @@ workflows: parameters: # ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] # gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] - ruby_version: ["ruby:2.6-alpine", "ruby:2.7-alpine", "jruby:9.2"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 309fe46980158cd678bd6959241063194cad8080 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:50:11 +0800 Subject: [PATCH 239/282] [#130] copying spec config --- .circleci/config.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 119ce5be..f565d210 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,6 +26,9 @@ jobs: - run: name: Install gems command: bundle install --gemfile=<< parameters.gemfile >> + - run: + name: Configure spec config database.yml + command: cp spec/config/database.yml.sample spec/config/database.yml # TODO: copy config/database.yml.samples before tests start # - run: # name: Run tests @@ -37,7 +40,6 @@ workflows: - build: matrix: parameters: - # ruby_versions: ["jruby-9.2.11.0", "2.4.10", "2.5.8", "2.6.6", "2.7.1", "jruby-head", "ruby-head"] - # gemfiles: ["gemfiles/rails_5_0.gemfile", "gemfiles/rails_5_1.gemfile", "gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_master.gemfile"] + # TODO: figure out jruby image with git ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 6c7a68328adb215b3c147c120da54209bebcb674 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 12:52:42 +0800 Subject: [PATCH 240/282] [#130] trying to run tests --- .circleci/config.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index f565d210..f3613b89 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,13 +26,13 @@ jobs: - run: name: Install gems command: bundle install --gemfile=<< parameters.gemfile >> + # TODO: copy config/database.yml.samples before tests start - run: name: Configure spec config database.yml command: cp spec/config/database.yml.sample spec/config/database.yml - # TODO: copy config/database.yml.samples before tests start - # - run: - # name: Run tests - # command: bundle exec rspec + - run: + name: Run tests + command: bundle exec rspec workflows: test_suite: @@ -41,5 +41,5 @@ workflows: matrix: parameters: # TODO: figure out jruby image with git - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From c7b7284ce7b2d2a635c20be5aa6526f09594d2f1 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:04:11 +0800 Subject: [PATCH 241/282] [#130] setting gemfile path --- .circleci/config.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index f3613b89..2d637d0d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,17 +1,16 @@ version: 2.1 -# orbs: -# ruby: circleci/ruby@0.1.2 jobs: build: docker: - image: << parameters.ruby_version >> - # executor: ruby/default parameters: ruby_version: type: string gemfile: type: string + environment: + BUNDLE_GEMFILE: << parameters.gemfile >> steps: - checkout - run: @@ -25,7 +24,7 @@ jobs: command: ruby -v - run: name: Install gems - command: bundle install --gemfile=<< parameters.gemfile >> + command: bundle install # TODO: copy config/database.yml.samples before tests start - run: name: Configure spec config database.yml From de4a938e7ecc8a845a9805a5fd8c44e35f3b786b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:08:28 +0800 Subject: [PATCH 242/282] [#130] copying spec dummy --- .circleci/config.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2d637d0d..2ea59da0 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -29,6 +29,9 @@ jobs: - run: name: Configure spec config database.yml command: cp spec/config/database.yml.sample spec/config/database.yml + - run: + name: Configure spec dummy config database.yml + command: cp spec/dummy/config/database.yml.sample spec/dummy/config/database.yml - run: name: Run tests command: bundle exec rspec From f9a8d7ddacad1c39c3995342e678bcfc83dc1c42 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:11:58 +0800 Subject: [PATCH 243/282] [#130] trying to start databases --- .circleci/config.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2ea59da0..1c384535 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -32,6 +32,9 @@ jobs: - run: name: Configure spec dummy config database.yml command: cp spec/dummy/config/database.yml.sample spec/dummy/config/database.yml + - run: + name: Start database services + command: docker-compose up -d - run: name: Run tests command: bundle exec rspec From 57756fa26f6ada6fce3cbc991c3139eb914767af Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:23:02 +0800 Subject: [PATCH 244/282] [#130] using circle image --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1c384535..31eb8896 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ version: 2.1 jobs: build: docker: - - image: << parameters.ruby_version >> + - image: circle/<< parameters.ruby_version >> parameters: ruby_version: type: string From 13bd1a1b048b386f501412692cad795a03e47b5c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:24:21 +0800 Subject: [PATCH 245/282] [#130] fixed docker image --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 31eb8896..c68d9fad 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ version: 2.1 jobs: build: docker: - - image: circle/<< parameters.ruby_version >> + - image: circleci/<< parameters.ruby_version >> parameters: ruby_version: type: string From 14ea863702aea90a14394f85369b4bdb54aa6736 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:29:44 +0800 Subject: [PATCH 246/282] [#130] checking docker version --- .circleci/config.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index c68d9fad..b35a5ba5 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -22,6 +22,9 @@ jobs: - run: name: Which ruby? command: ruby -v + - run: + name: Which docker? + command: docker -v - run: name: Install gems command: bundle install @@ -34,7 +37,7 @@ jobs: command: cp spec/dummy/config/database.yml.sample spec/dummy/config/database.yml - run: name: Start database services - command: docker-compose up -d + command: sudo docker-compose up -d - run: name: Run tests command: bundle exec rspec @@ -46,5 +49,7 @@ workflows: matrix: parameters: # TODO: figure out jruby image with git - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster"] - gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] + # ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] + ruby_version: ["ruby:2.7-buster"] + # gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] + gemfile: ["gemfiles/rails_6_0.gemfile"] From 2cc207b49b8cfb4f87dbbefff9c741f88c32d001 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 13:38:05 +0800 Subject: [PATCH 247/282] [#130] setup remote docker --- .circleci/config.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b35a5ba5..69a79428 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -35,9 +35,11 @@ jobs: - run: name: Configure spec dummy config database.yml command: cp spec/dummy/config/database.yml.sample spec/dummy/config/database.yml + - setup_remote_docker: + version: 19.03.13 - run: name: Start database services - command: sudo docker-compose up -d + command: docker-compose up -d - run: name: Run tests command: bundle exec rspec From 78926082e5c68b253568cd385415381fe5bd0c88 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:08:20 +0800 Subject: [PATCH 248/282] [#130] trying to wait --- .circleci/config.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 69a79428..318730a8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -40,6 +40,12 @@ jobs: - run: name: Start database services command: docker-compose up -d + - run: + name: wait for postgresql + command: dockerize -wait tcp://localhost:5432 -timeout 1m + - run: + name: wait for mysql + command: dockerize -wait tcp://localhost:3306 -timeout 1m - run: name: Run tests command: bundle exec rspec From 612cc494cd70178d9e051c68282fc5662032796c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:29:31 +0800 Subject: [PATCH 249/282] [#130] trying cache and wait for mysql only --- .circleci/config.yml | 46 ++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 318730a8..5a102cfa 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -13,39 +13,43 @@ jobs: BUNDLE_GEMFILE: << parameters.gemfile >> steps: - checkout - - run: - name: Install bundler - command: gem install bundler - - run: - name: Which bundler? - command: bundle -v - - run: - name: Which ruby? - command: ruby -v - - run: - name: Which docker? - command: docker -v - - run: - name: Install gems - command: bundle install - # TODO: copy config/database.yml.samples before tests start + # Restore Cached Dependencies + - restore_cache: + keys: + - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "Gemfile.lock" }} + - gem-cache-v1-{{ arch }}-{{ .Branch }} + - gem-cache-v1 + + - run: bundle install --path vendor/bundle + + - save_cache: + key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "Gemfile.lock" }} + paths: + - vendor/bundle + - run: name: Configure spec config database.yml - command: cp spec/config/database.yml.sample spec/config/database.yml + command: cp spec/config/{database.yml.sample,database.yml} + - run: name: Configure spec dummy config database.yml - command: cp spec/dummy/config/database.yml.sample spec/dummy/config/database.yml + command: cp spec/dummy/config/{database.yml.sample,database.yml} + - setup_remote_docker: version: 19.03.13 + - run: name: Start database services command: docker-compose up -d - - run: - name: wait for postgresql - command: dockerize -wait tcp://localhost:5432 -timeout 1m + + # - run: + # name: wait for postgresql + # command: dockerize -wait tcp://localhost:5432 -timeout 1m + - run: name: wait for mysql command: dockerize -wait tcp://localhost:3306 -timeout 1m + - run: name: Run tests command: bundle exec rspec From 5e2b0110648ea1a03ab6f8dfc98238bdf296f692 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:49:44 +0800 Subject: [PATCH 250/282] [#130] usign bundle gemfile --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 5a102cfa..a313dafd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -16,14 +16,14 @@ jobs: # Restore Cached Dependencies - restore_cache: keys: - - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "Gemfile.lock" }} + - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "$BUNDLE_GEMFILE.lock" }} - gem-cache-v1-{{ arch }}-{{ .Branch }} - gem-cache-v1 - run: bundle install --path vendor/bundle - save_cache: - key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "Gemfile.lock" }} + key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "$BUNDLE_GEMFILE.lock" }} paths: - vendor/bundle From ad2665bdc2c064e27fb13476ef09bd65d6f8a898 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:52:17 +0800 Subject: [PATCH 251/282] [#130] trying to interpolate --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index a313dafd..656fcd6a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -16,14 +16,14 @@ jobs: # Restore Cached Dependencies - restore_cache: keys: - - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "$BUNDLE_GEMFILE.lock" }} + - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "${BUNDLE_GEMFILE}.lock" }} - gem-cache-v1-{{ arch }}-{{ .Branch }} - gem-cache-v1 - run: bundle install --path vendor/bundle - save_cache: - key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "$BUNDLE_GEMFILE.lock" }} + key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "${BUNDLE_GEMFILE}.lock" }} paths: - vendor/bundle From be46fad3b246a42f2b4d84b6c6438557bfb986a7 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:54:09 +0800 Subject: [PATCH 252/282] [#130] using parameters --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 656fcd6a..98b10b55 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -16,14 +16,14 @@ jobs: # Restore Cached Dependencies - restore_cache: keys: - - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "${BUNDLE_GEMFILE}.lock" }} + - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.bundle_gemfile >>.lock" }} - gem-cache-v1-{{ arch }}-{{ .Branch }} - gem-cache-v1 - run: bundle install --path vendor/bundle - save_cache: - key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "${BUNDLE_GEMFILE}.lock" }} + key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.bundle_gemfile >>.lock" }} paths: - vendor/bundle From b48e481e6f6fb2ba644f6973577b0dc4182a7df5 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 14:55:05 +0800 Subject: [PATCH 253/282] [#130] fixed parameter name --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 98b10b55..bccb709d 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -16,14 +16,14 @@ jobs: # Restore Cached Dependencies - restore_cache: keys: - - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.bundle_gemfile >>.lock" }} + - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} - gem-cache-v1-{{ arch }}-{{ .Branch }} - gem-cache-v1 - run: bundle install --path vendor/bundle - save_cache: - key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.bundle_gemfile >>.lock" }} + key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} paths: - vendor/bundle From ade1d9c3a4dceb12111bae1136942e7437525446 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 15:03:45 +0800 Subject: [PATCH 254/282] [#130] trying multiple docker images --- .circleci/config.yml | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index bccb709d..5ba3b2ce 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,6 +4,10 @@ jobs: build: docker: - image: circleci/<< parameters.ruby_version >> + - image: circleci/postgres:9.6.2-alpine + - image: circleci/mysql:5.7 + environment: + MYSQL_ALLOW_EMPTY_PASSWORD: "yes" parameters: ruby_version: type: string @@ -35,16 +39,9 @@ jobs: name: Configure spec dummy config database.yml command: cp spec/dummy/config/{database.yml.sample,database.yml} - - setup_remote_docker: - version: 19.03.13 - - run: - name: Start database services - command: docker-compose up -d - - # - run: - # name: wait for postgresql - # command: dockerize -wait tcp://localhost:5432 -timeout 1m + name: wait for postgresql + command: dockerize -wait tcp://localhost:5432 -timeout 1m - run: name: wait for mysql From ae50827be0da3a6eea40c19b292ffc481a008f72 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 15:08:07 +0800 Subject: [PATCH 255/282] [#130] try to create db --- .circleci/config.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 5ba3b2ce..e3389240 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -47,6 +47,12 @@ jobs: name: wait for mysql command: dockerize -wait tcp://localhost:3306 -timeout 1m + - run: + name: Database Setup + command: | + bundle exec rake db:create + bundle exec rake db:structure:load + - run: name: Run tests command: bundle exec rspec From 4cd75147a87b7a94ea9503cdefb791b0b19df1de Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 15:20:21 +0800 Subject: [PATCH 256/282] [#130] using rake available commands --- .circleci/config.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index e3389240..c6be0ca5 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -50,8 +50,7 @@ jobs: - run: name: Database Setup command: | - bundle exec rake db:create - bundle exec rake db:structure:load + bundle exec rake mysql:build_db postgres:build_db - run: name: Run tests From f0dc0ebc3ac3c84cbe348caa2c6139fd802cb660 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 15:51:35 +0800 Subject: [PATCH 257/282] [#130] trying to create pg db --- .circleci/config.yml | 33 +++++++++++++++++++-------------- Rakefile | 1 + 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index c6be0ca5..58b22c64 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -18,26 +18,26 @@ jobs: steps: - checkout # Restore Cached Dependencies - - restore_cache: - keys: - - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} - - gem-cache-v1-{{ arch }}-{{ .Branch }} - - gem-cache-v1 + # - restore_cache: + # keys: + # - gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} + # - gem-cache-v1-{{ arch }}-{{ .Branch }} + # - gem-cache-v1 - run: bundle install --path vendor/bundle - - save_cache: - key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} - paths: - - vendor/bundle + # - save_cache: + # key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }} + # paths: + # - vendor/bundle - run: - name: Configure spec config database.yml - command: cp spec/config/{database.yml.sample,database.yml} + name: Install postgres client + command: sudo apt install -y postgresql-client - run: - name: Configure spec dummy config database.yml - command: cp spec/dummy/config/{database.yml.sample,database.yml} + name: Configure config database.yml + command: bundle exec rake db:copy_credentials - run: name: wait for postgresql @@ -47,10 +47,15 @@ jobs: name: wait for mysql command: dockerize -wait tcp://localhost:3306 -timeout 1m + # - run: + # name: Database Setup + # command: | + # bundle exec rake db:test:prepare + - run: name: Database Setup command: | - bundle exec rake mysql:build_db postgres:build_db + bundle exec rake postgres:build_db - run: name: Run tests diff --git a/Rakefile b/Rakefile index 948bd059..6415d2e8 100644 --- a/Rakefile +++ b/Rakefile @@ -65,6 +65,7 @@ namespace :postgres do params << "-U#{pg_config['username']}" params << "-h#{pg_config['host']}" if pg_config['host'] params << "-p#{pg_config['port']}" if pg_config['port'] + begin `createdb #{params.join(' ')}` rescue StandardError From 95604abd34bcf0d33243d74e857cd7591acadfe1 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 15:55:59 +0800 Subject: [PATCH 258/282] [#130] trying to install mysqladmin --- .circleci/config.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.circleci/config.yml b/.circleci/config.yml index 58b22c64..957e5e55 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -35,6 +35,10 @@ jobs: name: Install postgres client command: sudo apt install -y postgresql-client + - run: + name: Install mysql client + command: sudo apt install -y mysql-server + - run: name: Configure config database.yml command: bundle exec rake db:copy_credentials From 5095f12a6ff11daaefa3faa15dcc14a072c06f1e Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:06:21 +0800 Subject: [PATCH 259/282] [#130] installing mysql and prep db --- .circleci/config.yml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 957e5e55..2774cd15 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -37,7 +37,7 @@ jobs: - run: name: Install mysql client - command: sudo apt install -y mysql-server + command: sudo apt install -y default-mysql-client - run: name: Configure config database.yml @@ -51,15 +51,10 @@ jobs: name: wait for mysql command: dockerize -wait tcp://localhost:3306 -timeout 1m - # - run: - # name: Database Setup - # command: | - # bundle exec rake db:test:prepare - - run: name: Database Setup command: | - bundle exec rake postgres:build_db + bundle exec rake db:test:prepare - run: name: Run tests From 9b41e4e866624bd9f2d90b3ab57c73bd1910299a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:15:59 +0800 Subject: [PATCH 260/282] [#130] add back jruby and rails 5_2 gemfile --- .circleci/config.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 2774cd15..046075ad 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,8 +66,5 @@ workflows: - build: matrix: parameters: - # TODO: figure out jruby image with git - # ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] - ruby_version: ["ruby:2.7-buster"] - # gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] - gemfile: ["gemfiles/rails_6_0.gemfile"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] + gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 6bc13ac2367ea67ae2b8f90ab9403d11566db0c9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:17:26 +0800 Subject: [PATCH 261/282] [#130] removed travis.yml --- .travis.yml | 49 ------------------------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 784d4b5c..00000000 --- a/.travis.yml +++ /dev/null @@ -1,49 +0,0 @@ -os: linux - -language: ruby -services: - - docker -rvm: - - jruby-9.2.11.0 - - 2.4.10 - - 2.5.8 - - 2.6.6 - - 2.7.1 - - jruby-head - - ruby-head - -branches: - only: - - master - - development - -gemfile: - - gemfiles/rails_5_0.gemfile - - gemfiles/rails_5_1.gemfile - - gemfiles/rails_5_2.gemfile - - gemfiles/rails_6_0.gemfile - - gemfiles/rails_master.gemfile - -bundler_args: --without local -before_install: - - sudo /etc/init.d/mysql stop - - sudo /etc/init.d/postgresql stop - - docker-compose up -d - -env: - RUBY_GC_MALLOC_LIMIT: 90000000 - RUBY_GC_HEAP_FREE_SLOTS: 200000 -jobs: - include: - - name: Rubocop Lint - script: gem install rubocop - - allow_failures: - - rvm: ruby-head - - rvm: jruby-head - - gemfile: gemfiles/rails_master.gemfile - exclude: - - rvm: 2.4.10 - gemfile: gemfiles/rails_6_0.gemfile - fast_finish: true -cache: bundler From 98e97520e100a339b2b5506d1d96f517c02f7a6a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:34:28 +0800 Subject: [PATCH 262/282] [#130] trying new jruby version --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 046075ad..10f46a28 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,5 +66,5 @@ workflows: - build: matrix: parameters: - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.13-jdk14"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 925b5b0767726f1b2a9b27f53f40ed31e2b84dd2 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:46:07 +0800 Subject: [PATCH 263/282] [#130] lower jruby version to match what travis was running --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 10f46a28..bdfe8641 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,5 +66,5 @@ workflows: - build: matrix: parameters: - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.13-jdk14"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk14"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From beed58fa7f743f5d95951694ec612a703874d322 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 16:58:38 +0800 Subject: [PATCH 264/282] [#130] try other jruby version --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index bdfe8641..b2a4d8e7 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,5 +66,5 @@ workflows: - build: matrix: parameters: - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk14"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk11"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 93f04ba787c92d298e3e76f9f1ae5bfa4f9d4211 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 17:01:31 +0800 Subject: [PATCH 265/282] [#130] try other jruby version --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index b2a4d8e7..42d69887 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,5 +66,5 @@ workflows: - build: matrix: parameters: - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk11"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk8"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 276e5da69af0393d96e431a9f5d9e31896134ff9 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 17:03:48 +0800 Subject: [PATCH 266/282] [#130] removed jruby for now --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 42d69887..ac75da7e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -66,5 +66,5 @@ workflows: - build: matrix: parameters: - ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster", "jruby:9.2.11.1-jdk8"] + ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] From 9263f9f67bf4136b69c7f4a2fd40a42a891dba5a Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 17:21:23 +0800 Subject: [PATCH 267/282] [#134] added rubocop to workflows --- .circleci/config.yml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index ac75da7e..9cc48303 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,5 +1,8 @@ version: 2.1 +orbs: + rubocop: hanachin/rubocop@0.0.6 + jobs: build: docker: @@ -61,10 +64,14 @@ jobs: command: bundle exec rspec workflows: - test_suite: + tests: jobs: - build: matrix: parameters: ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster"] gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] + + rubocop: + jobs: + - rubocop/rubocop From a885ffca5fa64af3f9242858c2184e7cf7130d9c Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 18:12:57 +0800 Subject: [PATCH 268/282] [#134] fixed some of the rubocops --- Rakefile | 4 ++-- lib/apartment/adapters/postgresql_adapter.rb | 4 ++-- lib/apartment/log_subscriber.rb | 1 + lib/apartment/railtie.rb | 13 ++++++++----- spec/examples/generic_adapter_examples.rb | 10 +++++----- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/Rakefile b/Rakefile index 6415d2e8..1769f7d0 100644 --- a/Rakefile +++ b/Rakefile @@ -47,9 +47,9 @@ namespace :db do rails_db_file = 'spec/dummy/config/database.yml' unless File.exist?(apartment_db_file) - FileUtils.copy(apartment_db_file + '.sample', apartment_db_file, verbose: true) + FileUtils.copy("#{apartment_db_file}.sample", apartment_db_file, verbose: true) end - FileUtils.copy(rails_db_file + '.sample', rails_db_file, verbose: true) unless File.exist?(rails_db_file) + FileUtils.copy("#{rails_db_file}.sample", rails_db_file, verbose: true) unless File.exist?(rails_db_file) end end diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index fd2ea683..9540f016 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -98,7 +98,7 @@ def tenant_exists?(tenant) def create_tenant_command(conn, tenant) # NOTE: This was causing some tests to fail because of the database strategy for rspec - if ActiveRecord::Base.connection.open_transactions > 0 + if ActiveRecord::Base.connection.open_transactions.positive? conn.execute(%(CREATE SCHEMA "#{tenant}")) else schema = %(BEGIN; @@ -113,7 +113,7 @@ def create_tenant_command(conn, tenant) end def rollback_transaction(conn) - conn.execute("ROLLBACK;") + conn.execute('ROLLBACK;') end # Generate the final search path to set including persistent_schemas diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb index 237bebf4..9345b036 100644 --- a/lib/apartment/log_subscriber.rb +++ b/lib/apartment/log_subscriber.rb @@ -3,6 +3,7 @@ require 'active_record/log_subscriber' module Apartment + # Custom Log subscriber to include database name and schema name in sql logs class LogSubscriber < ActiveRecord::LogSubscriber def sql(event) super(event) diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 18b47644..649c6fcd 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -6,7 +6,6 @@ module Apartment class Railtie < Rails::Railtie - # # Set up our default config options # Do this before the app initializers run so we don't override custom settings @@ -27,13 +26,14 @@ class Railtie < Rails::Railtie end # Hook into ActionDispatch::Reloader to ensure Apartment is properly initialized - # Note that this doens't entirely work as expected in Development, because this is called before classes are reloaded + # Note that this doesn't entirely work as expected in Development, + # because this is called before classes are reloaded # See the middleware/console declarations below to help with this. Hope to fix that soon. # config.to_prepare do next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } next if ARGV.any? { |arg| arg == 'webpacker:compile' } - next if ENV["APARTMENT_DISABLE_INIT"] + next if ENV['APARTMENT_DISABLE_INIT'] begin Apartment.connection_class.connection_pool.with_connection do @@ -45,7 +45,7 @@ class Railtie < Rails::Railtie end end - config.after_initialize do |app| + config.after_initialize do # NOTE: Load the custom log subscriber if enabled if Apartment.active_record_log ActiveSupport::Notifications.unsubscribe 'sql.active_record' @@ -72,10 +72,13 @@ class Railtie < Rails::Railtie app.config.middleware.use Apartment::Reloader end - # Overrides reload! to also call Apartment::Tenant.init as well so that the reloaded classes have the proper table_names + # Overrides reload! to also call Apartment::Tenant.init as well + # so that the reloaded classes have the proper table_names + # rubocop:disable Lint/Debugger console do require 'apartment/console' end + # rubocop:enable Lint/Debugger end end end diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index 767b122c..cbe6013f 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -26,20 +26,20 @@ end it 'should not connect if env var is set' do - ENV["APARTMENT_DISABLE_INIT"] = "true" + ENV['APARTMENT_DISABLE_INIT'] = 'true' begin ActiveRecord::Base.connection_pool.disconnect! Apartment::Railtie.config.to_prepare_blocks.map(&:call) num_available_connections = Apartment.connection_class.connection_pool - .instance_variable_get(:@available) - .instance_variable_get(:@queue) - .size + .instance_variable_get(:@available) + .instance_variable_get(:@queue) + .size expect(num_available_connections).to eq(0) ensure - ENV.delete("APARTMENT_DISABLE_INIT") + ENV.delete('APARTMENT_DISABLE_INIT') end end end From 80afbac5e409cb5aed18d4f92cf87c2ef6a83d92 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 21:34:06 +0800 Subject: [PATCH 269/282] [#134] addressed most of rubocop issues --- .circleci/config.yml | 3 ++- .rubocop.yml | 1 + lib/apartment/adapters/abstract_adapter.rb | 2 ++ lib/apartment/console.rb | 4 +++- lib/apartment/log_subscriber.rb | 3 +++ lib/apartment/tenant.rb | 5 +++-- spec/spec_helper.rb | 2 ++ spec/support/setup.rb | 2 ++ 8 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 9cc48303..edfeb0fc 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -74,4 +74,5 @@ workflows: rubocop: jobs: - - rubocop/rubocop + - rubocop/rubocop: + version: 0.88.0 diff --git a/.rubocop.yml b/.rubocop.yml index b0a4cc6c..4f62ff04 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -4,6 +4,7 @@ AllCops: Exclude: - 'gemfiles/**/*.gemfile' - 'gemfiles/vendor/**/*' + - 'spec/dummy_engine/dummy_engine.gemspec' Style/WordArray: Exclude: diff --git a/lib/apartment/adapters/abstract_adapter.rb b/lib/apartment/adapters/abstract_adapter.rb index 8ca4f308..e59ba523 100644 --- a/lib/apartment/adapters/abstract_adapter.rb +++ b/lib/apartment/adapters/abstract_adapter.rb @@ -201,11 +201,13 @@ def import_database_schema # @param {String} tenant: Database name # @param {Boolean} with_database: if true, use the actual tenant's db name # if false, use the default db name from the db + # rubocop:disable Style/OptionalBooleanParameter def multi_tenantify(tenant, with_database = true) db_connection_config(tenant).tap do |config| multi_tenantify_with_tenant_db_name(config, tenant) if with_database end end + # rubocop:enable Style/OptionalBooleanParameter def multi_tenantify_with_tenant_db_name(config, tenant) config[:database] = environmentify(tenant) diff --git a/lib/apartment/console.rb b/lib/apartment/console.rb index 1398fe72..91721222 100644 --- a/lib/apartment/console.rb +++ b/lib/apartment/console.rb @@ -1,9 +1,10 @@ # frozen_string_literal: true -# A workaraound to get `reload!` to also call Apartment::Tenant.init +# A workaround to get `reload!` to also call Apartment::Tenant.init # This is unfortunate, but I haven't figured out how to hook into the reload process *after* files are reloaded # reloads the environment +# rubocop:disable Style/OptionalBooleanParameter def reload!(print = true) puts 'Reloading...' if print @@ -13,6 +14,7 @@ def reload!(print = true) Apartment::Tenant.init true end +# rubocop:enable Style/OptionalBooleanParameter def st(schema_name = nil) if schema_name.nil? diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb index 9345b036..a9e06e5e 100644 --- a/lib/apartment/log_subscriber.rb +++ b/lib/apartment/log_subscriber.rb @@ -5,9 +5,12 @@ module Apartment # Custom Log subscriber to include database name and schema name in sql logs class LogSubscriber < ActiveRecord::LogSubscriber + # NOTE: for some reason, if the method definition is not here, then the custom debug method is not called + # rubocop:disable Lint/UselessMethodDefinition def sql(event) super(event) end + # rubocop:enable Lint/UselessMethodDefinition private diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 32f69ca7..01f0ead2 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -24,9 +24,10 @@ def adapter adapter_method = "#{config[:adapter]}_adapter" if defined?(JRUBY_VERSION) - if config[:adapter] =~ /mysql/ + case config[:adapter] + when /mysql/ adapter_method = 'jdbc_mysql_adapter' - elsif config[:adapter] =~ /postgresql/ + when /postgresql/ adapter_method = 'jdbc_postgresql_adapter' end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 68b9c680..f5ba6bbe 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -22,12 +22,14 @@ require 'capybara/rspec' require 'capybara/rails' +# rubocop:disable Lint/ConstantDefinitionInBlock begin require 'pry' silence_warnings { IRB = Pry } rescue LoadError nil end +# rubocop:enable Lint/ConstantDefinitionInBlock ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true diff --git a/spec/support/setup.rb b/spec/support/setup.rb index ef650383..109cbaef 100644 --- a/spec/support/setup.rb +++ b/spec/support/setup.rb @@ -3,6 +3,7 @@ module Apartment module Spec module Setup + # rubocop:disable Metrics/AbcSize def self.included(base) base.instance_eval do let(:db1) { Apartment::Test.next_db } @@ -41,6 +42,7 @@ def config end end end + # rubocop:enable Metrics/AbcSize end end end From 96405a397996ebb500d842a885afe9a635e1f35b Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 21:44:39 +0800 Subject: [PATCH 270/282] [#134] disable rules for constant definition in block --- spec/examples/generic_adapters_callbacks_examples.rb | 2 ++ spec/unit/elevators/generic_spec.rb | 2 ++ 2 files changed, 4 insertions(+) diff --git a/spec/examples/generic_adapters_callbacks_examples.rb b/spec/examples/generic_adapters_callbacks_examples.rb index 5d878d38..3184a4a1 100644 --- a/spec/examples/generic_adapters_callbacks_examples.rb +++ b/spec/examples/generic_adapters_callbacks_examples.rb @@ -3,9 +3,11 @@ require 'spec_helper' shared_examples_for 'a generic apartment adapter callbacks' do + # rubocop:disable Lint/ConstantDefinitionInBlock class MyProc def self.call(tenant_name); end end + # rubocop:enable Lint/ConstantDefinitionInBlock include Apartment::Spec::AdapterRequirements diff --git a/spec/unit/elevators/generic_spec.rb b/spec/unit/elevators/generic_spec.rb index b282a5af..f4112e78 100644 --- a/spec/unit/elevators/generic_spec.rb +++ b/spec/unit/elevators/generic_spec.rb @@ -4,11 +4,13 @@ require 'apartment/elevators/generic' describe Apartment::Elevators::Generic do + # rubocop:disable Lint/ConstantDefinitionInBlock class MyElevator < described_class def parse_tenant_name(*) 'tenant2' end end + # rubocop:enable Lint/ConstantDefinitionInBlock subject(:elevator) { described_class.new(proc {}) } From 7005842e3a5641de1f7475d4092c2fa064cf6c5d Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 17 Dec 2020 21:48:25 +0800 Subject: [PATCH 271/282] [#134] disable minimum ruby version --- .rubocop.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.rubocop.yml b/.rubocop.yml index 4f62ff04..b7c5c8b6 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -6,6 +6,10 @@ AllCops: - 'gemfiles/vendor/**/*' - 'spec/dummy_engine/dummy_engine.gemspec' +Gemspec/RequiredRubyVersion: + Exclude: + - 'ros-apartment.gemspec' + Style/WordArray: Exclude: - spec/schemas/**/*.rb From 9a49689a0df6c1cbb4bf73f0b080cabe2c1ac579 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 18 Dec 2020 00:58:45 +0800 Subject: [PATCH 272/282] [#127] Fixed method to get the current db name --- lib/apartment/log_subscriber.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/log_subscriber.rb b/lib/apartment/log_subscriber.rb index a9e06e5e..119acbee 100644 --- a/lib/apartment/log_subscriber.rb +++ b/lib/apartment/log_subscriber.rb @@ -21,7 +21,7 @@ def debug(progname = nil, &block) end def apartment_log - database = color("[#{Apartment.connection.current_database}] ", ActiveSupport::LogSubscriber::MAGENTA, true) + database = color("[#{Apartment.connection.raw_connection.db}] ", ActiveSupport::LogSubscriber::MAGENTA, true) schema = nil unless Apartment.connection.schema_search_path.nil? schema = color("[#{Apartment.connection.schema_search_path.tr('"', '')}] ", From c0e4a6a46f9a021dc09c13fef10f417d041f92f4 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 18 Dec 2020 01:29:18 +0800 Subject: [PATCH 273/282] [#127] updated changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb38ac55..4ce60fbe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ **Fixed bugs:** - New version raises an error with ActiveSupport::LogSubscriber [#128](https://github.com/rails-on-services/apartment/issues/128) +- Weird logs when tenant fails to create [#127]() **Closed issues:** From 4bdec0835ff79948d551ba0d677fbcf43fdbf811 Mon Sep 17 00:00:00 2001 From: Nick Gal Date: Thu, 17 Dec 2020 09:35:49 -0800 Subject: [PATCH 274/282] Update README.md Update readme example for `active_record_log` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b4a5112..fa033c09 100644 --- a/README.md +++ b/README.md @@ -351,7 +351,7 @@ Please note that our custom logger inherits from `ActiveRecord::LogSubscriber` s ```ruby Apartment.configure do |config| - active_record_log = true + config.active_record_log = true end ``` From 14159c2e9cada2519dbd8fda7775b8405c4e44b6 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 18 Dec 2020 01:57:13 +0800 Subject: [PATCH 275/282] updated rc2 version --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 7f3379e6..30c74076 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.8.1.rc1' + VERSION = '2.8.1.rc2' end From 6fbbaf271b8961dabf75296586231f9bafb6a327 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 18 Dec 2020 02:06:22 +0800 Subject: [PATCH 276/282] Removed delegator for non existent method --- lib/apartment/tenant.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/apartment/tenant.rb b/lib/apartment/tenant.rb index 01f0ead2..abbe87d5 100644 --- a/lib/apartment/tenant.rb +++ b/lib/apartment/tenant.rb @@ -10,8 +10,7 @@ module Tenant extend Forwardable def_delegators :adapter, :create, :drop, :switch, :switch!, :current, :each, - :reset, :init, :set_callback, :seed, :current_tenant, - :default_tenant, :environmentify + :reset, :init, :set_callback, :seed, :default_tenant, :environmentify attr_writer :config From 30f08c4b41b448172b319a5c40a9ad69302359ef Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Fri, 18 Dec 2020 09:15:10 +0800 Subject: [PATCH 277/282] Version Bump --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 30c74076..37e1cdee 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.8.1.rc2' + VERSION = '2.8.1' end From 50ebd85a46a28f4ab2817727f493545a5aeed7ba Mon Sep 17 00:00:00 2001 From: jonian Date: Fri, 18 Dec 2020 14:52:57 +0200 Subject: [PATCH 278/282] add config writer for db_migrate_tenant_missing_strategy --- lib/apartment.rb | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/apartment.rb b/lib/apartment.rb index 59a61cd1..a9506fd9 100644 --- a/lib/apartment.rb +++ b/lib/apartment.rb @@ -27,7 +27,7 @@ class << self WRITER_METHODS = %i[tenant_names database_schema_file excluded_models persistent_schemas connection_class - db_migrate_tenants seed_data_file + db_migrate_tenants db_migrate_tenant_missing_strategy seed_data_file parallel_migration_threads pg_excluded_names].freeze attr_accessor(*ACCESSOR_METHODS) @@ -72,6 +72,21 @@ def db_migrate_tenants @db_migrate_tenants = true end + # How to handle tenant missing on db:migrate + # defaults to :rescue_exception + # available options: rescue_exception, raise_exception, create_tenant + def db_migrate_tenant_missing_strategy + valid = %i[rescue_exception raise_exception create_tenant] + value = @db_migrate_tenant_missing_strategy || :rescue_exception + + return value if valid.include?(value) + + key_name = 'config.db_migrate_tenant_missing_strategy' + opt_names = valid.join(', ') + + raise ApartmentError, "Option #{value} not valid for `#{key_name}`. Use one of #{opt_names}" + end + # Default to empty array def excluded_models @excluded_models || [] From 8ab8bbd58c82c3e431e6acda6cc5e3c7ebd0d0de Mon Sep 17 00:00:00 2001 From: jonian Date: Fri, 18 Dec 2020 14:53:53 +0200 Subject: [PATCH 279/282] add migrate_tenant task helper --- lib/apartment/tasks/task_helper.rb | 12 ++++++++++++ lib/tasks/apartment.rake | 8 +------- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/lib/apartment/tasks/task_helper.rb b/lib/apartment/tasks/task_helper.rb index 6065c953..32cd908e 100644 --- a/lib/apartment/tasks/task_helper.rb +++ b/lib/apartment/tasks/task_helper.rb @@ -36,5 +36,17 @@ def self.create_tenant(tenant_name) rescue Apartment::TenantExists => e puts "Tried to create already existing tenant: #{e}" end + + def self.migrate_tenant(tenant_name) + strategy = Apartment.db_migrate_tenant_missing_strategy + create_tenant(tenant_name) if strategy == :create_tenant + + puts("Migrating #{tenant_name} tenant") + Apartment::Migrator.migrate tenant_name + rescue Apartment::TenantNotFound => e + raise e if strategy == :raise_exception + + puts e.message + end end end diff --git a/lib/tasks/apartment.rake b/lib/tasks/apartment.rake index 1ea98fed..5ae47c0f 100644 --- a/lib/tasks/apartment.rake +++ b/lib/tasks/apartment.rake @@ -30,13 +30,7 @@ apartment_namespace = namespace :apartment do task :migrate do Apartment::TaskHelper.warn_if_tenants_empty Apartment::TaskHelper.each_tenant do |tenant| - begin - Apartment::TaskHelper.create_tenant(tenant) - puts("Migrating #{tenant} tenant") - Apartment::Migrator.migrate tenant - rescue Apartment::TenantNotFound => e - puts e.message - end + Apartment::TaskHelper.migrate_tenant(tenant) end end From 1ec5af54634ec3a8c8222c2f34878b9b028f0a22 Mon Sep 17 00:00:00 2001 From: John Mortlock Date: Fri, 8 Jan 2021 09:08:22 +1030 Subject: [PATCH 280/282] Add Rails 6.1 to build matrix --- .circleci/config.yml | 2 +- Appraisals | 18 +++++++++++++++--- gemfiles/rails_6_1.gemfile | 23 +++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 gemfiles/rails_6_1.gemfile diff --git a/.circleci/config.yml b/.circleci/config.yml index edfeb0fc..2f3e3c8b 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -70,7 +70,7 @@ workflows: matrix: parameters: ruby_version: ["ruby:2.6-buster", "ruby:2.7-buster"] - gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile"] + gemfile: ["gemfiles/rails_5_2.gemfile", "gemfiles/rails_6_0.gemfile", "gemfiles/rails_6_1.gemfile"] rubocop: jobs: diff --git a/Appraisals b/Appraisals index 519e9767..5f55c5ac 100644 --- a/Appraisals +++ b/Appraisals @@ -45,14 +45,26 @@ appraise 'rails-6-0' do end end +appraise 'rails-6-1' do + gem 'rails', '~> 6.1.0' + platforms :ruby do + gem 'sqlite3', '~> 1.4' + end + platforms :jruby do + gem 'activerecord-jdbc-adapter', '~> 61.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 61.0' + gem 'activerecord-jdbcmysql-adapter', '~> 61.0' + end +end + appraise 'rails-master' do gem 'rails', git: 'https://github.com/rails/rails.git' platforms :ruby do gem 'sqlite3', '~> 1.4' end platforms :jruby do - gem 'activerecord-jdbc-adapter', '~> 52.0' - gem 'activerecord-jdbcpostgresql-adapter', '~> 52.0' - gem 'activerecord-jdbcmysql-adapter', '~> 52.0' + gem 'activerecord-jdbc-adapter', '~> 61.0' + gem 'activerecord-jdbcpostgresql-adapter', '~> 61.0' + gem 'activerecord-jdbcmysql-adapter', '~> 61.0' end end diff --git a/gemfiles/rails_6_1.gemfile b/gemfiles/rails_6_1.gemfile new file mode 100644 index 00000000..e6de4f27 --- /dev/null +++ b/gemfiles/rails_6_1.gemfile @@ -0,0 +1,23 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 6.1.0" +gem "rubocop" + +group :local do + gem "guard-rspec", "~> 4.2" + gem "pry" +end + +platforms :ruby do + gem "sqlite3", "~> 1.4" +end + +platforms :jruby do + gem "activerecord-jdbc-adapter", "~> 61.0" + gem "activerecord-jdbcpostgresql-adapter", "~> 61.0" + gem "activerecord-jdbcmysql-adapter", "~> 61.0" +end + +gemspec path: "../" From 6ce41138337a46829e9a06ff31c7811a7e42aa18 Mon Sep 17 00:00:00 2001 From: Rui Baltazar Date: Thu, 21 Jan 2021 23:30:50 +0800 Subject: [PATCH 281/282] version bump --- lib/apartment/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/apartment/version.rb b/lib/apartment/version.rb index 37e1cdee..7ec53121 100644 --- a/lib/apartment/version.rb +++ b/lib/apartment/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Apartment - VERSION = '2.8.1' + VERSION = '2.9.0' end From 19770a1a1b24d1771e57d738d8a139317b1f49e9 Mon Sep 17 00:00:00 2001 From: Ryan Brunner Date: Mon, 1 Oct 2018 10:23:48 -0400 Subject: [PATCH 282/282] Allow a list of schemas when switching using schemas --- README.md | 8 ++++++++ lib/apartment/adapters/jdbc_postgresql_adapter.rb | 5 +++-- lib/apartment/adapters/postgresql_adapter.rb | 9 +++++---- spec/examples/schema_adapter_examples.rb | 7 +++++++ 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fa033c09..5e58ffb0 100644 --- a/README.md +++ b/README.md @@ -84,6 +84,14 @@ would not allow a full new database to be created. One can optionally use the full database creation instead if they want, though this is not recommended +When using schemas, you can also pass in a list of schemas if desired. Any tables defined in a schema earlier in the chain will be referenced first, so this is only useful if you have a schema with only some of the tables defined: + +```ruby +Apartment::Tenant.switch(['tenant_1', 'tenant_2']) do + # ... +end +``` + ### Switching Tenants To switch tenants using Apartment, use the following command: diff --git a/lib/apartment/adapters/jdbc_postgresql_adapter.rb b/lib/apartment/adapters/jdbc_postgresql_adapter.rb index 70dbadf3..57cf2fa5 100644 --- a/lib/apartment/adapters/jdbc_postgresql_adapter.rb +++ b/lib/apartment/adapters/jdbc_postgresql_adapter.rb @@ -38,9 +38,10 @@ class JDBCPostgresqlSchemaAdapter < PostgresqlSchemaAdapter # def connect_to_new(tenant = nil) return reset if tenant.nil? + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless schema_exists?(tenant) - tenant = tenant.to_s - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) + @current = tenant.is_a?(Array) ? tenant.map(&:to_s) : tenant.to_s + Apartment.connection.schema_search_path = full_search_path @current = tenant Apartment.connection.schema_search_path = full_search_path diff --git a/lib/apartment/adapters/postgresql_adapter.rb b/lib/apartment/adapters/postgresql_adapter.rb index 9540f016..860523a7 100644 --- a/lib/apartment/adapters/postgresql_adapter.rb +++ b/lib/apartment/adapters/postgresql_adapter.rb @@ -72,11 +72,9 @@ def drop_command(conn, tenant) # def connect_to_new(tenant = nil) return reset if tenant.nil? + raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless schema_exists?(tenant) - tenant = tenant.to_s - raise ActiveRecord::StatementInvalid, "Could not find schema #{tenant}" unless tenant_exists?(tenant) - - @current = tenant + @current = tenant.is_a?(Array) ? tenant.map(&:to_s) : tenant.to_s Apartment.connection.schema_search_path = full_search_path # When the PostgreSQL version is < 9.3, @@ -148,6 +146,9 @@ def reset_sequence_names # unreproduceable error we're checking before trying to remove it c.remove_instance_variable :@sequence_name if c.instance_variable_defined?(:@sequence_name) end + + def schema_exists?(schemas) + [*schemas].all? { |schema| Apartment.connection.schema_exists?(schema.to_s) } end end diff --git a/spec/examples/schema_adapter_examples.rb b/spec/examples/schema_adapter_examples.rb index 447322e3..f8c98ac7 100644 --- a/spec/examples/schema_adapter_examples.rb +++ b/spec/examples/schema_adapter_examples.rb @@ -127,6 +127,13 @@ expect(connection.schema_search_path).to start_with %("#{public_schema}") expect(User.sequence_name).to eq "#{public_schema}.#{User.table_name}_id_seq" end + + it "allows a list of schemas" do + subject.switch([schema1, schema2]) do + expect(connection.schema_search_path).to include %{"#{schema1}"} + expect(connection.schema_search_path).to include %{"#{schema2}"} + end + end end describe '#reset' do