schema_shard 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ module QueryLogger
5
+ class << self
6
+ def install!(logger: nil)
7
+ return @subscriber if @subscriber
8
+ return nil unless defined?(ActiveSupport::Notifications)
9
+
10
+ @subscriber = ActiveSupport::Notifications.subscribe('sql.active_record') do |*, payload|
11
+ shard = SchemaShard.current_shard_label
12
+ next unless shard
13
+
14
+ active_conn = SchemaShard.active_connection
15
+ next if payload.key?(:connection) && active_conn && !payload[:connection].equal?(active_conn)
16
+
17
+ log = logger || SchemaShard.configuration.effective_logger
18
+ next unless log
19
+
20
+ tenant = SchemaShard.current_tenant
21
+ tag = tenant ? "Shard: #{shard} | Tenant: #{tenant}" : "Shard: #{shard}"
22
+ message = format_message(tag, payload[:name], payload[:sql])
23
+ log.debug(message)
24
+ end
25
+ end
26
+
27
+ def uninstall!
28
+ return unless @subscriber && defined?(ActiveSupport::Notifications)
29
+
30
+ ActiveSupport::Notifications.unsubscribe(@subscriber)
31
+ @subscriber = nil
32
+ end
33
+
34
+ private
35
+
36
+ def format_message(tag, name, sql)
37
+ line = "==[#{tag}] #{name} -> #{sql}"
38
+ return "\e[33m#{line}\e[0m" if colorize?
39
+
40
+ line
41
+ end
42
+
43
+ def colorize?
44
+ defined?(ActiveSupport::LogSubscriber) && ActiveSupport::LogSubscriber.colorize_logging
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/railtie'
4
+
5
+ module SchemaShard
6
+ class Railtie < ::Rails::Railtie
7
+ initializer 'schema_shard.active_record' do
8
+ ActiveSupport.on_load(:active_record) do
9
+ SchemaShard.install!
10
+ end
11
+ end
12
+
13
+ initializer 'schema_shard.after_initialize' do
14
+ config.after_initialize do
15
+ SchemaShard::QueryLogger.install! if SchemaShard.configuration.log_shard_queries
16
+ SchemaShard.install_fork_hook! if SchemaShard.configuration.auto_fork_safety
17
+ end
18
+ end
19
+
20
+ initializer 'schema_shard.executor' do |app|
21
+ if app.respond_to?(:executor) && app.executor.respond_to?(:to_complete)
22
+ app.executor.to_complete do
23
+ if !SchemaShard::ExecutionContext.in_active_block? && SchemaShard.current_shard_label
24
+ SchemaShard.clear_thread_locals!
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module TenantAdapters
7
+ # Delegates tenant switching to ros-apartment (+::Apartment::Tenant.switch+).
8
+ class Apartment < Base
9
+ # Switches to +tenant+ for the duration of the block.
10
+ #
11
+ # Engines without namespace support (SQLite3, generic adapters) never delegate to
12
+ # Apartment; they go through +db_adapter.switch_namespace+ so its fail-closed guards
13
+ # (e.g. shared non-template SQLite shards) still apply.
14
+ #
15
+ # @param tenant [String]
16
+ # @param conn [ActiveRecord::ConnectionAdapters::AbstractAdapter]
17
+ # @param db_adapter [SchemaShard::DatabaseAdapters::Base]
18
+ # @param shard_config [Hash, nil]
19
+ # @yield the tenant-scoped block
20
+ # @return [Object] the block's return value
21
+ def switch(tenant, conn:, db_adapter:, shard_config: nil, &)
22
+ unless db_adapter.supports_namespaces?
23
+ return db_adapter.switch_namespace(
24
+ conn, tenant, persistent_schemas: persistent_schemas, shard_config: shard_config, &
25
+ )
26
+ end
27
+
28
+ ::Apartment::Tenant.switch(tenant, &)
29
+ end
30
+
31
+ def current(conn:, db_adapter:) # rubocop:disable Lint/UnusedMethodArgument
32
+ return nil unless defined?(::Apartment::Tenant) && ::Apartment::Tenant.respond_to?(:current)
33
+
34
+ ::Apartment::Tenant.current.to_s
35
+ end
36
+
37
+ def matches_current?(tenant, conn:, db_adapter:, live: false)
38
+ super && db_adapter.namespace_matches?(conn, tenant, persistent_schemas: persistent_schemas, live: live)
39
+ end
40
+
41
+ # The shard's default (non-tenant) namespace.
42
+ #
43
+ # +Apartment.default_schema+ is a PostgreSQL schema name, so it is only honored for
44
+ # PostgreSQL shards (or when +db_adapter+ is omitted, preserving legacy behavior).
45
+ # Other engines use their own default (e.g. the MySQL shard's configured +database+).
46
+ #
47
+ # @param shard_config [Hash, nil]
48
+ # @param db_adapter [SchemaShard::DatabaseAdapters::Base, nil]
49
+ # @return [String, nil]
50
+ def default_namespace(shard_config = nil, db_adapter: nil)
51
+ if apartment_default_schema? && TenantAdapters.apartment_compatible?(db_adapter)
52
+ ::Apartment.default_schema.to_s
53
+ else
54
+ super
55
+ end
56
+ end
57
+
58
+ def persistent_schemas
59
+ apt_schemas = if defined?(::Apartment) && ::Apartment.respond_to?(:persistent_schemas)
60
+ Array(::Apartment.persistent_schemas).map(&:to_s)
61
+ else
62
+ []
63
+ end
64
+ (apt_schemas + super).uniq
65
+ end
66
+
67
+ def excluded_models
68
+ apt_excluded = if defined?(::Apartment) && ::Apartment.respond_to?(:excluded_models)
69
+ Array(::Apartment.excluded_models).map(&:to_s)
70
+ else
71
+ []
72
+ end
73
+ (apt_excluded + super).uniq
74
+ end
75
+
76
+ private
77
+
78
+ def apartment_default_schema?
79
+ defined?(::Apartment) && ::Apartment.respond_to?(:default_schema) &&
80
+ !::Apartment.default_schema.nil? && !::Apartment.default_schema.to_s.empty?
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ module TenantAdapters
5
+ # Resolves the tenant adapter for the given configuration.
6
+ #
7
+ # In +:auto+ mode, the ros-apartment adapter is only selected when +::Apartment::Tenant+
8
+ # is loaded AND the shard engine is PostgreSQL (or the engine is unknown, i.e. +db_adapter+
9
+ # is omitted). Every other engine (MySQL/Trilogy, SQLite3, generic) uses {Native}, so a
10
+ # PostgreSQL-configured Apartment never drives switching on a heterogeneous shard.
11
+ #
12
+ # @param configuration [SchemaShard::Configuration]
13
+ # @param db_adapter [SchemaShard::DatabaseAdapters::Base, nil] the shard's database adapter;
14
+ # when +nil+, +:auto+ keeps the legacy engine-agnostic behavior.
15
+ # @return [SchemaShard::TenantAdapters::Base] a tenant adapter instance (or the custom
16
+ # adapter object assigned to +configuration.tenant_adapter+).
17
+ def self.resolve(configuration, db_adapter: nil)
18
+ return None.new(configuration) if configuration.tenant_mode == :none
19
+
20
+ case configuration.tenant_adapter
21
+ when :auto
22
+ if defined?(::Apartment::Tenant) && apartment_compatible?(db_adapter)
23
+ Apartment.new(configuration)
24
+ else
25
+ Native.new(configuration)
26
+ end
27
+ when :apartment
28
+ Apartment.new(configuration)
29
+ when :native, :postgresql_schema
30
+ Native.new(configuration)
31
+ when :none
32
+ None.new(configuration)
33
+ else
34
+ configuration.tenant_adapter
35
+ end
36
+ end
37
+
38
+ # @api private
39
+ def self.apartment_compatible?(db_adapter)
40
+ db_adapter.nil? || db_adapter.is_a?(DatabaseAdapters::Postgresql)
41
+ end
42
+
43
+ class Base
44
+ def initialize(configuration)
45
+ @configuration = configuration
46
+ end
47
+
48
+ def switches_tenant?
49
+ true
50
+ end
51
+
52
+ def switch(_tenant, conn:, db_adapter:, shard_config: nil) # rubocop:disable Lint/UnusedMethodArgument
53
+ yield
54
+ end
55
+
56
+ def current(conn:, db_adapter:) # rubocop:disable Lint/UnusedMethodArgument
57
+ nil
58
+ end
59
+
60
+ def matches_current?(tenant, conn:, db_adapter:, live: false) # rubocop:disable Lint/UnusedMethodArgument
61
+ live_current = current(conn: conn, db_adapter: db_adapter)
62
+ live_current.nil? || live_current.to_s == tenant.to_s
63
+ end
64
+
65
+ def default_namespace(shard_config = nil, db_adapter: nil)
66
+ if db_adapter && shard_config
67
+ db_adapter.default_namespace_for(shard_config, configured_default: @configuration.default_schema)
68
+ else
69
+ @configuration.default_schema.to_s
70
+ end
71
+ end
72
+
73
+ def persistent_schemas
74
+ Array(@configuration.persistent_schemas).map(&:to_s)
75
+ end
76
+
77
+ def excluded_models
78
+ Array(@configuration.excluded_models).map(&:to_s)
79
+ end
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module TenantAdapters
7
+ # Zero-dependency tenant switcher delegating directly to the shard's DatabaseAdapter
8
+ # (PostgreSQL `search_path`, MySQL `USE db`, SQLite per-tenant DB file).
9
+ class Native < Base
10
+ def switch(tenant, conn:, db_adapter:, shard_config: nil, &)
11
+ db_adapter.switch_namespace(
12
+ conn,
13
+ tenant,
14
+ persistent_schemas: persistent_schemas,
15
+ shard_config: shard_config,
16
+ &
17
+ )
18
+ end
19
+
20
+ def current(conn:, db_adapter:)
21
+ db_adapter.current_namespace(conn, live: false)
22
+ end
23
+
24
+ def matches_current?(tenant, conn:, db_adapter:, live: false)
25
+ db_adapter.namespace_matches?(conn, tenant, persistent_schemas: persistent_schemas, live: live)
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ module SchemaShard
6
+ module TenantAdapters
7
+ # No-op tenant adapter for pure database sharding / read-replica routing.
8
+ class None < Base
9
+ def switches_tenant?
10
+ false
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SchemaShard
4
+ VERSION = '0.1.1'
5
+ end