influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.66k stars 464 forks source link

ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: #601

Closed slicksammy closed 5 years ago

slicksammy commented 5 years ago
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR:  relation "mapping_fields" does not exist
LINE 8:                WHERE a.attrelid = '"mapping_fields"'::regcla...
                                          ^
:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
                     pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod,
                     c.collname, col_description(a.attrelid, a.attnum) AS comment
                FROM pg_attribute a
                LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
                LEFT JOIN pg_type t ON a.atttypid = t.oid
                LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation
               WHERE a.attrelid = '"mapping_fields"'::regclass
                 AND a.attnum > 0 AND NOT a.attisdropped
               ORDER BY a.attnum
):

We recently migrated to rails major version 5 and this issue started happening in development. I believe it has to do with rails reloading because everything works fine on initial boot but some minor code changes while developing cause this issue.

Another interesting example is we have to skip Apartment configuration when we run rake db:drop for example because we get the same exception. So in our initializer file we have return if ENV['SKIP_APARTMENT_INITIALIZER'] == 'true' at the top and we run SKIP_APARTMENT_INITIALIZER=true bundle exec rake db:drop db:create db:migrate to setup our database

Steps to reproduce

Make code changes to controller in development environment (ie add a line of code) after initial boot.

rails s
load page
make change to controller
reload page
exception

OR

rake db:drop
exception

Expected behavior

Not raise exception

Actual behavior

Raises exception

System configuration

slicksammy commented 5 years ago

Solved. We added the following code into config/application.rb:

ActiveSupport::Reloader.after_class_unload do
  Apartment::Tenant.reset
end