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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d391e03f15ce77fa2eb4bfc55542f96499746a3d1b637007f53b15106f68afd9
4
+ data.tar.gz: 8c68ecf3fb342228dbca0bf889c4e8e4110ccabad49461d615c09e343c346b4d
5
+ SHA512:
6
+ metadata.gz: ff85b9f8e8ed943ebb23c27e0b1c1cf06d86ae6a83eb0c475248b1c897a8d24dbc224058325a95b4c8074ff69fd1f28f00207640833c6fb11bbb9bd43eaa2aa7
7
+ data.tar.gz: 1579ceb5b1ace497b9398a5dde8172be78a54326fd17a10514bd85ed2c82c0eeae3e1ae07a53a9f039b3cebe5d70217aae8d85991f5bfca4f5af26fb40c5535e
data/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.1] - 2026-11-29
9
+
10
+ ### Changed
11
+ - `TenantAdapters.resolve` (`:auto`) now takes an optional `db_adapter:` keyword and only selects `TenantAdapters::Apartment` for PostgreSQL shards when `ros-apartment` is loaded, falling back to `TenantAdapters::Native` for MySQL/Trilogy, SQLite3, and generic shards so heterogeneous multi-DB setups remain isolated. Apps using `ros-apartment` on MySQL should set `config.tenant_adapter = :apartment` explicitly.
12
+
13
+ ### Fixed
14
+ - Ensured `PoolRegistry#build_connection_pool` loads `active_record` and `ActiveRecord::Base` on cold lazy-loaded Rails 8 boots (`eager_load = false`) so the first `SchemaShard.with` / `SchemaShard.on_shard` call cannot fail with `NameError: uninitialized constant ActiveRecord::DatabaseConfigurations`.
15
+ - Prevented cross-tenant namespace leaks when nesting `SchemaShard.on_shard` or `:optional` `SchemaShard.with(nil)` inside `SchemaShard.with(tenant)` on the same PostgreSQL or MySQL shard connection (including `A -> B -> A` re-entry) by temporarily switching to the shard's default namespace and restoring the enclosing tenant (and any `Apartment.persistent_schemas`) on exit.
16
+ - Scoped `TenantAdapters::Apartment#default_namespace` (`Apartment.default_schema`) to PostgreSQL shards and routed non-namespace engines through `db_adapter.switch_namespace` fail-closed guards.
17
+ - Rejected nested `read_only: false` escalation inside `read_only: true` blocks before acquiring or creating a writable connection pool.
18
+ - Capped `PoolRegistry` key cache size (`max_pools * 10`) to bound memory under dynamic shard keys.
19
+ - Hardened cross-shard `A -> B -> A` nesting and `.with` inside `.on_shard` dirty-frame propagation.
20
+ - Fixed namespace restoration error handling so restore failures on clean block exit are never swallowed while in-flight exceptions are preserved.
21
+ - Added Rails 8 `lease_connection` and `retrieve_connection` routing with `prevent_permanent_checkout: true` and `pool.release_connection` in inner `ensure`.
22
+ - Fixed `custom_connection_model?` via `connection_class_for_self` and `primary_class?` to protect `connects_to` subclasses (`SolidQueue::Job`, `SolidCache::Entry`, etc.).
23
+ - Fixed fork safety to call `ConnectionPool#discard!` (never `disconnect!`).
24
+ - Added `ConnectionUrlResolver` support for `url:` shard configs and SQLite `%{tenant}` URL templates.
25
+ - Fixed MySQL 8 / Trilogy `non_idle_transaction?` fail-closed handling and `Sqlite#default_namespace_for`.
26
+
27
+ ## [0.1.0] - 2026-11-26
28
+
29
+ ### Added
30
+ - Initial Rails 8-first release of `schema_shard`.
31
+ - Multi-database adapter architecture supporting PostgreSQL (`postgresql`, `postgis`), MySQL/MariaDB (`mysql2`, `trilogy`), SQLite3 (`sqlite3`), and generic ActiveRecord adapters.
32
+ - Pluggable tenant adapters: `:auto`, `:apartment` (`ros-apartment`), `:native` (zero-dependency DB switching), `:none` (pure shard routing), plus custom adapter support.
33
+ - Flexible tenant modes (`:strict`, `:optional`, `:none`) and explicit `SchemaShard.on_shard` / `SchemaShard.with_public` APIs.
34
+ - Dual-layer read-only protection (`ActiveRecord::Base.while_preventing_writes` + database-level read-only session settings).
35
+ - Fail-closed connection sanitization and tainted connection discarding.
36
+ - Race-free LRU connection pool registry using Dekker-style atomic refcounting (`PoolEntry`).
37
+ - Rails 8 `ActiveSupport::IsolatedExecutionState` support, Railtie integration, fork safety (`Process._fork` + `discard_pools_after_fork!`), Sidekiq middleware, optional SQL query logger, and `rails g schema_shard:install` generator.
38
+ - Built-in Prometheus and StatsD observability formatters.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Raynald Serenas (Syrns)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,366 @@
1
+ # SchemaShard
2
+
3
+ **Rails 8-first database sharding and read-replica routing with optional, fail-closed multi-tenant isolation.**
4
+
5
+ `schema_shard` gives Rails 8+ applications dynamic, LRU-managed shard and read-replica connection pooling across **PostgreSQL**, **MySQL / MariaDB** (`mysql2` & `trilogy`), **SQLite3**, and custom ActiveRecord adapters — with flexible tenant isolation (`ros-apartment`, native DB switching, or pure shard-only routing).
6
+
7
+ ## Features
8
+
9
+ - **Multi-Database by Design**: Auto-detects the database engine per shard from `adapter:` in `config/shards.yml`:
10
+ - **PostgreSQL (`postgresql`, `postgis`)**: `ros-apartment` or zero-dependency native `search_path` switching, `default_transaction_read_only = on`, and fail-closed `PG::PQTRANS_IDLE` verification.
11
+ - **MySQL / MariaDB (`mysql2`, `trilogy`)**: `ros-apartment` or native `USE \`tenant_db\`` switching, `transaction_read_only = 1`, and open-transaction checks.
12
+ - **SQLite3 (`sqlite3`)**: Shard-only routing or per-tenant `.sqlite3` file templates (`storage/tenants/%{tenant}.sqlite3`) backed by LRU pool eviction and `PRAGMA query_only = ON`.
13
+ - **Generic / Custom**: Register custom database or tenant adapters via `SchemaShard::DatabaseAdapters.register`.
14
+ - **Flexible Tenant Modes**:
15
+ - `:strict` *(default)* — Fail-closed. `nil`, blank, system schemas (`pg_*`, `information_schema`), or accidental `public` fallback raise `SchemaShard::InvalidTenantError`.
16
+ - `:optional` — `nil` tenant gracefully falls back to the shard's default schema/database.
17
+ - `:none` — Pure database sharding / read-replica routing with zero tenant switching.
18
+ - `SchemaShard.on_shard('shard01')` — Explicit shard-only routing regardless of `tenant_mode`.
19
+ - **Dual-Layer Read-Only Protection**: Combines `ActiveRecord::Base.while_preventing_writes` in Ruby with DB-level read-only session settings.
20
+ - **Race-Free LRU Pool Lifecycle**: Atomic Dekker-style refcounting (`PoolEntry`) prevents races between active queries and concurrent pool eviction.
21
+ - **Rails 8 Native**: Uses `ActiveSupport::IsolatedExecutionState` (`:thread` & `:fiber` safe), `HashConfig`/`PoolConfig`, Railtie lazy loading, Rails Executor cleanup, and Ruby 3.1+ `Process._fork` safety.
22
+ - **Observability Out-of-the-Box**: Lock-free counters with built-in **Prometheus** and **StatsD** formatters plus an opt-in SQL query logger.
23
+
24
+ ## Installation
25
+
26
+ Add to your `Gemfile`:
27
+
28
+ ```ruby
29
+ gem 'schema_shard'
30
+ ```
31
+
32
+ Install and generate the initializer and `config/shards.yml` template:
33
+
34
+ ```bash
35
+ bundle install
36
+ bin/rails generate schema_shard:install
37
+ ```
38
+
39
+ ## Configuration
40
+
41
+ ### 1. Shared Setup & How `config/shards.yml` Is Loaded
42
+
43
+ Configure global behavior in `config/initializers/schema_shard.rb` (generated by `bin/rails generate schema_shard:install`):
44
+
45
+ ```ruby
46
+ # config/initializers/schema_shard.rb
47
+ SchemaShard.configure do |config|
48
+ config.config_path = Rails.root.join('config', 'shards.yml')
49
+ config.config_root_key = nil # optional top-level YAML key (see structure below)
50
+ config.default_shard = 'replica_1' # scaffolded as 'shard01' by schema_shard:install
51
+
52
+ # :auto (Apartment on PostgreSQL if loaded, else :native), :apartment, :native, :none, or custom adapter
53
+ config.tenant_adapter = :auto
54
+
55
+ # :strict (fail-closed), :optional (fallback to default), or :none (shard-only)
56
+ config.tenant_mode = :strict
57
+
58
+ # Models that must never be routed to a shard connection
59
+ config.excluded_models = %w[Account]
60
+ config.default_schema = 'public'
61
+ # Native PostgreSQL persistent schemas (leave [] when using ros-apartment; set Apartment.persistent_schemas instead)
62
+ config.persistent_schemas = %w[shared_extensions]
63
+
64
+ # Default per-pool connection settings when omitted on an individual shard in shards.yml
65
+ config.default_pool_size = ENV.fetch('RAILS_MAX_THREADS', 5).to_i
66
+ config.checkout_timeout = 5
67
+ config.reaping_frequency = 10
68
+
69
+ # Process-wide LRU pool registry limits
70
+ config.max_pools = ENV.fetch('SCHEMA_SHARD_MAX_POOLS', 10).to_i
71
+ config.cleanup_threshold = ENV.fetch('SCHEMA_SHARD_CLEANUP_THRESHOLD', 8).to_i
72
+ config.log_shard_queries = Rails.env.development?
73
+ end
74
+ ```
75
+
76
+ #### How `ConfigLoader` & `PoolRegistry` Resolve Shard Entries
77
+
78
+ - **No inheritance from `config/database.yml`**: Shard entries do **not** inherit `host`, `username`, `password`, `pool`, or any other settings from Rails's primary `config/database.yml`. Every shard entry is isolated to `config/shards.yml` (plus the `SchemaShard.configuration` fallbacks below) so shard routing can never accidentally fall back to your primary database.
79
+ - **ERB & YAML anchors**: `config/shards.yml` is evaluated through `ERB` and parsed with `YAML.safe_load(..., aliases: true)`, so `<%= ENV.fetch(...) %>` and YAML anchors (`default: &default` / `<<: *default`) work just like in Rails config files.
80
+ - **Environment & optional root key**:
81
+ - By default (`config.config_root_key = nil`), top-level keys are environment names matching `Rails.env` (falling back to `config.env`, `ENV['RAILS_ENV']`, `ENV['RACK_ENV']`, or `'development'`), and second-level keys are your shard names (`replica_1`, `write_shard_2`, etc.).
82
+ - If your YAML nests environments under a wrapper key (for example `shards:`), set `config.config_root_key = 'shards'` (`shards` → `<env>` → `<shard_key>`).
83
+ - Instead of a YAML file, you can assign a Ruby `Hash` (or a `Proc` returning a `Hash`) with the same `<env>` → `<shard_key>` structure to `config.shards`.
84
+ - **`url:` expansion & overrides**: When a shard defines `url:`, `SchemaShard` expands it via Rails's `ActiveRecord::DatabaseConfigurations::ConnectionUrlResolver` and merges any explicit sibling keys on top (for example, `url:` for credentials plus explicit `pool: 10` or `sslrootcert:`).
85
+ - **Active Record passthrough vs. gem-managed options**: `SchemaShard` validates the required connection locator (`url` or `host` + `database`, depending on adapter), applies pool defaults and read-only session settings, builds an `ActiveRecord::DatabaseConfigurations::HashConfig`, and hands the hash to `ActiveRecord::ConnectionAdapters::ConnectionPool`. Additional adapter options supported by your Active Record driver (such as SSL parameters, `variables`, `prepared_statements`, or driver timeouts) are passed directly through to Active Record.
86
+ - Pool deduplication hashes `shard_key`, `read_only`, `password` (SHA-256), and these recognized connection keys: `adapter`, `host`, `port`, `socket`, `database`, `username`, `url`, `sslmode`, `ssl_mode`, `sslrootcert`, `sslcert`, `sslkey`, `variables`, `pragmas`, `schema_search_path`, `prepared_statements`, `advisory_locks`, `pool`, `checkout_timeout`, `timeout`, `reaping_frequency`, and `encoding`.
87
+
88
+ #### Shared Shard Settings Reference
89
+
90
+ | Key | Required? | Default (when omitted) | Handled by | What it controls |
91
+ |---|---|---|---|---|
92
+ | `adapter` | Recommended | `'postgresql'` (or inferred from `url:` scheme) | `SchemaShard` & Active Record | Selects both the `SchemaShard::DatabaseAdapters` strategy and the Active Record connection adapter (`postgresql`, `postgis`, `trilogy`, `mysql2`, `sqlite3`, or custom). |
93
+ | `url` | Either `url` **or** `host` + `database` (SQLite/Generic: `url` or `database`) | — | `SchemaShard` (`ConnectionUrlResolver`) | Full connection URI (e.g., `postgres://...`, `trilogy://...`, `sqlite3://...`). Explicit sibling keys override values parsed from `url`. |
94
+ | `host` | Required on PG & MySQL when `url` is omitted | — | `SchemaShard` & Active Record | Database hostname, IP, or (on PostgreSQL) absolute Unix socket directory path. |
95
+ | `port` | Optional | Driver default (`5432` PG, `3306` MySQL) | Active Record / driver | TCP port of the database server. |
96
+ | `database` | Required when `url` is omitted | — | `SchemaShard` & Active Record | Database name (or file path / `%{tenant}` template on SQLite3). On MySQL, also acts as the shard's default namespace. |
97
+ | `username` | Optional | Driver default (OS user / `root`) | Active Record / driver | Database login role. Always use **`username`** (Active Record's key), not `user`. |
98
+ | `password` | Optional | `nil` | Active Record / driver | Database password. Interpolate from `ENV` rather than committing plaintext. |
99
+ | `pool` | Optional | `config.default_pool_size` (`RAILS_MAX_THREADS` or `5`, min `1`) | `SchemaShard` & Active Record | Max concurrent connections per Ruby process in **this** shard pool. Note that read-only (`read_only: true`) and writable (`read_only: false`) calls on the same shard maintain separate pools. |
100
+ | `checkout_timeout` | Optional | `config.checkout_timeout` (`5` seconds) | `SchemaShard` & Active Record | Seconds a thread waits for a free connection from the shard pool before raising `ActiveRecord::ConnectionTimeoutError`. |
101
+ | `reaping_frequency` | Optional | `config.reaping_frequency` (`10` seconds) | `SchemaShard` & Active Record | Interval in seconds at which Active Record's `ConnectionPool::Reaper` reclaims dead connections. |
102
+ | `encoding` | Optional | `'unicode'` (PG), `'utf8mb4'` (MySQL), unset (SQLite) | `SchemaShard` & Active Record | Client character encoding passed to Active Record. |
103
+ | `variables` | Optional | Merged with read-only flag when `read_only: true` | `SchemaShard` & Active Record | Session variables set on new connections. On read-only pools, `SchemaShard` merges `default_transaction_read_only: 'on'` (PG) or `transaction_read_only: 1` (MySQL) onto any custom `variables` hash. |
104
+
105
+ ---
106
+
107
+ ### 2. PostgreSQL (`postgresql`, `postgis`)
108
+
109
+ Add `gem 'pg'` to your application's `Gemfile` (`schema_shard` does not force-install database drivers).
110
+
111
+ A PostgreSQL shard requires **either** `url` **or** both `host` and `database`; all other keys are optional:
112
+
113
+ ```yaml
114
+ # config/shards.yml
115
+ default: &default
116
+ adapter: postgresql
117
+ encoding: unicode
118
+ pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
119
+ checkout_timeout: 5
120
+ reaping_frequency: 10
121
+
122
+ development:
123
+ replica_1:
124
+ <<: *default
125
+ host: <%= ENV.fetch('REPLICA_1_DB_HOST', 'localhost') %>
126
+ port: <%= ENV.fetch('REPLICA_1_DB_PORT', 5432) %>
127
+ database: <%= ENV.fetch('REPLICA_1_DB_NAME', 'app_development') %>
128
+ username: <%= ENV.fetch('REPLICA_1_DB_USERNAME', 'postgres') %>
129
+ password: <%= ENV.fetch('REPLICA_1_DB_PASSWORD', '') %>
130
+
131
+ write_shard_2:
132
+ <<: *default
133
+ host: <%= ENV.fetch('WRITE_SHARD_2_DB_HOST', 'localhost') %>
134
+ port: <%= ENV.fetch('WRITE_SHARD_2_DB_PORT', 5432) %>
135
+ database: <%= ENV.fetch('WRITE_SHARD_2_DB_NAME', 'app_shard2_development') %>
136
+ username: <%= ENV.fetch('WRITE_SHARD_2_DB_USERNAME', 'postgres') %>
137
+ password: <%= ENV.fetch('WRITE_SHARD_2_DB_PASSWORD', '') %>
138
+
139
+ production:
140
+ # Option A: Discrete connection keys + libpq SSL verification
141
+ replica_1:
142
+ <<: *default
143
+ host: <%= ENV.fetch('REPLICA_1_DB_HOST') %>
144
+ port: <%= ENV.fetch('REPLICA_1_DB_PORT', 5432) %>
145
+ database: <%= ENV.fetch('REPLICA_1_DB_NAME') %>
146
+ username: <%= ENV.fetch('REPLICA_1_DB_USERNAME') %>
147
+ password: <%= ENV.fetch('REPLICA_1_DB_PASSWORD') %>
148
+ sslmode: verify-full
149
+ sslrootcert: <%= ENV.fetch('DB_SSL_ROOT_CERT', '/etc/ssl/certs/rds-ca.pem') %>
150
+ variables:
151
+ statement_timeout: 5000
152
+
153
+ # Option B: Connection URL with explicit pool/SSL overrides
154
+ write_shard_2:
155
+ <<: *default
156
+ url: <%= ENV.fetch('WRITE_SHARD_2_DATABASE_URL') %>
157
+ pool: <%= ENV.fetch('WRITE_SHARD_2_POOL', 10) %>
158
+ sslmode: require
159
+ ```
160
+
161
+ #### PostgreSQL-Specific Notes
162
+
163
+ - **Use `username`, not `user`**: Active Record's `PostgreSQLAdapter` (and `SchemaShard`'s pool-identity digest) reads `username` and maps it to `libpq`'s `user` parameter internally.
164
+ - **SSL options (Active Record / `pg` passthrough)**: `sslmode` (`disable`, `allow`, `prefer`, `require`, `verify-ca`, `verify-full`), `sslrootcert`, `sslcert`, and `sslkey` are passed straight through to `PostgreSQLAdapter` / `libpq` and tracked in the pool identity digest.
165
+ - **Session & adapter options (passthrough)**: Standard `PostgreSQLAdapter` options such as `prepared_statements`, `advisory_locks`, `schema_search_path`, `connect_timeout`, and `variables` are forwarded to Active Record. When `read_only: true` (the default), `SchemaShard` automatically sets `variables.default_transaction_read_only = 'on'` while preserving any other entries in `variables` (such as `statement_timeout`).
166
+ - **Tenant schema isolation**: Switches `search_path` to `"<tenant>"` (plus `persistent_schemas`) via `ros-apartment` or native `SET search_path`, rejects `pg_*` and `information_schema`, and verifies `PG::PQTRANS_IDLE` before returning connections to the pool.
167
+ - **PostGIS (`adapter: postgis`)**: `postgis` is registered to the built-in PostgreSQL adapter. Add your PostGIS extension schema to `config.persistent_schemas = %w[postgis]` (or `Apartment.persistent_schemas` when using `ros-apartment`).
168
+
169
+ ---
170
+
171
+ ### 3. MySQL / MariaDB (`trilogy`, `mysql2`)
172
+
173
+ Both Rails 8's default **`trilogy`** driver (`gem 'trilogy'`) and **`mysql2`** (`gem 'mysql2'`) are supported. Each shard requires **either** `url` **or** both `host` and `database` (default `encoding` is `'utf8mb4'`):
174
+
175
+ ```yaml
176
+ # config/shards.yml
177
+ production:
178
+ mysql_replica:
179
+ adapter: trilogy # or: mysql2
180
+ host: <%= ENV.fetch('MYSQL_REPLICA_HOST') %>
181
+ port: <%= ENV.fetch('MYSQL_REPLICA_PORT', 3306) %>
182
+ database: <%= ENV.fetch('MYSQL_REPLICA_DB') %>
183
+ username: <%= ENV.fetch('MYSQL_REPLICA_USERNAME') %>
184
+ password: <%= ENV.fetch('MYSQL_REPLICA_PASSWORD') %>
185
+ pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
186
+ checkout_timeout: 5
187
+ ssl_mode: verify_identity # Active Record TrilogyAdapter SSL option
188
+ prepared_statements: false
189
+ ```
190
+
191
+ #### MySQL / MariaDB-Specific Notes
192
+
193
+ - **Driver recommendation on MySQL 8.0**: Prefer `trilogy >= 2.12.0` on MySQL 8.0 so `SchemaShard` can inspect live `Trilogy::Result#in_transaction?` protocol flags for raw SQL `BEGIN` statements. `mysql2` 0.5.x on MySQL 8.0 (like `trilogy < 2.12.0`) only detects Active Record-managed transactions (`open_transactions > 0`). MariaDB automatically falls back to `SELECT @@in_transaction` on both drivers.
194
+ - **`database:` is the default namespace**: Native tenant switching executes ``USE `<tenant>` `` on the connection and restores ``USE `<database>` `` on exit (rejecting `mysql`, `information_schema`, `performance_schema`, and `sys`). If you configure `url:`, ensure the URL path includes the default database name (`trilogy://user:pass@host:3306/app_production`).
195
+ - **SSL key names depend on the driver (passthrough)**: Active Record's `TrilogyAdapter` expects `ssl_mode` (e.g. `disabled`, `preferred`, `required`, `verify_ca`, `verify_identity`) plus `sslca` / `sslcert` / `sslkey`, whereas `Mysql2Adapter` accepts `ssl_mode` / `sslmode` plus `sslca` / `sslcert` / `sslkey`. Both `ssl_mode` and `sslmode` are tracked in `SchemaShard`'s pool identity digest.
196
+ - **Read-only session flag**: Read-only pools automatically inject `variables.transaction_read_only = 1`.
197
+
198
+ ---
199
+
200
+ ### 4. SQLite3 (`sqlite3`)
201
+
202
+ Add `gem 'sqlite3', '>= 2.0'` to your `Gemfile`. SQLite shards require **either** `database` **or** `url` (`host` is not required) and support two distinct modes:
203
+
204
+ ```yaml
205
+ # config/shards.yml
206
+ production:
207
+ # 1. Shared single-file shard (use with SchemaShard.on_shard or tenant_mode: :none)
208
+ analytics_sqlite:
209
+ adapter: sqlite3
210
+ database: <%= Rails.root.join('storage', 'analytics_replica.sqlite3') %>
211
+ pool: 5
212
+ timeout: 5000
213
+
214
+ # 2. Per-tenant database file template (use with SchemaShard.with(tenant, shard_key: 'sqlite_tenants'))
215
+ sqlite_tenants:
216
+ adapter: sqlite3
217
+ database: <%= Rails.root.join('storage', 'tenants', '%{tenant}.sqlite3') %>
218
+ pool: 2
219
+ timeout: 5000
220
+ # URL templates are also supported:
221
+ # url: sqlite3://<%= Rails.root.join('storage', 'tenants') %>/tenant_%{tenant}.sqlite3
222
+ ```
223
+
224
+ #### SQLite-Specific Notes
225
+
226
+ - **Shared vs. `%{tenant}` template (fail-closed)**: Calling `SchemaShard.with('acme_corp', shard_key: 'analytics_sqlite')` on a SQLite shard **without** `%{tenant}` in `database` or `url` raises `SchemaShard::ConfigurationError` rather than running tenant queries against a shared file. Use `SchemaShard.on_shard` for shared SQLite shards.
227
+ - **Path traversal & LRU pooling**: `%{tenant}` templates validate tenant names against `\A[a-zA-Z0-9][a-zA-Z0-9_-]{0,62}\z` (blocking `../` traversal) and allocate one LRU-managed pool per tenant bounded by `config.max_pools` and `config.cleanup_threshold`. Prefer absolute paths (via `Rails.root.join(...)` in ERB) so file resolution never depends on the process working directory.
228
+ - **Read-only & busy timeout**: `SchemaShard` executes `PRAGMA query_only = ON` (or `OFF` when `read_only: false`) on every checkout. Active Record SQLite options such as `timeout` (busy timeout in milliseconds) and `pragmas` pass directly through to `SQLite3Adapter`.
229
+
230
+ ---
231
+
232
+ ### 5. Generic & Custom Adapters
233
+
234
+ Any `adapter:` name other than `postgresql`, `postgis`, `trilogy`, `mysql2`, or `sqlite3` resolves to `SchemaShard::DatabaseAdapters::Generic` (requiring `database` or `url`):
235
+
236
+ - **Out-of-the-box shard-only routing**: `Generic` works immediately with `SchemaShard.on_shard` (or `config.tenant_mode = :none`) for routing queries to secondary databases or replicas on other Active Record adapters.
237
+ - **Fail-closed on `.with(tenant)`**: Because `Generic` cannot assume how an unknown engine isolates tenants, calling `SchemaShard.with(tenant)` raises `SchemaShard::ConfigurationError` unless you register a custom subclass of `SchemaShard::DatabaseAdapters::Base`:
238
+
239
+ ```ruby
240
+ # config/initializers/schema_shard.rb
241
+ SchemaShard::DatabaseAdapters.register('cockroachdb', SchemaShard::DatabaseAdapters::Postgresql.instance)
242
+ ```
243
+
244
+ ---
245
+
246
+ ### 6. Environment Variables, Credentials & Security Practices
247
+
248
+ - **Never commit credentials**: Keep passwords, connection URLs, and private keys out of `config/shards.yml` and version control. Supply them at runtime through your platform's secret store or process environment (Kubernetes Secrets, AWS SSM / Secrets Manager, Docker/Kamal env, `systemd` `EnvironmentFile`, or an untracked `.env` in local development) so both Puma and background workers (Sidekiq / SolidQueue) inherit them.
249
+ - **Prefer `ENV.fetch('VAR')` in deployed environments**: Note that `bin/rails generate schema_shard:install` scaffolds `ENV['SHARD01_DATABASE_URL']` in `production` so a freshly generated app can boot before shards are provisioned. Once deployed, switch required production variables to `<%= ENV.fetch('REPLICA_1_DB_PASSWORD') %>` (or `<%= ENV.fetch('WRITE_SHARD_2_DATABASE_URL') %>`) so a missing secret fails immediately with the variable name instead of silently producing a blank `url:`.
250
+ - **Redacted pool identifiers & logs**: `PoolRegistry` hashes `password` with SHA-256 and truncates the composite configuration digest (`replica_1_9f86d081884c7d65`), so plaintext hosts and passwords never appear in pool keys, logs, or Prometheus/StatsD labels.
251
+ - **Database-level least privilege**: `read_only: true` enforces both `ActiveRecord::Base.while_preventing_writes` and session-level read-only variables (`default_transaction_read_only = on` / `transaction_read_only = 1` / `PRAGMA query_only = ON`), **and** production read replicas should still connect with a database role granted `SELECT`-only privileges.
252
+
253
+ ---
254
+
255
+ ### 7. Validating a Configuration & Common Setup Mistakes
256
+
257
+ You can verify `config/shards.yml` syntax, required keys, and live connectivity from `bin/rails console` or a deploy health check:
258
+
259
+ ```ruby
260
+ # 1. Validate ERB, YAML nesting, URL parsing, and adapter-required keys (no DB socket opened)
261
+ SchemaShard.config_loader.fetch!('replica_1')
262
+
263
+ # 2. Verify live connectivity, SSL, credentials, and read-only session setup
264
+ SchemaShard.on_shard('replica_1') do
265
+ ActiveRecord::Base.connection.select_value('SELECT 1')
266
+ end
267
+ ```
268
+
269
+ If you rotate credentials or edit `config/shards.yml` at runtime, call `SchemaShard.reload_config!` to clear the cached config and retire unused pools while letting in-flight queries finish safely.
270
+
271
+ #### Common Setup Mistakes
272
+
273
+ - **Expecting fallback to `config/database.yml`**: Omitting `host` or `username` because they exist in `database.yml` — shard entries are completely independent (use YAML `&default` anchors inside `shards.yml` to share settings across shards).
274
+ - **Writing `user:` instead of `username:`**: Active Record adapters and `SchemaShard` expect `username:`; `user:` is ignored.
275
+ - **Blank `ENV['...']` URL in production**: If `url: <%= ENV['SHARD01_DATABASE_URL'] %>` evaluates to `nil` and neither `host` nor `database` is set, `ConfigLoader` raises `ArgumentError: Shard '...' must explicitly configure either 'url' or both 'host' and 'database'`.
276
+ - **Unix socket without `host` or `url`**: On PostgreSQL and MySQL, `validate_config!` requires `url` or `host` + `database`. For local Unix sockets, pass the socket directory as `host: /var/run/postgresql` (PostgreSQL) or include `host: localhost` alongside `socket:` (MySQL), or use a `url:`.
277
+ - **Environment or `config_root_key` mismatch**: Raising `Environment '<env>' not found` usually means `config/shards.yml` is missing a block for the current `Rails.env` (for example `staging:`), or wraps environments under a top-level key without matching `config.config_root_key`.
278
+ - **Connection math across processes**: Total connections to a database equal `(web + worker processes) × pool` (and up to `max_pools` distinct pools per process when using per-tenant SQLite or many shards, plus separate `:reading` and `:writing` pools if a shard is called with both `read_only: true` and `read_only: false`). Size `pool` and `max_pools` within your database's `max_connections` budget (or place PgBouncer in front of PostgreSQL shards).
279
+
280
+ ### Production Notes
281
+
282
+ - **Read-Only Defense in Depth**: `read_only: true` applies both `ActiveRecord::Base.while_preventing_writes` (which prevents writes thread-wide for the duration of the block, including `excluded_models`) and DB-level session read-only flags. In production, always back read replicas with a **read-only database role/user** as well.
283
+ - **Open Transactions & Nested Switches**: Nested different-tenant switches inside an open database transaction are rejected fail-closed (`SchemaShard::TaintedConnectionError`), and the tainted pool frame blocks any further queries even if the error is rescued.
284
+ - **MySQL 8 (`trilogy` vs `mysql2`)**: `trilogy >= 2.12.0` is strongly recommended on MySQL 8.0 for live `Trilogy::Result#in_transaction?` protocol inspection of raw SQL `BEGIN` transactions; `mysql2` 0.5.x on MySQL 8.0 (like `trilogy < 2.12.0`) only detects ActiveRecord-managed transactions (`open_transactions > 0`). MariaDB automatically falls back to `SELECT @@in_transaction` on both drivers.
285
+ - **Fast-Path Live Verification**: Set `config.live_verify_fast_path = true` if application code mutates `search_path` or `USE` via raw SQL outside `SchemaShard.with`. Avoid wrapping a nested `SchemaShard.with` inside an out-of-band `Apartment::Tenant.switch` call.
286
+ - **Metrics Cardinality**: Per-shard metrics are bounded by `config.max_tracked_shards` (default `100`, bucketing overflow into `_other`). Call `SchemaShard.reset_metrics!` if you rotate dynamic shard keys.
287
+ - **Rails 8 `Relation#load_async`**: Do not call `.load_async` inside `SchemaShard.with` or `SchemaShard.on_shard` blocks; ActiveRecord's background async executor runs on separate worker threads that do not inherit the caller's `ExecutionContext` or tenant `search_path` / `USE` session state.
288
+ - **PostgreSQL `$user` Role Naming**: PostgreSQL's built-in `"$user, public"` `search_path` is treated as equivalent to `"public"` when `persistent_schemas` is empty; ensure your database connection role name never matches a tenant schema name.
289
+ - **`ros-apartment` Persistent Schemas**: When using `ros-apartment`, configure persistent schemas via `Apartment.persistent_schemas` and leave `SchemaShard.configuration.persistent_schemas` empty (or identical) so fast-path namespace checks match `Apartment::Tenant.switch`.
290
+ - **Fiber Concurrency (Falcon / Async)**: Set `config.active_support.isolation_level = :fiber` in Rails 8 so `ActiveSupport::IsolatedExecutionState` isolates shard context per Fiber.
291
+ - **Standalone / Non-Rails Apps**: Call `SchemaShard.install!` once at boot to prepend `SchemaShard::ConnectionPatch` onto `ActiveRecord::Base`, and call `SchemaShard.install_fork_hook!` if your process forks (in Rails, the Railtie installs both automatically).
292
+
293
+ ## Usage
294
+
295
+ ### Multi-Tenant + Shard Routing (PostgreSQL, MySQL, SQLite)
296
+
297
+ ```ruby
298
+ SchemaShard.with('acme_corp', shard_key: 'replica_1') do
299
+ Order.where(status: 'paid').count
300
+ end
301
+ ```
302
+
303
+ ### Shard-Only Routing (No Schema/Tenant Selection)
304
+
305
+ ```ruby
306
+ # Uses the shard's default schema/database regardless of tenant_mode
307
+ SchemaShard.on_shard('replica_1') do
308
+ Order.where(status: 'paid').count
309
+ end
310
+ ```
311
+
312
+ ### Explicit Default (`public`) Schema Access
313
+
314
+ ```ruby
315
+ SchemaShard.with_public(shard_key: 'replica_1') do
316
+ Account.count
317
+ end
318
+ ```
319
+
320
+ ### Writable Shards
321
+
322
+ ```ruby
323
+ SchemaShard.on_shard('write_shard_2', read_only: false) do
324
+ AuditLog.create!(event: 'synced')
325
+ end
326
+ ```
327
+
328
+ ### Sidekiq & Puma Integration
329
+
330
+ ```ruby
331
+ # config/initializers/sidekiq.rb
332
+ Sidekiq.configure_server do |config|
333
+ config.server_middleware do |chain|
334
+ chain.add SchemaShard::Middleware::Sidekiq
335
+ end
336
+ end
337
+ ```
338
+
339
+ In Rails apps, fork safety is enabled automatically on Ruby 3.1+ via `Process._fork` (when `config.auto_fork_safety = true`). Standalone / non-Rails apps can call `SchemaShard.install_fork_hook!` at boot, or you can call `SchemaShard.discard_pools_after_fork!` explicitly in `config/puma.rb`:
340
+
341
+ ```ruby
342
+ on_worker_boot do
343
+ SchemaShard.discard_pools_after_fork!
344
+ end
345
+ ```
346
+
347
+ ### Observability (Prometheus & StatsD)
348
+
349
+ ```ruby
350
+ SchemaShard.metrics # => Hash snapshot (global, per_shard, pools, timestamp)
351
+ SchemaShard.prometheus_metrics # => Prometheus text exposition format
352
+ SchemaShard.statsd_metrics # => Array of StatsD/DogStatsD gauge descriptors
353
+ ```
354
+
355
+ ## Development
356
+
357
+ ```bash
358
+ bundle install
359
+ bundle exec rspec
360
+ bundle exec rubocop
361
+ gem build schema_shard.gemspec
362
+ ```
363
+
364
+ ## License
365
+
366
+ The gem is available as open source under the terms of the [MIT License](https://github.com/syrens/schema_shard/blob/main/LICENSE.txt).
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+
5
+ module SchemaShard
6
+ module Generators
7
+ class InstallGenerator < ::Rails::Generators::Base
8
+ source_root File.expand_path('templates', __dir__)
9
+
10
+ desc 'Creates a SchemaShard initializer and config/shards.yml template.'
11
+
12
+ def copy_initializer
13
+ template 'initializer.rb.tt', 'config/initializers/schema_shard.rb'
14
+ end
15
+
16
+ def copy_shards_config
17
+ template 'shards.yml.tt', 'config/shards.yml'
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ SchemaShard.configure do |config|
4
+ # Path to your shards YAML file (ERB-enabled)
5
+ config.config_path = Rails.root.join('config', 'shards.yml')
6
+
7
+ # Optional top-level YAML key (leave nil for standard env-at-root layout)
8
+ # config.config_root_key = nil
9
+
10
+ # Optional default shard key when omitted from SchemaShard.with / SchemaShard.on_shard
11
+ config.default_shard = 'shard01'
12
+
13
+ # Tenant isolation adapter:
14
+ # :auto - uses ros-apartment for PostgreSQL shards if loaded, otherwise native DB switching
15
+ # :apartment - forces ros-apartment
16
+ # :native - zero-dependency DB switching (PG search_path, MySQL USE, SQLite file)
17
+ # :none - pure shard / read-replica routing with no tenant switching
18
+ config.tenant_adapter = :auto
19
+
20
+ # Tenant validation mode:
21
+ # :strict - fail-closed; nil or default schema raises InvalidTenantError (recommended for SaaS)
22
+ # :optional - nil tenant gracefully falls back to the shard's default schema/database
23
+ # :none - disables tenant switching completely
24
+ config.tenant_mode = :strict
25
+
26
+ # Shared models that should NEVER be routed to a shard connection
27
+ # (automatically merged with Apartment.excluded_models when Apartment is present)
28
+ config.excluded_models = []
29
+
30
+ # PostgreSQL default schema & persistent schemas (e.g. extensions)
31
+ config.default_schema = 'public'
32
+ config.persistent_schemas = []
33
+
34
+ # Connection pool LRU limits
35
+ config.max_pools = ENV.fetch('SCHEMA_SHARD_MAX_POOLS', 10).to_i
36
+ config.cleanup_threshold = ENV.fetch('SCHEMA_SHARD_CLEANUP_THRESHOLD', 8).to_i
37
+
38
+ # Log SQL queries tagged with active shard & tenant in development
39
+ config.log_shard_queries = Rails.env.development?
40
+ end
@@ -0,0 +1,31 @@
1
+ default: &default
2
+ pool: <%= ENV.fetch('RAILS_MAX_THREADS', 5) %>
3
+ checkout_timeout: 5
4
+ reaping_frequency: 10
5
+
6
+ development:
7
+ shard01:
8
+ <<: *default
9
+ adapter: postgresql
10
+ encoding: unicode
11
+ host: <%= ENV.fetch('SHARD01_DB_HOST', 'localhost') %>
12
+ port: <%= ENV.fetch('SHARD01_DB_PORT', 5432) %>
13
+ database: <%= ENV.fetch('SHARD01_DB_NAME', 'app_development') %>
14
+ username: <%= ENV.fetch('SHARD01_DB_USERNAME', 'postgres') %>
15
+ password: <%= ENV.fetch('SHARD01_DB_PASSWORD', '') %>
16
+
17
+ test:
18
+ shard01:
19
+ <<: *default
20
+ adapter: postgresql
21
+ encoding: unicode
22
+ host: <%= ENV.fetch('SHARD01_DB_HOST', 'localhost') %>
23
+ port: <%= ENV.fetch('SHARD01_DB_PORT', 5432) %>
24
+ database: <%= ENV.fetch('SHARD01_DB_NAME', 'app_test') %>
25
+ username: <%= ENV.fetch('SHARD01_DB_USERNAME', 'postgres') %>
26
+ password: <%= ENV.fetch('SHARD01_DB_PASSWORD', '') %>
27
+
28
+ production:
29
+ shard01:
30
+ <<: *default
31
+ url: <%= ENV['SHARD01_DATABASE_URL'] %>