From 81684e64219dc5f2b6cb0161b15ed32dc4b5d06b Mon Sep 17 00:00:00 2001 From: r888888888 Date: Thu, 28 Jan 2016 18:31:03 -0800 Subject: [PATCH] use replica db for calculating post counts --- app/models/post.rb | 8 ++++---- app/models/post_read_only.rb | 9 +++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/app/models/post.rb b/app/models/post.rb index 8beec866b..98882ddc9 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -1061,8 +1061,8 @@ class Post < ActiveRecord::Base end def fast_count_search(tags, options = {}) - count = Post.with_timeout(options[:statement_timeout] || 500, nil, :tags => tags) do - Post.tag_match(tags).count + count = PostReadOnly.with_timeout(3_000, nil) do + PostReadOnly.tag_match(tags).count end if count == nil && tags !~ / / @@ -1083,8 +1083,8 @@ class Post < ActiveRecord::Base i = Post.maximum(:id) sum = 0 while i > 0 - count = Post.with_timeout(options[:statement_timeout] || 500, nil, :tags => tags) do - sum += Post.tag_match(tags).where("id <= ? and id > ?", i, i - 25_000).count + count = PostReadOnly.with_timeout(1_000, nil) do + sum += PostReadOnly.tag_match(tags).where("id <= ? and id > ?", i, i - 25_000).count i -= 25_000 end diff --git a/app/models/post_read_only.rb b/app/models/post_read_only.rb index c70f75b63..3307e8472 100644 --- a/app/models/post_read_only.rb +++ b/app/models/post_read_only.rb @@ -1,4 +1,13 @@ class PostReadOnly < Post establish_connection "ro_#{Rails.env}".to_sym attr_readonly *column_names + + def with_timeout(n, default_value = nil) + connection.execute("SET STATEMENT_TIMEOUT = #{n}") unless Rails.env == "test" + yield + rescue ::ActiveRecord::StatementInvalid => x + return default_value + ensure + connection.execute("SET STATEMENT_TIMEOUT = 0") unless Rails.env == "test" + end end