【问题标题】:Rails: Clearing postgres schemas in test databaseRails:清除测试数据库中的 postgres 模式
【发布时间】:2013-04-26 10:33:25
【问题描述】:

我正在使用 postgres 模式完成多租户的工作。

每次运行后都需要清除测试数据库中每个租户的架构,以便测试正确运行。

rspec 产生以下错误

An error occurred in an after hook
  PG::Error: ERROR:  syntax error at or near "where"
LINE 5:       where nspowner != (select oid from pg_roles where role...


1) account scoping displays only account A's records
  Failure/Error: let!(:account_a) { FactoryGirl.create(:account_with_schema) }
  Apartment::SchemaExists:
    The schema test1 already exists.
  # ./app/models/subscribem/account.rb:20:in `create_schema'
  # ./spec/support/factories/account_factory.rb:11:in `block (4 levels) in <top (required)>'
  # ./spec/features/accounts/scoping_spec.rb:4:in `block (2 levels) in <top (required)>'

这是每次测试后尝试清除数据库的代码。

spec_helper.rb

 config.after(:each) do
   Apartment::Database.reset
   DatabaseCleaner.clean
   connection = ActiveRecord::Base.connection.raw_connection
   schema = connection.query(%Q{
    SELECT 'drop schema ' || nspname || ' cascade;' 
    from pg_namespace 
    where nspname != 'public' AND 
    where nspowner != (select oid from pg_roles where rolname = 'postgres'); 
   })
   schemas.each do |query|
    connection.query(query.values.first)
   end 
 end

【问题讨论】:

    标签: ruby-on-rails postgresql rspec multi-tenant


    【解决方案1】:

    您的 SQL 似乎有一些问题。

    首先,您有两个WHERE 子句,只需使用AND 而不是AND WHERE。其次,您的子查询条件可能需要使用NOT IN 而不是!=

    试试:

    schema = connection.query(%Q{
      SELECT 'drop schema ' || nspname || ' cascade;' 
      from pg_namespace 
      where nspname != 'public' AND 
      nspowner NOT IN (select oid from pg_roles where rolname = 'postgres'); 
    })
    

    【讨论】:

    • 仍然产生相同的错误在后挂钩中发生错误 PG::Error: ERROR: syntax error at or near "where" LINE 5: where nspowner NOT IN (select oid from pg_roles where .. .
    • 看起来它还有两个WHERE子句,错误中提到的第5行应该是nspowner NOT IN...而不是where nspowner NOT IN
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多