Skip to content

Instantly share code, notes, and snippets.

View codertcet111's full-sized avatar
💭
Consistency brings happiness

codertcet111

💭
Consistency brings happiness
View GitHub Profile
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
namespace :db do
task :setup do
# Set statement timeout for each query
if ActiveRecord::Base.connection_config[:adapter] == 'postgresql'
ActiveRecord::Base.connection.execute("SET statement_timeout = '10000';") # 10 seconds
class UpdateEmployeeDocumentWorker
include Shoryuken::Worker
shoryuken_options queue: 'default'
def perform(sqs_msg, employee_id, name)
UpdateEmployeeDocumentJob.new.perform(employee_id, name)
end
end
class Employee < ApplicationRecord
searchkick
after_commit :update_elasticsearch_document, on: [:update]
def update_elasticsearch_document
UpdateEmployeeDocumentJob.perform_later(id, name)
end
def update_document(name)
class UpdateEmployeeDocumentJob < ApplicationJob
queue_as :default
def perform(employee_id, name)
employee = Employee.find(employee_id)
employee.update_document(name)
end
end
production:
adapter: postgresql
database: my_app_production
username: my_app
password: secret
host: localhost
port: 5432
variables:
statement_timeout: 10000 # Set query timeout to 10 seconds
# db/migrate/20230419000000_create_products.rb
Thread.current[:__migration_context__] = true
class CreateProducts < ActiveRecord::Migration[6.1]
def change
create_table :products do |t|
t.string :name
t.integer :price
t.timestamps
# config/initializers/postgresql_adapter.rb
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def exec_query(sql, name = nil, binds = [])
if migration_context? # Skip query timeout check during migrations
super(sql, name, binds)
else
with_statement_timeout(10_000) { super(sql, name, binds) } # Set query timeout to 10 seconds
production:
adapter: postgresql
database: my_app_production
username: my_app
password: secret
host: localhost
port: 5432
variables:
statement_timeout: 10000 # Set query timeout to 10 seconds
# Find users who have posted at least 10 times in the last week
active_users = User.joins(:posts)
.where(posts: {created_at: 1.week.ago..Time.current})
.group("users.id")
.having("count(posts.id) >= 10")
# Find the average number of posts per user
avg_posts = User.joins(:posts)
.select("count(posts.id) as post_count")
.average("post_count")