puzzle-apartment 2.12.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.circleci/config.yml +71 -0
- data/.github/ISSUE_TEMPLATE.md +21 -0
- data/.github/workflows/changelog.yml +63 -0
- data/.github/workflows/reviewdog.yml +22 -0
- data/.gitignore +15 -0
- data/.pryrc +5 -0
- data/.rspec +4 -0
- data/.rubocop.yml +33 -0
- data/.rubocop_todo.yml +418 -0
- data/.ruby-version +1 -0
- data/.story_branch.yml +5 -0
- data/Appraisals +49 -0
- data/CHANGELOG.md +963 -0
- data/Gemfile +17 -0
- data/Guardfile +11 -0
- data/HISTORY.md +496 -0
- data/README.md +652 -0
- data/Rakefile +157 -0
- data/TODO.md +50 -0
- data/docker-compose.yml +33 -0
- data/gemfiles/rails_6_1.gemfile +17 -0
- data/gemfiles/rails_7_0.gemfile +17 -0
- data/gemfiles/rails_7_1.gemfile +17 -0
- data/gemfiles/rails_master.gemfile +17 -0
- data/lib/apartment/active_record/connection_handling.rb +34 -0
- data/lib/apartment/active_record/internal_metadata.rb +9 -0
- data/lib/apartment/active_record/postgresql_adapter.rb +39 -0
- data/lib/apartment/active_record/schema_migration.rb +13 -0
- data/lib/apartment/adapters/abstract_adapter.rb +275 -0
- data/lib/apartment/adapters/abstract_jdbc_adapter.rb +20 -0
- data/lib/apartment/adapters/jdbc_mysql_adapter.rb +19 -0
- data/lib/apartment/adapters/jdbc_postgresql_adapter.rb +62 -0
- data/lib/apartment/adapters/mysql2_adapter.rb +77 -0
- data/lib/apartment/adapters/postgis_adapter.rb +13 -0
- data/lib/apartment/adapters/postgresql_adapter.rb +284 -0
- data/lib/apartment/adapters/sqlite3_adapter.rb +66 -0
- data/lib/apartment/console.rb +24 -0
- data/lib/apartment/custom_console.rb +42 -0
- data/lib/apartment/deprecation.rb +11 -0
- data/lib/apartment/elevators/domain.rb +23 -0
- data/lib/apartment/elevators/first_subdomain.rb +18 -0
- data/lib/apartment/elevators/generic.rb +33 -0
- data/lib/apartment/elevators/host.rb +35 -0
- data/lib/apartment/elevators/host_hash.rb +26 -0
- data/lib/apartment/elevators/subdomain.rb +66 -0
- data/lib/apartment/log_subscriber.rb +45 -0
- data/lib/apartment/migrator.rb +52 -0
- data/lib/apartment/model.rb +29 -0
- data/lib/apartment/railtie.rb +68 -0
- data/lib/apartment/tasks/enhancements.rb +55 -0
- data/lib/apartment/tasks/task_helper.rb +52 -0
- data/lib/apartment/tenant.rb +63 -0
- data/lib/apartment/version.rb +5 -0
- data/lib/apartment.rb +159 -0
- data/lib/generators/apartment/install/USAGE +5 -0
- data/lib/generators/apartment/install/install_generator.rb +11 -0
- data/lib/generators/apartment/install/templates/apartment.rb +116 -0
- data/lib/tasks/apartment.rake +106 -0
- data/puzzle-apartment.gemspec +59 -0
- metadata +385 -0
data/README.md
ADDED
@@ -0,0 +1,652 @@
|
|
1
|
+
# Apartment
|
2
|
+
|
3
|
+
[![Gem Version](https://badge.fury.io/rb/puzzle-apartment.svg)](https://badge.fury.io/rb/apartment)
|
4
|
+
|
5
|
+
*Multitenancy for Rails and ActiveRecord*
|
6
|
+
|
7
|
+
Apartment provides tools to help you deal with multiple tenants in your Rails
|
8
|
+
application. If you need to have certain data sequestered based on account or company,
|
9
|
+
but still allow some data to exist in a common tenant, Apartment can help.
|
10
|
+
|
11
|
+
## Apartment drop in replacement gem
|
12
|
+
|
13
|
+
Nor the orginal [apartment](https://github.com/influitive/apartment) gem nor
|
14
|
+
the Rails 6 for by [ros-apartment](https://github.com/rails-on-services/apartment)
|
15
|
+
are maintained anymore.
|
16
|
+
|
17
|
+
Since we wanted to upgrade our application to Rails 7.1 we decided to fork
|
18
|
+
and start some development to support Rails 7.1. Because we don't have access
|
19
|
+
to the apartment gem itself, the solution was to release it under a different
|
20
|
+
name but providing the exact same API as it was before.
|
21
|
+
|
22
|
+
We maintain this gem for our own projects at the moment but would love to see
|
23
|
+
a living community fork showing up again.
|
24
|
+
|
25
|
+
|
26
|
+
## Installation
|
27
|
+
|
28
|
+
### Rails
|
29
|
+
|
30
|
+
Add the following to your Gemfile:
|
31
|
+
|
32
|
+
```ruby
|
33
|
+
gem 'puzzle-apartment', require: 'apartment'
|
34
|
+
```
|
35
|
+
|
36
|
+
Then generate your `Apartment` config file using
|
37
|
+
|
38
|
+
```ruby
|
39
|
+
bundle exec rails generate apartment:install
|
40
|
+
```
|
41
|
+
|
42
|
+
This will create a `config/initializers/apartment.rb` initializer file.
|
43
|
+
Configure as needed using the docs below.
|
44
|
+
|
45
|
+
That's all you need to set up the Apartment libraries. If you want to switch tenants
|
46
|
+
on a per-user basis, look under "Usage - Switching tenants per request", below.
|
47
|
+
|
48
|
+
> NOTE: If using [postgresql schemas](http://www.postgresql.org/docs/9.0/static/ddl-schemas.html) you must use:
|
49
|
+
>
|
50
|
+
> * for Rails 3.1.x: _Rails ~> 3.1.2_, it contains a [patch](https://github.com/rails/rails/pull/3232) that makes prepared statements work with multiple schemas
|
51
|
+
|
52
|
+
## Usage
|
53
|
+
|
54
|
+
### Video Tutorial
|
55
|
+
|
56
|
+
How to separate your application data into different accounts or companies.
|
57
|
+
[GoRails #47](https://gorails.com/episodes/multitenancy-with-apartment)
|
58
|
+
|
59
|
+
### Creating new Tenants
|
60
|
+
|
61
|
+
Before you can switch to a new apartment tenant, you will need to create it. Whenever
|
62
|
+
you need to create a new tenant, you can run the following command:
|
63
|
+
|
64
|
+
```ruby
|
65
|
+
Apartment::Tenant.create('tenant_name')
|
66
|
+
```
|
67
|
+
|
68
|
+
If you're using the [prepend environment](https://github.com/influitive/apartment#handling-environments) config option or you AREN'T using Postgresql Schemas, this will create a tenant in the following format: "#{environment}\_tenant_name".
|
69
|
+
In the case of a sqlite database, this will be created in your 'db/' folder. With
|
70
|
+
other databases, the tenant will be created as a new DB within the system.
|
71
|
+
|
72
|
+
When you create a new tenant, all migrations will be run against that tenant, so it will be
|
73
|
+
up to date when create returns.
|
74
|
+
|
75
|
+
#### Notes on PostgreSQL
|
76
|
+
|
77
|
+
PostgreSQL works slightly differently than other databases when creating a new tenant. If you
|
78
|
+
are using PostgreSQL, Apartment by default will set up a new [schema](http://www.postgresql.org/docs/9.3/static/ddl-schemas.html)
|
79
|
+
and migrate into there. This provides better performance, and allows Apartment to work on systems like Heroku, which
|
80
|
+
would not allow a full new database to be created.
|
81
|
+
|
82
|
+
One can optionally use the full database creation instead if they want, though this is not recommended
|
83
|
+
|
84
|
+
### Switching Tenants
|
85
|
+
|
86
|
+
To switch tenants using Apartment, use the following command:
|
87
|
+
|
88
|
+
```ruby
|
89
|
+
Apartment::Tenant.switch('tenant_name') do
|
90
|
+
# ...
|
91
|
+
end
|
92
|
+
```
|
93
|
+
|
94
|
+
When switch is called, all requests coming to ActiveRecord will be routed to the tenant
|
95
|
+
you specify (with the exception of excluded models, see below). The tenant is automatically
|
96
|
+
switched back at the end of the block to what it was before.
|
97
|
+
|
98
|
+
There is also `switch!` which doesn't take a block, but it's recommended to use `switch`.
|
99
|
+
To return to the default tenant, you can call `switch` with no arguments.
|
100
|
+
|
101
|
+
#### Multiple Tenants
|
102
|
+
|
103
|
+
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:
|
104
|
+
|
105
|
+
```ruby
|
106
|
+
Apartment::Tenant.switch(['tenant_1', 'tenant_2']) do
|
107
|
+
# ...
|
108
|
+
end
|
109
|
+
```
|
110
|
+
|
111
|
+
### Switching Tenants per request
|
112
|
+
|
113
|
+
You can have Apartment route to the appropriate tenant by adding some Rack middleware.
|
114
|
+
Apartment can support many different "Elevators" that can take care of this routing to your data.
|
115
|
+
|
116
|
+
**NOTE: when switching tenants per-request, keep in mind that the order of your Rack middleware is important.**
|
117
|
+
See the [Middleware Considerations](#middleware-considerations) section for more.
|
118
|
+
|
119
|
+
The initializer above will generate the appropriate code for the Subdomain elevator
|
120
|
+
by default. You can see this in `config/initializers/apartment.rb` after running
|
121
|
+
that generator. If you're *not* using the generator, you can specify your
|
122
|
+
elevator below. Note that in this case you will **need** to require the elevator
|
123
|
+
manually in your `application.rb` like so
|
124
|
+
|
125
|
+
```ruby
|
126
|
+
# config/application.rb
|
127
|
+
require 'apartment/elevators/subdomain' # or 'domain', 'first_subdomain', 'host'
|
128
|
+
```
|
129
|
+
|
130
|
+
#### Switch on subdomain
|
131
|
+
|
132
|
+
In house, we use the subdomain elevator, which analyzes the subdomain of the request and switches to a tenant schema of the same name. It can be used like so:
|
133
|
+
|
134
|
+
```ruby
|
135
|
+
# application.rb
|
136
|
+
module MyApplication
|
137
|
+
class Application < Rails::Application
|
138
|
+
config.middleware.use Apartment::Elevators::Subdomain
|
139
|
+
end
|
140
|
+
end
|
141
|
+
```
|
142
|
+
|
143
|
+
If you want to exclude a domain, for example if you don't want your application to treat www like a subdomain, in an initializer in your application, you can set the following:
|
144
|
+
|
145
|
+
```ruby
|
146
|
+
# config/initializers/apartment/subdomain_exclusions.rb
|
147
|
+
Apartment::Elevators::Subdomain.excluded_subdomains = ['www']
|
148
|
+
```
|
149
|
+
|
150
|
+
This functions much in the same way as Apartment.excluded_models. This example will prevent switching your tenant when the subdomain is www. Handy for subdomains like: "public", "www", and "admin" :)
|
151
|
+
|
152
|
+
#### Switch on first subdomain
|
153
|
+
|
154
|
+
To switch on the first subdomain, which analyzes the chain of subdomains of the request and switches to a tenant schema of the first name in the chain (e.g. owls.birds.animals.com would switch to "owls"). It can be used like so:
|
155
|
+
|
156
|
+
```ruby
|
157
|
+
# application.rb
|
158
|
+
module MyApplication
|
159
|
+
class Application < Rails::Application
|
160
|
+
config.middleware.use Apartment::Elevators::FirstSubdomain
|
161
|
+
end
|
162
|
+
end
|
163
|
+
```
|
164
|
+
|
165
|
+
If you want to exclude a domain, for example if you don't want your application to treat www like a subdomain, in an initializer in your application, you can set the following:
|
166
|
+
|
167
|
+
```ruby
|
168
|
+
# config/initializers/apartment/subdomain_exclusions.rb
|
169
|
+
Apartment::Elevators::FirstSubdomain.excluded_subdomains = ['www']
|
170
|
+
```
|
171
|
+
|
172
|
+
This functions much in the same way as the Subdomain elevator. **NOTE:** in fact, at the time of this writing, the `Subdomain` and `FirstSubdomain` elevators both use the first subdomain ([#339](https://github.com/influitive/apartment/issues/339#issuecomment-235578610)). If you need to switch on larger parts of a Subdomain, consider using a Custom Elevator.
|
173
|
+
|
174
|
+
#### Switch on domain
|
175
|
+
|
176
|
+
To switch based on full domain (excluding the 'www' subdomains and top level domains *ie '.com'* ) use the following:
|
177
|
+
|
178
|
+
```ruby
|
179
|
+
# application.rb
|
180
|
+
module MyApplication
|
181
|
+
class Application < Rails::Application
|
182
|
+
config.middleware.use Apartment::Elevators::Domain
|
183
|
+
end
|
184
|
+
end
|
185
|
+
```
|
186
|
+
|
187
|
+
Note that if you have several subdomains, then it will match on the first *non-www* subdomain:
|
188
|
+
- example.com => example
|
189
|
+
- www.example.com => example
|
190
|
+
- a.example.com => a
|
191
|
+
|
192
|
+
#### Switch on full host using a hash
|
193
|
+
|
194
|
+
To switch based on full host with a hash to find corresponding tenant name use the following:
|
195
|
+
|
196
|
+
```ruby
|
197
|
+
# application.rb
|
198
|
+
module MyApplication
|
199
|
+
class Application < Rails::Application
|
200
|
+
config.middleware.use Apartment::Elevators::HostHash, {'example.com' => 'example_tenant'}
|
201
|
+
end
|
202
|
+
end
|
203
|
+
```
|
204
|
+
|
205
|
+
#### Switch on full host, ignoring given first subdomains
|
206
|
+
|
207
|
+
To switch based on full host to find corresponding tenant name use the following:
|
208
|
+
|
209
|
+
```ruby
|
210
|
+
# application.rb
|
211
|
+
module MyApplication
|
212
|
+
class Application < Rails::Application
|
213
|
+
config.middleware.use Apartment::Elevators::Host
|
214
|
+
end
|
215
|
+
end
|
216
|
+
```
|
217
|
+
|
218
|
+
If you want to exclude a first-subdomain, for example if you don't want your application to include www in the matching, in an initializer in your application, you can set the following:
|
219
|
+
|
220
|
+
```ruby
|
221
|
+
Apartment::Elevators::Host.ignored_first_subdomains = ['www']
|
222
|
+
```
|
223
|
+
|
224
|
+
With the above set, these would be the results:
|
225
|
+
- example.com => example.com
|
226
|
+
- www.example.com => example.com
|
227
|
+
- a.example.com => a.example.com
|
228
|
+
- www.a.example.com => a.example.com
|
229
|
+
|
230
|
+
#### Custom Elevator
|
231
|
+
|
232
|
+
A Generic Elevator exists that allows you to pass a `Proc` (or anything that responds to `call`) to the middleware. This Object will be passed in an `ActionDispatch::Request` object when called for you to do your magic. Apartment will use the return value of this proc to switch to the appropriate tenant. Use like so:
|
233
|
+
|
234
|
+
```ruby
|
235
|
+
# application.rb
|
236
|
+
module MyApplication
|
237
|
+
class Application < Rails::Application
|
238
|
+
# Obviously not a contrived example
|
239
|
+
config.middleware.use Apartment::Elevators::Generic, proc { |request| request.host.reverse }
|
240
|
+
end
|
241
|
+
end
|
242
|
+
```
|
243
|
+
|
244
|
+
Your other option is to subclass the Generic elevator and implement your own
|
245
|
+
switching mechanism. This is exactly how the other elevators work. Look at
|
246
|
+
the `subdomain.rb` elevator to get an idea of how this should work. Basically
|
247
|
+
all you need to do is subclass the generic elevator and implement your own
|
248
|
+
`parse_tenant_name` method that will ultimately return the name of the tenant
|
249
|
+
based on the request being made. It *could* look something like this:
|
250
|
+
|
251
|
+
```ruby
|
252
|
+
# app/middleware/my_custom_elevator.rb
|
253
|
+
class MyCustomElevator < Apartment::Elevators::Generic
|
254
|
+
|
255
|
+
# @return {String} - The tenant to switch to
|
256
|
+
def parse_tenant_name(request)
|
257
|
+
# request is an instance of Rack::Request
|
258
|
+
|
259
|
+
# example: look up some tenant from the db based on this request
|
260
|
+
tenant_name = SomeModel.from_request(request)
|
261
|
+
|
262
|
+
return tenant_name
|
263
|
+
end
|
264
|
+
end
|
265
|
+
```
|
266
|
+
|
267
|
+
#### Middleware Considerations
|
268
|
+
|
269
|
+
In the examples above, we show the Apartment middleware being appended to the Rack stack with
|
270
|
+
|
271
|
+
```ruby
|
272
|
+
Rails.application.config.middleware.use Apartment::Elevators::Subdomain
|
273
|
+
```
|
274
|
+
|
275
|
+
By default, the Subdomain middleware switches into a Tenant based on the subdomain at the beginning of the request, and when the request is finished, it switches back to the "public" Tenant. This happens in the [Generic](https://github.com/influitive/apartment/blob/development/lib/apartment/elevators/generic.rb#L22) elevator, so all elevators that inherit from this elevator will operate as such.
|
276
|
+
|
277
|
+
It's also good to note that Apartment switches back to the "public" tenant any time an error is raised in your application.
|
278
|
+
|
279
|
+
This works okay for simple applications, but it's important to consider that you may want to maintain the "selected" tenant through different parts of the Rack application stack. For example, the [Devise](https://github.com/plataformatec/devise) gem adds the `Warden::Manager` middleware at the end of the stack in the examples above, our `Apartment::Elevators::Subdomain` middleware would come after it. Trouble is, Apartment resets the selected tenant after the request is finish, so some redirects (e.g. authentication) in Devise will be run in the context of the "public" tenant. The same issue would also effect a gem such as the [better_errors](https://github.com/charliesome/better_errors) gem which inserts a middleware quite early in the Rails middleware stack.
|
280
|
+
|
281
|
+
To resolve this issue, consider adding the Apartment middleware at a location in the Rack stack that makes sense for your needs, e.g.:
|
282
|
+
|
283
|
+
```ruby
|
284
|
+
Rails.application.config.middleware.insert_before Warden::Manager, Apartment::Elevators::Subdomain
|
285
|
+
```
|
286
|
+
|
287
|
+
Now work done in the Warden middleware is wrapped in the `Apartment::Tenant.switch` context started in the Generic elevator.
|
288
|
+
|
289
|
+
### Dropping Tenants
|
290
|
+
|
291
|
+
To drop tenants using Apartment, use the following command:
|
292
|
+
|
293
|
+
```ruby
|
294
|
+
Apartment::Tenant.drop('tenant_name')
|
295
|
+
```
|
296
|
+
|
297
|
+
When method is called, the schema is dropped and all data from itself will be lost. Be careful with this method.
|
298
|
+
|
299
|
+
### Custom Prompt
|
300
|
+
|
301
|
+
#### Console methods
|
302
|
+
|
303
|
+
`ros-apartment` console configures two helper methods:
|
304
|
+
1. `tenant_list` - list available tenants while using the console
|
305
|
+
2. `st(tenant_name:String)` - Switches the context to the tenant name passed, if
|
306
|
+
it exists.
|
307
|
+
|
308
|
+
#### Custom printed prompt
|
309
|
+
|
310
|
+
`ros-apartment` also has a custom prompt that gives a bit more information about
|
311
|
+
the context in which you're running. It shows the environment as well as the tenant
|
312
|
+
that is currently switched to. In order for you to enable this, you need to require
|
313
|
+
the custom console in your application.
|
314
|
+
|
315
|
+
In `application.rb` add `require 'apartment/custom_console'`.
|
316
|
+
Please note that we rely on `pry-rails` to edit the prompt, thus your project needs
|
317
|
+
to install it as well. In order to do so, you need to add `gem 'pry-rails'` to your
|
318
|
+
project's gemfile.
|
319
|
+
|
320
|
+
## Config
|
321
|
+
|
322
|
+
The following config options should be set up in a Rails initializer such as:
|
323
|
+
|
324
|
+
config/initializers/apartment.rb
|
325
|
+
|
326
|
+
To set config options, add this to your initializer:
|
327
|
+
|
328
|
+
```ruby
|
329
|
+
Apartment.configure do |config|
|
330
|
+
# set your options (described below) here
|
331
|
+
end
|
332
|
+
```
|
333
|
+
|
334
|
+
### Skip tenant schema check
|
335
|
+
|
336
|
+
This is configurable by setting: `tenant_presence_check`. It defaults to true
|
337
|
+
in order to maintain the original gem behavior. This is only checked when using one of the PostgreSQL adapters.
|
338
|
+
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.
|
339
|
+
|
340
|
+
Setting this configuration value to `false` will disable the schema presence check before trying to switch the context.
|
341
|
+
|
342
|
+
```ruby
|
343
|
+
Apartment.configure do |config|
|
344
|
+
config.tenant_presence_check = false
|
345
|
+
end
|
346
|
+
```
|
347
|
+
|
348
|
+
### Additional logging information
|
349
|
+
|
350
|
+
Enabling this configuration will output the database that the process is currently connected to as well as which
|
351
|
+
schemas are in the search path. This can be enabled by setting to true the `active_record_log` configuration.
|
352
|
+
|
353
|
+
Please note that our custom logger inherits from `ActiveRecord::LogSubscriber` so this will be required for the configuration to work.
|
354
|
+
|
355
|
+
**Example log output:**
|
356
|
+
|
357
|
+
<img src="documentation/images/log_example.png">
|
358
|
+
|
359
|
+
```ruby
|
360
|
+
Apartment.configure do |config|
|
361
|
+
config.active_record_log = true
|
362
|
+
end
|
363
|
+
```
|
364
|
+
|
365
|
+
### Excluding models
|
366
|
+
|
367
|
+
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:
|
368
|
+
|
369
|
+
```ruby
|
370
|
+
config.excluded_models = ["User", "Company"] # these models will not be multi-tenanted, but remain in the global (public) namespace
|
371
|
+
```
|
372
|
+
|
373
|
+
Note that a string representation of the model name is now the standard so that models are properly constantized when reloaded in development
|
374
|
+
|
375
|
+
Rails will always access the 'public' tenant when accessing these models, but note that tables will be created in all schemas. This may not be ideal, but its done this way because otherwise rails wouldn't be able to properly generate the schema.rb file.
|
376
|
+
|
377
|
+
> **NOTE - Many-To-Many Excluded Models:**
|
378
|
+
> Since model exclusions must come from referencing a real ActiveRecord model, `has_and_belongs_to_many` is NOT supported. In order to achieve a many-to-many relationship for excluded models, you MUST use `has_many :through`. This way you can reference the join model in the excluded models configuration.
|
379
|
+
|
380
|
+
### Postgresql Schemas
|
381
|
+
|
382
|
+
#### Alternative: Creating new schemas by using raw SQL dumps
|
383
|
+
|
384
|
+
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.
|
385
|
+
|
386
|
+
This only applies while using postgres adapter and `config.use_schemas` is set to `true`.
|
387
|
+
(Note: this option doesn't use `db/structure.sql`, it creates SQL dump by executing `pg_dump`)
|
388
|
+
|
389
|
+
Enable this option with:
|
390
|
+
|
391
|
+
```ruby
|
392
|
+
config.use_sql = true
|
393
|
+
```
|
394
|
+
|
395
|
+
### Providing a Different default_tenant
|
396
|
+
|
397
|
+
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:
|
398
|
+
|
399
|
+
```ruby
|
400
|
+
config.default_tenant = "some_other_schema"
|
401
|
+
```
|
402
|
+
|
403
|
+
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.
|
404
|
+
|
405
|
+
### Persistent Schemas
|
406
|
+
|
407
|
+
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:
|
408
|
+
|
409
|
+
```ruby
|
410
|
+
config.persistent_schemas = ['some', 'other', 'schemas']
|
411
|
+
```
|
412
|
+
|
413
|
+
### Installing Extensions into Persistent Schemas
|
414
|
+
|
415
|
+
Persistent Schemas have numerous useful applications. [Hstore](http://www.postgresql.org/docs/9.1/static/hstore.html), for instance, is a popular storage engine for Postgresql. In order to use extensions such as Hstore, you have to install it to a specific schema and have that always in the `schema_search_path`.
|
416
|
+
|
417
|
+
When using extensions, keep in mind:
|
418
|
+
* Extensions can only be installed into one schema per database, so we will want to install it into a schema that is always available in the `schema_search_path`
|
419
|
+
* The schema and extension need to be created in the database *before* they are referenced in migrations, database.yml or apartment.
|
420
|
+
* There does not seem to be a way to create the schema and extension using standard rails migrations.
|
421
|
+
* Rails db:test:prepare deletes and recreates the database, so it needs to be easy for the extension schema to be recreated here.
|
422
|
+
|
423
|
+
#### 1. Ensure the extensions schema is created when the database is created
|
424
|
+
|
425
|
+
```ruby
|
426
|
+
# lib/tasks/db_enhancements.rake
|
427
|
+
|
428
|
+
####### Important information ####################
|
429
|
+
# This file is used to setup a shared extensions #
|
430
|
+
# within a dedicated schema. This gives us the #
|
431
|
+
# advantage of only needing to enable extensions #
|
432
|
+
# in one place. #
|
433
|
+
# #
|
434
|
+
# This task should be run AFTER db:create but #
|
435
|
+
# BEFORE db:migrate. #
|
436
|
+
##################################################
|
437
|
+
|
438
|
+
namespace :db do
|
439
|
+
desc 'Also create shared_extensions Schema'
|
440
|
+
task :extensions => :environment do
|
441
|
+
# Create Schema
|
442
|
+
ActiveRecord::Base.connection.execute 'CREATE SCHEMA IF NOT EXISTS shared_extensions;'
|
443
|
+
# Enable Hstore
|
444
|
+
ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS HSTORE SCHEMA shared_extensions;'
|
445
|
+
# Enable UUID-OSSP
|
446
|
+
ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS "uuid-ossp" SCHEMA shared_extensions;'
|
447
|
+
# Grant usage to public
|
448
|
+
ActiveRecord::Base.connection.execute 'GRANT usage ON SCHEMA shared_extensions to public;'
|
449
|
+
end
|
450
|
+
end
|
451
|
+
|
452
|
+
Rake::Task["db:create"].enhance do
|
453
|
+
Rake::Task["db:extensions"].invoke
|
454
|
+
end
|
455
|
+
|
456
|
+
Rake::Task["db:test:purge"].enhance do
|
457
|
+
Rake::Task["db:extensions"].invoke
|
458
|
+
end
|
459
|
+
```
|
460
|
+
|
461
|
+
#### 2. Ensure the schema is in Rails' default connection
|
462
|
+
|
463
|
+
Next, your `database.yml` file must mimic what you've set for your default and persistent schemas in Apartment. When you run migrations with Rails, it won't know about the extensions schema because Apartment isn't injected into the default connection, it's done on a per-request basis, therefore Rails doesn't know about `hstore` or `uuid-ossp` during migrations. To do so, add the following to your `database.yml` for all environments
|
464
|
+
|
465
|
+
```yaml
|
466
|
+
# database.yml
|
467
|
+
...
|
468
|
+
adapter: postgresql
|
469
|
+
schema_search_path: "public,shared_extensions"
|
470
|
+
...
|
471
|
+
```
|
472
|
+
|
473
|
+
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:
|
474
|
+
|
475
|
+
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)
|
476
|
+
2. Run `heroku pg:psql` from your command line
|
477
|
+
3. And then `DROP EXTENSION hstore;` (**Note:** This will drop all columns that use `hstore` type, so proceed with caution; only do this with a fresh PostgreSQL instance)
|
478
|
+
4. Next: `CREATE SCHEMA IF NOT EXISTS hstore;`
|
479
|
+
5. Finally: `CREATE EXTENSION IF NOT EXISTS hstore SCHEMA hstore;` and hit enter (`\q` to exit)
|
480
|
+
|
481
|
+
To double check, login to the console of your Heroku app and see if `Apartment.connection.schema_search_path` is `public,hstore`
|
482
|
+
|
483
|
+
#### 3. Ensure the schema is in the apartment config
|
484
|
+
|
485
|
+
```ruby
|
486
|
+
# config/initializers/apartment.rb
|
487
|
+
...
|
488
|
+
config.persistent_schemas = ['shared_extensions']
|
489
|
+
...
|
490
|
+
```
|
491
|
+
|
492
|
+
#### Alternative: Creating schema by default
|
493
|
+
|
494
|
+
Another way that we've successfully configured hstore for our applications is to add it into the
|
495
|
+
postgresql template1 database so that every tenant that gets created has it by default.
|
496
|
+
|
497
|
+
One caveat with this approach is that it can interfere with other projects in development using the same extensions and template, but not using apartment with this approach.
|
498
|
+
|
499
|
+
You can do so using a command like so
|
500
|
+
|
501
|
+
```bash
|
502
|
+
psql -U postgres -d template1 -c "CREATE SCHEMA shared_extensions AUTHORIZATION some_username;"
|
503
|
+
psql -U postgres -d template1 -c "CREATE EXTENSION IF NOT EXISTS hstore SCHEMA shared_extensions;"
|
504
|
+
```
|
505
|
+
|
506
|
+
The *ideal* setup would actually be to install `hstore` into the `public` schema and leave the public
|
507
|
+
schema in the `search_path` at all times. We won't be able to do this though until public doesn't
|
508
|
+
also contain the tenanted tables, which is an open issue with no real milestone to be completed.
|
509
|
+
Happy to accept PR's on the matter.
|
510
|
+
|
511
|
+
### Managing Migrations
|
512
|
+
|
513
|
+
In order to migrate all of your tenants (or postgresql schemas) you need to provide a list
|
514
|
+
of dbs to Apartment. You can make this dynamic by providing a Proc object to be called on migrations.
|
515
|
+
This object should yield an array of string representing each tenant name. Example:
|
516
|
+
|
517
|
+
```ruby
|
518
|
+
# Dynamically get tenant names to migrate
|
519
|
+
config.tenant_names = lambda{ Customer.pluck(:tenant_name) }
|
520
|
+
|
521
|
+
# Use a static list of tenant names for migrate
|
522
|
+
config.tenant_names = ['tenant1', 'tenant2']
|
523
|
+
```
|
524
|
+
|
525
|
+
You can then migrate your tenants using the normal rake task:
|
526
|
+
|
527
|
+
```ruby
|
528
|
+
rake db:migrate
|
529
|
+
```
|
530
|
+
|
531
|
+
This just invokes `Apartment::Tenant.migrate(#{tenant_name})` for each tenant name supplied
|
532
|
+
from `Apartment.tenant_names`
|
533
|
+
|
534
|
+
Note that you can disable the default migrating of all tenants with `db:migrate` by setting
|
535
|
+
`Apartment.db_migrate_tenants = false` in your `Rakefile`. Note this must be done
|
536
|
+
*before* the rake tasks are loaded. ie. before `YourApp::Application.load_tasks` is called
|
537
|
+
|
538
|
+
#### Parallel Migrations
|
539
|
+
|
540
|
+
Apartment supports parallelizing migrations into multiple threads when
|
541
|
+
you have a large number of tenants. By default, parallel migrations is
|
542
|
+
turned off. You can enable this by setting `parallel_migration_threads` to
|
543
|
+
the number of threads you want to use in your initializer.
|
544
|
+
|
545
|
+
Keep in mind that because migrations are going to access the database,
|
546
|
+
the number of threads indicated here should be less than the pool size
|
547
|
+
that Rails will use to connect to your database.
|
548
|
+
|
549
|
+
### Handling Environments
|
550
|
+
|
551
|
+
By default, when not using postgresql schemas, Apartment will prepend the environment to the tenant name
|
552
|
+
to ensure there is no conflict between your environments. This is mainly for the benefit of your development
|
553
|
+
and test environments. If you wish to turn this option off in production, you could do something like:
|
554
|
+
|
555
|
+
```ruby
|
556
|
+
config.prepend_environment = !Rails.env.production?
|
557
|
+
```
|
558
|
+
|
559
|
+
## Tenants on different servers
|
560
|
+
|
561
|
+
You can store your tenants in different databases on one or more servers.
|
562
|
+
To do it, specify your `tenant_names` as a hash, keys being the actual tenant names,
|
563
|
+
values being a hash with the database configuration to use.
|
564
|
+
|
565
|
+
Example:
|
566
|
+
|
567
|
+
```ruby
|
568
|
+
config.with_multi_server_setup = true
|
569
|
+
config.tenant_names = {
|
570
|
+
'tenant1' => {
|
571
|
+
adapter: 'postgresql',
|
572
|
+
host: 'some_server',
|
573
|
+
port: 5555,
|
574
|
+
database: 'postgres' # this is not the name of the tenant's db
|
575
|
+
# but the name of the database to connect to, before creating the tenant's db
|
576
|
+
# mandatory in postgresql
|
577
|
+
}
|
578
|
+
}
|
579
|
+
# or using a lambda:
|
580
|
+
config.tenant_names = lambda do
|
581
|
+
Tenant.all.each_with_object({}) do |tenant, hash|
|
582
|
+
hash[tenant.name] = tenant.db_configuration
|
583
|
+
end
|
584
|
+
end
|
585
|
+
```
|
586
|
+
|
587
|
+
## Background workers
|
588
|
+
|
589
|
+
Both these gems have been forked as a side consequence of having a new gem name.
|
590
|
+
You can use them exactly as you were using before. They are, just like this one
|
591
|
+
a drop-in replacement.
|
592
|
+
|
593
|
+
See [apartment-sidekiq](https://github.com/rails-on-services/apartment-sidekiq)
|
594
|
+
or [apartment-activejob](https://github.com/rails-on-services/apartment-activejob).
|
595
|
+
|
596
|
+
## Callbacks
|
597
|
+
|
598
|
+
You can execute callbacks when switching between tenants or creating a new one, Apartment provides the following callbacks:
|
599
|
+
|
600
|
+
- before_create
|
601
|
+
- after_create
|
602
|
+
- before_switch
|
603
|
+
- after_switch
|
604
|
+
|
605
|
+
You can register a callback using [ActiveSupport::Callbacks](https://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html) the following way:
|
606
|
+
|
607
|
+
```ruby
|
608
|
+
require 'apartment/adapters/abstract_adapter'
|
609
|
+
|
610
|
+
module Apartment
|
611
|
+
module Adapters
|
612
|
+
class AbstractAdapter
|
613
|
+
set_callback :switch, :before do |object|
|
614
|
+
...
|
615
|
+
end
|
616
|
+
end
|
617
|
+
end
|
618
|
+
end
|
619
|
+
```
|
620
|
+
|
621
|
+
## Running rails console without a connection to the database
|
622
|
+
|
623
|
+
By default, once apartment starts, it establishes a connection to the database. It is possible to
|
624
|
+
disable this initial connection, by running with `APARTMENT_DISABLE_INIT` set to something:
|
625
|
+
|
626
|
+
```shell
|
627
|
+
$ APARTMENT_DISABLE_INIT=true DATABASE_URL=postgresql://localhost:1234/buk_development bin/rails runner 'puts 1'
|
628
|
+
# 1
|
629
|
+
```
|
630
|
+
|
631
|
+
## Contributing
|
632
|
+
|
633
|
+
* In both `spec/dummy/config` and `spec/config`, you will see `database.yml.sample` files
|
634
|
+
* Copy them into the same directory but with the name `database.yml`
|
635
|
+
* Edit them to fit your own settings
|
636
|
+
* Rake tasks (see the Rakefile) will help you setup your dbs necessary to run tests
|
637
|
+
* To run tests without Mysql, call `rspec -t ~database:mysql`
|
638
|
+
* Please issue pull requests to the `development` branch. All development happens here, master is used for releases.
|
639
|
+
* Ensure that your code is accompanied with tests. No code will be merged without tests
|
640
|
+
|
641
|
+
* If you're looking to help, check out the TODO file for some upcoming changes I'd like to implement in Apartment.
|
642
|
+
|
643
|
+
### Running bundle install
|
644
|
+
|
645
|
+
mysql2 gem in some cases fails to install.
|
646
|
+
If you face problems running bundle install in OSX, try installing the gem running:
|
647
|
+
|
648
|
+
`gem install mysql2 -v '0.5.3' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include`
|
649
|
+
|
650
|
+
## License
|
651
|
+
|
652
|
+
Apartment is released under the [MIT License](http://www.opensource.org/licenses/MIT).
|