Skip to content

Commit

Permalink
fix pg view
Browse files Browse the repository at this point in the history
  • Loading branch information
hooopo committed Oct 17, 2019
1 parent 5ebdbc8 commit 742652f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 16 deletions.
9 changes: 9 additions & 0 deletions db/migrate/20191017233918_init_view.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class InitView < ActiveRecord::Migration[5.2]
def up
BadgePostsViewManager.create!
end

def down
BadgePostsViewManager.drop!
end
end
18 changes: 2 additions & 16 deletions lib/badge_posts_view_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class BadgePostsViewManager

def self.create!
sql = <<~SQL
CREATE VIEW #{VIEW_NAME} AS
CREATE OR REPLACE VIEW #{VIEW_NAME} AS
SELECT p.*
FROM posts p
JOIN topics t ON t.id = p.topic_id
Expand All @@ -19,23 +19,9 @@ def self.create!
SQL

DB.exec(sql)
raise "Failed to create '#{VIEW_NAME}' view" unless badge_posts_view_exists?
end

def self.drop!
DB.exec("DROP VIEW #{VIEW_NAME}")
raise "Failed to drop '#{VIEW_NAME}' view" if badge_posts_view_exists?
end

def self.badge_posts_view_exists?
sql = <<~SQL
SELECT 1
FROM pg_catalog.pg_views
WHERE schemaname
IN ('public')
AND viewname = '#{VIEW_NAME}';
SQL

DB.exec(sql) == 1
DB.exec("DROP VIEW IF EXISTS #{VIEW_NAME}")
end
end

0 comments on commit 742652f

Please sign in to comment.