ros-apartment 2.3.0.alpha1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (148) hide show
  1. checksums.yaml +7 -0
  2. data/.github/ISSUE_TEMPLATE.md +21 -0
  3. data/.gitignore +15 -0
  4. data/.pryrc +3 -0
  5. data/.rspec +4 -0
  6. data/.travis.yml +65 -0
  7. data/Appraisals +71 -0
  8. data/Gemfile +10 -0
  9. data/Guardfile +24 -0
  10. data/HISTORY.md +398 -0
  11. data/README.md +576 -0
  12. data/Rakefile +128 -0
  13. data/TODO.md +51 -0
  14. data/apartment.gemspec +46 -0
  15. data/docker-compose.yml +33 -0
  16. data/gemfiles/rails_4_2.gemfile +23 -0
  17. data/gemfiles/rails_5_0.gemfile +22 -0
  18. data/gemfiles/rails_5_1.gemfile +22 -0
  19. data/gemfiles/rails_5_2.gemfile +18 -0
  20. data/gemfiles/rails_6_0.gemfile +22 -0
  21. data/gemfiles/rails_master.gemfile +22 -0
  22. data/lib/apartment.rb +118 -0
  23. data/lib/apartment/adapters/abstract_adapter.rb +269 -0
  24. data/lib/apartment/adapters/abstract_jdbc_adapter.rb +18 -0
  25. data/lib/apartment/adapters/jdbc_mysql_adapter.rb +19 -0
  26. data/lib/apartment/adapters/jdbc_postgresql_adapter.rb +56 -0
  27. data/lib/apartment/adapters/mysql2_adapter.rb +71 -0
  28. data/lib/apartment/adapters/postgis_adapter.rb +12 -0
  29. data/lib/apartment/adapters/postgresql_adapter.rb +236 -0
  30. data/lib/apartment/adapters/sqlite3_adapter.rb +56 -0
  31. data/lib/apartment/console.rb +12 -0
  32. data/lib/apartment/deprecation.rb +10 -0
  33. data/lib/apartment/elevators/domain.rb +22 -0
  34. data/lib/apartment/elevators/first_subdomain.rb +17 -0
  35. data/lib/apartment/elevators/generic.rb +32 -0
  36. data/lib/apartment/elevators/host.rb +30 -0
  37. data/lib/apartment/elevators/host_hash.rb +22 -0
  38. data/lib/apartment/elevators/subdomain.rb +62 -0
  39. data/lib/apartment/migrator.rb +51 -0
  40. data/lib/apartment/railtie.rb +67 -0
  41. data/lib/apartment/reloader.rb +21 -0
  42. data/lib/apartment/tasks/enhancements.rb +57 -0
  43. data/lib/apartment/tenant.rb +66 -0
  44. data/lib/apartment/version.rb +3 -0
  45. data/lib/generators/apartment/install/USAGE +5 -0
  46. data/lib/generators/apartment/install/install_generator.rb +10 -0
  47. data/lib/generators/apartment/install/templates/apartment.rb +109 -0
  48. data/lib/tasks/apartment.rake +145 -0
  49. data/spec/adapters/jdbc_mysql_adapter_spec.rb +19 -0
  50. data/spec/adapters/jdbc_postgresql_adapter_spec.rb +41 -0
  51. data/spec/adapters/mysql2_adapter_spec.rb +59 -0
  52. data/spec/adapters/postgresql_adapter_spec.rb +61 -0
  53. data/spec/adapters/sqlite3_adapter_spec.rb +83 -0
  54. data/spec/apartment_spec.rb +11 -0
  55. data/spec/config/database.yml.sample +49 -0
  56. data/spec/dummy/Rakefile +7 -0
  57. data/spec/dummy/app/controllers/application_controller.rb +6 -0
  58. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  59. data/spec/dummy/app/models/company.rb +3 -0
  60. data/spec/dummy/app/models/user.rb +3 -0
  61. data/spec/dummy/app/views/application/index.html.erb +1 -0
  62. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  63. data/spec/dummy/config.ru +4 -0
  64. data/spec/dummy/config/application.rb +49 -0
  65. data/spec/dummy/config/boot.rb +11 -0
  66. data/spec/dummy/config/database.yml.sample +44 -0
  67. data/spec/dummy/config/environment.rb +5 -0
  68. data/spec/dummy/config/environments/development.rb +28 -0
  69. data/spec/dummy/config/environments/production.rb +51 -0
  70. data/spec/dummy/config/environments/test.rb +34 -0
  71. data/spec/dummy/config/initializers/apartment.rb +4 -0
  72. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  73. data/spec/dummy/config/initializers/inflections.rb +10 -0
  74. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  75. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  76. data/spec/dummy/config/initializers/session_store.rb +8 -0
  77. data/spec/dummy/config/locales/en.yml +5 -0
  78. data/spec/dummy/config/routes.rb +3 -0
  79. data/spec/dummy/db/migrate/20110613152810_create_dummy_models.rb +39 -0
  80. data/spec/dummy/db/migrate/20111202022214_create_table_books.rb +14 -0
  81. data/spec/dummy/db/migrate/20180415260934_create_public_tokens.rb +13 -0
  82. data/spec/dummy/db/schema.rb +55 -0
  83. data/spec/dummy/db/seeds.rb +5 -0
  84. data/spec/dummy/db/seeds/import.rb +5 -0
  85. data/spec/dummy/public/404.html +26 -0
  86. data/spec/dummy/public/422.html +26 -0
  87. data/spec/dummy/public/500.html +26 -0
  88. data/spec/dummy/public/favicon.ico +0 -0
  89. data/spec/dummy/public/stylesheets/.gitkeep +0 -0
  90. data/spec/dummy/script/rails +6 -0
  91. data/spec/dummy_engine/.gitignore +8 -0
  92. data/spec/dummy_engine/Gemfile +15 -0
  93. data/spec/dummy_engine/Rakefile +34 -0
  94. data/spec/dummy_engine/bin/rails +12 -0
  95. data/spec/dummy_engine/config/initializers/apartment.rb +51 -0
  96. data/spec/dummy_engine/dummy_engine.gemspec +24 -0
  97. data/spec/dummy_engine/lib/dummy_engine.rb +4 -0
  98. data/spec/dummy_engine/lib/dummy_engine/engine.rb +4 -0
  99. data/spec/dummy_engine/lib/dummy_engine/version.rb +3 -0
  100. data/spec/dummy_engine/test/dummy/Rakefile +6 -0
  101. data/spec/dummy_engine/test/dummy/config.ru +4 -0
  102. data/spec/dummy_engine/test/dummy/config/application.rb +22 -0
  103. data/spec/dummy_engine/test/dummy/config/boot.rb +5 -0
  104. data/spec/dummy_engine/test/dummy/config/database.yml +25 -0
  105. data/spec/dummy_engine/test/dummy/config/environment.rb +5 -0
  106. data/spec/dummy_engine/test/dummy/config/environments/development.rb +37 -0
  107. data/spec/dummy_engine/test/dummy/config/environments/production.rb +78 -0
  108. data/spec/dummy_engine/test/dummy/config/environments/test.rb +39 -0
  109. data/spec/dummy_engine/test/dummy/config/initializers/assets.rb +8 -0
  110. data/spec/dummy_engine/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  111. data/spec/dummy_engine/test/dummy/config/initializers/cookies_serializer.rb +3 -0
  112. data/spec/dummy_engine/test/dummy/config/initializers/filter_parameter_logging.rb +4 -0
  113. data/spec/dummy_engine/test/dummy/config/initializers/inflections.rb +16 -0
  114. data/spec/dummy_engine/test/dummy/config/initializers/mime_types.rb +4 -0
  115. data/spec/dummy_engine/test/dummy/config/initializers/session_store.rb +3 -0
  116. data/spec/dummy_engine/test/dummy/config/initializers/wrap_parameters.rb +14 -0
  117. data/spec/dummy_engine/test/dummy/config/locales/en.yml +23 -0
  118. data/spec/dummy_engine/test/dummy/config/routes.rb +56 -0
  119. data/spec/dummy_engine/test/dummy/config/secrets.yml +22 -0
  120. data/spec/examples/connection_adapter_examples.rb +42 -0
  121. data/spec/examples/generic_adapter_custom_configuration_example.rb +95 -0
  122. data/spec/examples/generic_adapter_examples.rb +163 -0
  123. data/spec/examples/schema_adapter_examples.rb +234 -0
  124. data/spec/integration/apartment_rake_integration_spec.rb +107 -0
  125. data/spec/integration/query_caching_spec.rb +81 -0
  126. data/spec/integration/use_within_an_engine_spec.rb +28 -0
  127. data/spec/schemas/v1.rb +16 -0
  128. data/spec/schemas/v2.rb +43 -0
  129. data/spec/schemas/v3.rb +49 -0
  130. data/spec/spec_helper.rb +61 -0
  131. data/spec/support/apartment_helpers.rb +43 -0
  132. data/spec/support/capybara_sessions.rb +15 -0
  133. data/spec/support/config.rb +10 -0
  134. data/spec/support/contexts.rb +52 -0
  135. data/spec/support/requirements.rb +35 -0
  136. data/spec/support/setup.rb +46 -0
  137. data/spec/tasks/apartment_rake_spec.rb +129 -0
  138. data/spec/tenant_spec.rb +190 -0
  139. data/spec/unit/config_spec.rb +112 -0
  140. data/spec/unit/elevators/domain_spec.rb +32 -0
  141. data/spec/unit/elevators/first_subdomain_spec.rb +24 -0
  142. data/spec/unit/elevators/generic_spec.rb +54 -0
  143. data/spec/unit/elevators/host_hash_spec.rb +32 -0
  144. data/spec/unit/elevators/host_spec.rb +89 -0
  145. data/spec/unit/elevators/subdomain_spec.rb +76 -0
  146. data/spec/unit/migrator_spec.rb +77 -0
  147. data/spec/unit/reloader_spec.rb +24 -0
  148. metadata +487 -0
@@ -0,0 +1,269 @@
1
+ module Apartment
2
+ module Adapters
3
+ class AbstractAdapter
4
+ include ActiveSupport::Callbacks
5
+ define_callbacks :create, :switch
6
+
7
+ attr_writer :default_tenant
8
+
9
+ # @constructor
10
+ # @param {Hash} config Database config
11
+ #
12
+ def initialize(config)
13
+ @config = config
14
+ end
15
+
16
+ # Create a new tenant, import schema, seed if appropriate
17
+ #
18
+ # @param {String} tenant Tenant name
19
+ #
20
+ def create(tenant)
21
+ run_callbacks :create do
22
+ create_tenant(tenant)
23
+
24
+ switch(tenant) do
25
+ import_database_schema
26
+
27
+ # Seed data if appropriate
28
+ seed_data if Apartment.seed_after_create
29
+
30
+ yield if block_given?
31
+ end
32
+ end
33
+ end
34
+
35
+ # Note alias_method here doesn't work with inheritence apparently ??
36
+ #
37
+ def current
38
+ Apartment.connection.current_database
39
+ end
40
+
41
+ # Return the original public tenant
42
+ #
43
+ # @return {String} default tenant name
44
+ #
45
+ def default_tenant
46
+ @default_tenant || Apartment.default_tenant
47
+ end
48
+ alias :default_schema :default_tenant # TODO deprecate default_schema
49
+
50
+ # Drop the tenant
51
+ #
52
+ # @param {String} tenant name
53
+ #
54
+ def drop(tenant)
55
+ with_neutral_connection(tenant) do |conn|
56
+ drop_command(conn, tenant)
57
+ end
58
+
59
+ rescue *rescuable_exceptions => exception
60
+ raise_drop_tenant_error!(tenant, exception)
61
+ end
62
+
63
+ # Switch to a new tenant
64
+ #
65
+ # @param {String} tenant name
66
+ #
67
+ def switch!(tenant = nil)
68
+ run_callbacks :switch do
69
+ return reset if tenant.nil?
70
+
71
+ connect_to_new(tenant).tap do
72
+ Apartment.connection.clear_query_cache
73
+ end
74
+ end
75
+ end
76
+
77
+ # Connect to tenant, do your biz, switch back to previous tenant
78
+ #
79
+ # @param {String?} tenant to connect to
80
+ #
81
+ def switch(tenant = nil)
82
+ begin
83
+ previous_tenant = current
84
+ switch!(tenant)
85
+ yield
86
+
87
+ ensure
88
+ switch!(previous_tenant) rescue reset
89
+ end
90
+ end
91
+
92
+ # Iterate over all tenants, switch to tenant and yield tenant name
93
+ #
94
+ def each(tenants = Apartment.tenant_names)
95
+ tenants.each do |tenant|
96
+ switch(tenant){ yield tenant }
97
+ end
98
+ end
99
+
100
+ # Establish a new connection for each specific excluded model
101
+ #
102
+ def process_excluded_models
103
+ # All other models will shared a connection (at Apartment.connection_class) and we can modify at will
104
+ Apartment.excluded_models.each do |excluded_model|
105
+ process_excluded_model(excluded_model)
106
+ end
107
+ end
108
+
109
+ # Reset the tenant connection to the default
110
+ #
111
+ def reset
112
+ Apartment.establish_connection @config
113
+ end
114
+
115
+ # Load the rails seed file into the db
116
+ #
117
+ def seed_data
118
+ # Don't log the output of seeding the db
119
+ silence_warnings{ load_or_raise(Apartment.seed_data_file) } if Apartment.seed_data_file
120
+ end
121
+ alias_method :seed, :seed_data
122
+
123
+ # Prepend the environment if configured and the environment isn't already there
124
+ #
125
+ # @param {String} tenant Database name
126
+ # @return {String} tenant name with Rails environment *optionally* prepended
127
+ #
128
+ def environmentify(tenant)
129
+ unless tenant.include?(Rails.env)
130
+ if Apartment.prepend_environment
131
+ "#{Rails.env}_#{tenant}"
132
+ elsif Apartment.append_environment
133
+ "#{tenant}_#{Rails.env}"
134
+ else
135
+ tenant
136
+ end
137
+ else
138
+ tenant
139
+ end
140
+ end
141
+
142
+ protected
143
+
144
+ def process_excluded_model(excluded_model)
145
+ excluded_model.constantize.establish_connection @config
146
+ end
147
+
148
+ def drop_command(conn, tenant)
149
+ # connection.drop_database note that drop_database will not throw an exception, so manually execute
150
+ conn.execute("DROP DATABASE #{conn.quote_table_name(environmentify(tenant))}")
151
+ end
152
+
153
+ # Create the tenant
154
+ #
155
+ # @param {String} tenant Database name
156
+ #
157
+ def create_tenant(tenant)
158
+ with_neutral_connection(tenant) do |conn|
159
+ create_tenant_command(conn, tenant)
160
+ end
161
+ rescue *rescuable_exceptions => exception
162
+ raise_create_tenant_error!(tenant, exception)
163
+ end
164
+
165
+ def create_tenant_command(conn, tenant)
166
+ conn.create_database(environmentify(tenant), @config)
167
+ end
168
+
169
+ # Connect to new tenant
170
+ #
171
+ # @param {String} tenant Database name
172
+ #
173
+ def connect_to_new(tenant)
174
+ query_cache_enabled = ActiveRecord::Base.connection.query_cache_enabled
175
+
176
+ Apartment.establish_connection multi_tenantify(tenant)
177
+ Apartment.connection.active? # call active? to manually check if this connection is valid
178
+
179
+ Apartment.connection.enable_query_cache! if query_cache_enabled
180
+ rescue *rescuable_exceptions => exception
181
+ Apartment::Tenant.reset if reset_on_connection_exception?
182
+ raise_connect_error!(tenant, exception)
183
+ end
184
+
185
+ # Import the database schema
186
+ #
187
+ def import_database_schema
188
+ ActiveRecord::Schema.verbose = false # do not log schema load output.
189
+
190
+ load_or_raise(Apartment.database_schema_file) if Apartment.database_schema_file
191
+ end
192
+
193
+ # Return a new config that is multi-tenanted
194
+ # @param {String} tenant: Database name
195
+ # @param {Boolean} with_database: if true, use the actual tenant's db name
196
+ # if false, use the default db name from the db
197
+ def multi_tenantify(tenant, with_database = true)
198
+ db_connection_config(tenant).tap do |config|
199
+ if with_database
200
+ multi_tenantify_with_tenant_db_name(config, tenant)
201
+ end
202
+ end
203
+ end
204
+
205
+ def multi_tenantify_with_tenant_db_name(config, tenant)
206
+ config[:database] = environmentify(tenant)
207
+ end
208
+
209
+ # Load a file or raise error if it doesn't exists
210
+ #
211
+ def load_or_raise(file)
212
+ if File.exists?(file)
213
+ load(file)
214
+ else
215
+ raise FileNotFound, "#{file} doesn't exist yet"
216
+ end
217
+ end
218
+ # Backward compatibility
219
+ alias_method :load_or_abort, :load_or_raise
220
+
221
+ # Exceptions to rescue from on db operations
222
+ #
223
+ def rescuable_exceptions
224
+ [ActiveRecord::ActiveRecordError] + Array(rescue_from)
225
+ end
226
+
227
+ # Extra exceptions to rescue from
228
+ #
229
+ def rescue_from
230
+ []
231
+ end
232
+
233
+ def db_connection_config(tenant)
234
+ Apartment.db_config_for(tenant).clone
235
+ end
236
+
237
+ def with_neutral_connection(tenant, &block)
238
+ if Apartment.with_multi_server_setup
239
+ # neutral connection is necessary whenever you need to create/remove a database from a server.
240
+ # example: when you use postgresql, you need to connect to the default postgresql database before you create your own.
241
+ SeparateDbConnectionHandler.establish_connection(multi_tenantify(tenant, false))
242
+ yield(SeparateDbConnectionHandler.connection)
243
+ SeparateDbConnectionHandler.connection.close
244
+ else
245
+ yield(Apartment.connection)
246
+ end
247
+ end
248
+
249
+ def reset_on_connection_exception?
250
+ false
251
+ end
252
+
253
+ def raise_drop_tenant_error!(tenant, exception)
254
+ raise TenantNotFound, "Error while dropping tenant #{environmentify(tenant)}: #{ exception.message }"
255
+ end
256
+
257
+ def raise_create_tenant_error!(tenant, exception)
258
+ raise TenantExists, "Error while creating tenant #{environmentify(tenant)}: #{ exception.message }"
259
+ end
260
+
261
+ def raise_connect_error!(tenant, exception)
262
+ raise TenantNotFound, "Error while connecting to tenant #{environmentify(tenant)}: #{ exception.message }"
263
+ end
264
+
265
+ class SeparateDbConnectionHandler < ::ActiveRecord::Base
266
+ end
267
+ end
268
+ end
269
+ end
@@ -0,0 +1,18 @@
1
+ require 'apartment/adapters/abstract_adapter'
2
+
3
+ module Apartment
4
+ module Adapters
5
+ class AbstractJDBCAdapter < AbstractAdapter
6
+
7
+ private
8
+
9
+ def multi_tenantify_with_tenant_db_name(config, tenant)
10
+ config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}"
11
+ end
12
+
13
+ def rescue_from
14
+ ActiveRecord::JDBCError
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,19 @@
1
+ require "apartment/adapters/abstract_jdbc_adapter"
2
+
3
+ module Apartment
4
+
5
+ module Tenant
6
+ def self.jdbc_mysql_adapter(config)
7
+ Adapters::JDBCMysqlAdapter.new config
8
+ end
9
+ end
10
+
11
+ module Adapters
12
+ class JDBCMysqlAdapter < AbstractJDBCAdapter
13
+
14
+ def reset_on_connection_exception?
15
+ true
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,56 @@
1
+ require 'apartment/adapters/postgresql_adapter'
2
+
3
+ module Apartment
4
+ module Tenant
5
+
6
+ def self.jdbc_postgresql_adapter(config)
7
+ Apartment.use_schemas ?
8
+ Adapters::JDBCPostgresqlSchemaAdapter.new(config) :
9
+ Adapters::JDBCPostgresqlAdapter.new(config)
10
+ end
11
+ end
12
+
13
+ module Adapters
14
+
15
+ # Default adapter when not using Postgresql Schemas
16
+ class JDBCPostgresqlAdapter < PostgresqlAdapter
17
+
18
+ private
19
+
20
+ def multi_tenantify_with_tenant_db_name(config, tenant)
21
+ config[:url] = "#{config[:url].gsub(/(\S+)\/.+$/, '\1')}/#{environmentify(tenant)}"
22
+ end
23
+
24
+ def create_tenant_command(conn, tenant)
25
+ conn.create_database(environmentify(tenant), { :thisisahack => '' })
26
+ end
27
+
28
+ def rescue_from
29
+ ActiveRecord::JDBCError
30
+ end
31
+ end
32
+
33
+ # Separate Adapter for Postgresql when using schemas
34
+ class JDBCPostgresqlSchemaAdapter < PostgresqlSchemaAdapter
35
+
36
+ # Set schema search path to new schema
37
+ #
38
+ def connect_to_new(tenant = nil)
39
+ return reset if tenant.nil?
40
+ raise ActiveRecord::StatementInvalid.new("Could not find schema #{tenant}") unless Apartment.connection.all_schemas.include? tenant.to_s
41
+
42
+ @current = tenant.to_s
43
+ Apartment.connection.schema_search_path = full_search_path
44
+
45
+ rescue ActiveRecord::StatementInvalid, ActiveRecord::JDBCError
46
+ raise TenantNotFound, "One of the following schema(s) is invalid: #{full_search_path}"
47
+ end
48
+
49
+ private
50
+
51
+ def rescue_from
52
+ ActiveRecord::JDBCError
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,71 @@
1
+ require 'apartment/adapters/abstract_adapter'
2
+
3
+ module Apartment
4
+ module Tenant
5
+
6
+ def self.mysql2_adapter(config)
7
+ Apartment.use_schemas ?
8
+ Adapters::Mysql2SchemaAdapter.new(config) :
9
+ Adapters::Mysql2Adapter.new(config)
10
+ end
11
+ end
12
+
13
+ module Adapters
14
+ class Mysql2Adapter < AbstractAdapter
15
+
16
+ def initialize(config)
17
+ super
18
+
19
+ @default_tenant = config[:database]
20
+ end
21
+
22
+ protected
23
+
24
+ def rescue_from
25
+ Mysql2::Error
26
+ end
27
+ end
28
+
29
+ class Mysql2SchemaAdapter < AbstractAdapter
30
+ def initialize(config)
31
+ super
32
+
33
+ @default_tenant = config[:database]
34
+ reset
35
+ end
36
+
37
+ # Reset current tenant to the default_tenant
38
+ #
39
+ def reset
40
+ Apartment.connection.execute "use `#{default_tenant}`"
41
+ end
42
+
43
+ protected
44
+
45
+ # Connect to new tenant
46
+ #
47
+ def connect_to_new(tenant)
48
+ return reset if tenant.nil?
49
+
50
+ Apartment.connection.execute "use `#{environmentify(tenant)}`"
51
+
52
+ rescue ActiveRecord::StatementInvalid => exception
53
+ Apartment::Tenant.reset
54
+ raise_connect_error!(tenant, exception)
55
+ end
56
+
57
+ def process_excluded_model(model)
58
+ model.constantize.tap do |klass|
59
+ # Ensure that if a schema *was* set, we override
60
+ table_name = klass.table_name.split('.', 2).last
61
+
62
+ klass.table_name = "#{default_tenant}.#{table_name}"
63
+ end
64
+ end
65
+
66
+ def reset_on_connection_exception?
67
+ true
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,12 @@
1
+ # handle postgis adapter as if it were postgresql,
2
+ # only override the adapter_method used for initialization
3
+ require "apartment/adapters/postgresql_adapter"
4
+
5
+ module Apartment
6
+ module Tenant
7
+
8
+ def self.postgis_adapter(config)
9
+ postgresql_adapter(config)
10
+ end
11
+ end
12
+ end