2019-02-25 13:02:32 +08:00
class MiniSqlMultisiteConnection < MiniSql :: Postgres :: Connection
2018-06-19 14:13:14 +08: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?
where ( " NOT COALESCE( " << category_alias << " .read_restricted, false) OR " << category_alias << " .id in (:secure_category_ids) " , secure_category_ids : secure_category_ids )
else
where ( " NOT COALESCE( " << category_alias << " .read_restricted, false) " )
end
self
end
end
class ParamEncoder
def encode ( * sql_array )
# use active record to avoid any discrepencies
2019-05-07 09:27:05 +08:00
ActiveRecord :: Base . public_send ( :sanitize_sql_array , sql_array )
2018-06-19 14:13:14 +08:00
end
end
2018-07-24 16:41:55 +08:00
class AfterCommitWrapper
def initialize
@callback = Proc . new
end
def committed! ( * )
@callback . call
end
def before_committed! ( * ) ; end
def rolledback! ( * ) ; end
end
# Allows running arbitrary code after the current transaction has been committed.
# Works even with nested transactions. Useful for scheduling sidekiq jobs.
def after_commit ( & blk )
ActiveRecord :: Base . connection . add_transaction_record (
AfterCommitWrapper . new ( & blk )
)
end
2018-06-19 14:13:14 +08:00
def self . instance
2018-06-19 14:43:50 +08:00
new ( nil , param_encoder : ParamEncoder . new )
2018-06-19 14:13:14 +08:00
end
2018-06-19 14:43:50 +08:00
2018-06-19 14:13:14 +08: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 15:48:02 +08:00
def sql_fragment ( query , * args )
if args . length > 0
param_encoder . encode ( query , * args )
else
query
end
end
2018-06-19 14:13:14 +08:00
end