Skip to content

Commit

Permalink
Merge pull request influitive#131 from rails-on-services/development
Browse files Browse the repository at this point in the history
Prepare Release - 2.8.1

**Implemented enhancements:**

**Fixed bugs:**

- New version raises an error with ActiveSupport::LogSubscriber [influitive#128](rails-on-services/apartment#128)
- Weird logs when tenant fails to create [influitive#127](<rails-on-services/apartment#127>)

**Closed issues:**

- Removed travis and slim configured circleci [influitive#130](rails-on-services/apartment#130)
  • Loading branch information
rpbaltazar authored Dec 18, 2020
2 parents 8964442 + 6fbbaf2 commit 2f62620
Show file tree
Hide file tree
Showing 21 changed files with 184 additions and 83 deletions.
78 changes: 78 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
version: 2.1

orbs:
rubocop: hanachin/rubocop@0.0.6

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
gemfile:
type: string
environment:
BUNDLE_GEMFILE: << parameters.gemfile >>
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

- run: bundle install --path vendor/bundle

# - save_cache:
# key: gem-cache-v1-{{ arch }}-{{ .Branch }}-{{ checksum "<< parameters.gemfile >>.lock" }}
# paths:
# - vendor/bundle

- run:
name: Install postgres client
command: sudo apt install -y postgresql-client

- run:
name: Install mysql client
command: sudo apt install -y default-mysql-client

- run:
name: Configure config database.yml
command: bundle exec rake db:copy_credentials

- 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: Database Setup
command: |
bundle exec rake db:test:prepare
- run:
name: Run tests
command: bundle exec rspec

workflows:
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:
version: 0.88.0
5 changes: 5 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ AllCops:
Exclude:
- 'gemfiles/**/*.gemfile'
- 'gemfiles/vendor/**/*'
- 'spec/dummy_engine/dummy_engine.gemspec'

Gemspec/RequiredRubyVersion:
Exclude:
- 'ros-apartment.gemspec'

Style/WordArray:
Exclude:
Expand Down
49 changes: 0 additions & 49 deletions .travis.yml

This file was deleted.

38 changes: 26 additions & 12 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,41 @@

## [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)
- Weird logs when tenant fails to create [#127](<https://github.com/rails-on-services/apartment/issues/127>)

**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)

Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,23 @@ 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.

Please note that our custom logger inherits from `ActiveRecord::LogSubscriber` so this will be required for the configuration to work.

**Example log output:**

<img src="documentation/images/log_example.png">

```ruby
Apartment.configure do |config|
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:
Expand Down
5 changes: 3 additions & 2 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
Binary file added documentation/images/log_example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions lib/apartment/adapters/abstract_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions lib/apartment/adapters/postgresql_adapter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
4 changes: 3 additions & 1 deletion lib/apartment/console.rb
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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?
Expand Down
8 changes: 7 additions & 1 deletion lib/apartment/log_subscriber.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
# frozen_string_literal: true

require 'active_record/log_subscriber'

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

Expand All @@ -15,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('"', '')}] ",
Expand Down
13 changes: 8 additions & 5 deletions lib/apartment/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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'
Expand All @@ -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
8 changes: 4 additions & 4 deletions lib/apartment/tenant.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -24,9 +23,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
Expand Down
2 changes: 1 addition & 1 deletion lib/apartment/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module Apartment
VERSION = '2.8.0'
VERSION = '2.8.1.rc2'
end
Loading

0 comments on commit 2f62620

Please sign in to comment.