2013-04-26 60 views
2

我使用postgres模式通過多租戶調查。Rails:在測試數據庫中清除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 

回答

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'); 
}) 
+0

仍然產生相同的錯誤在發生錯誤鉤 PG ::錯誤後:錯誤:語法錯誤處或附近 「其中」 LINE 5:其中nspowner NOT IN(選擇oid from pg_roles where ... – 2013-04-26 17:51:30

+0

看起來它仍然有兩個'WHERE'子句,錯誤中提及的第5行應該是'nspowner NOT IN ...'not'where nspowner NOT IN'。 – Steve 2013-04-26 18:49:37