2019-05-02 17:17:27 -05:00
# frozen_string_literal: true
2019-02-24 23:02:32 -06:00
class MiniSqlMultisiteConnection < MiniSql :: Postgres :: Connection
2018-06-19 01:13:14 -05:00
class CustomBuilder < MiniSql :: Builder
def initialize ( connection , sql )
super
end
def secure_category ( secure_category_ids , category_alias = 'c' )
if secure_category_ids . present?
2019-05-02 17:17:27 -05:00
where ( " NOT COALESCE( #{ category_alias } .read_restricted, false) OR #{ category_alias } .id in (:secure_category_ids) " , secure_category_ids : secure_category_ids )
2018-06-19 01:13:14 -05:00
else
2019-05-02 17:17:27 -05:00
where ( " NOT COALESCE( #{ category_alias } .read_restricted, false) " )
2018-06-19 01:13:14 -05:00
end
self
end
end
class ParamEncoder
def encode ( * sql_array )
# use active record to avoid any discrepencies
2019-05-06 20:27:05 -05:00
ActiveRecord :: Base . public_send ( :sanitize_sql_array , sql_array )
2018-06-19 01:13:14 -05:00
end
end
2018-07-24 03:41:55 -05:00
class AfterCommitWrapper
2019-11-10 16:36:40 -06:00
def initialize ( & blk )
raise ArgumentError , " tried to create a Proc without a block in AfterCommitWrapper " if ! blk
@callback = blk
2018-07-24 03:41:55 -05:00
end
def committed! ( * )
@callback . call
end
def before_committed! ( * ) ; end
def rolledback! ( * ) ; end
2019-09-11 19:41:50 -05:00
def trigger_transactional_callbacks?
true
end
2018-07-24 03:41:55 -05:00
end
# Allows running arbitrary code after the current transaction has been committed.
2020-05-01 10:37:43 -05:00
# Works with nested ActiveRecord transaction blocks. Useful for scheduling sidekiq jobs.
# If not currently in a transaction, will execute immediately
2018-07-24 03:41:55 -05:00
def after_commit ( & blk )
2020-05-01 10:37:43 -05:00
return blk . call if ! ActiveRecord :: Base . connection . transaction_open?
# In tests, everything is run inside a transaction.
# To run immediately, check for joinable? transaction
# This mimics core rails behavior: https://github.com/rails/rails/blob/348e142b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb#L211
return blk . call if Rails . env . test? && ! ActiveRecord :: Base . connection . current_transaction . joinable?
2018-07-24 03:41:55 -05:00
ActiveRecord :: Base . connection . add_transaction_record (
AfterCommitWrapper . new ( & blk )
)
end
2018-06-19 01:13:14 -05:00
def self . instance
2018-06-19 01:43:50 -05:00
new ( nil , param_encoder : ParamEncoder . new )
2018-06-19 01:13:14 -05:00
end
2018-06-19 01:43:50 -05:00
2018-06-19 01:13:14 -05:00
# we need a tiny adapter here so we always run against the
# correct multisite connection
def raw_connection
ActiveRecord :: Base . connection . raw_connection
end
def build ( sql )
CustomBuilder . new ( self , sql )
end
2018-06-20 02:48:02 -05:00
def sql_fragment ( query , * args )
if args . length > 0
param_encoder . encode ( query , * args )
else
query
end
end
2018-06-19 01:13:14 -05:00
end