如何使用ActiveRecord Rails 5打开和关闭新的数据库连接

时间:2018-03-13 12:02:12

标签: ruby-on-rails postgresql activerecord

我有一些工作负载需要增加WORK_MEMTEMP_BUFFERS。问题是,一旦我这样做,连接(会话)不会关闭并返回到池中。这意味着额外的内存使用量不是暂时的,因为我无法在不破坏会话的情况下更改TEMP_BUFFERS

我想工作流程是这样的:

conn = ActiveRecord.create_new_connection
conn.execute <<-SQL
  SET TEMP_BUFFERS TO '512MB';
  -- do some memory intensive 
  CREATE TEMPORARY TABLE .....;
  UPDATE ....;
SQL
conn.close

或许有一种方法可以关闭当前的连接并让游戏池创建一个新的...

1 个答案:

答案 0 :(得分:1)

似乎像new_connection is a private method,这是我们在池外部手动创建连接所需的,

然后,在检查源代码时,您可以执行以下操作:

connection_specification = ActiveRecord::Base.connection_pool.spec
# i.e.
#   connection_specification.adapter_method == 'postgresql_connection'
#   connection_specification.config == {:adapter=>"postgresql", :encoding=>"unicode", :pool=>5, :database=>"someapp_development"}

connection = ActiveRecord::Base.send(
  connection_specification.adapter_method, 
  connection_specification.config
)

# DEBUG:
puts connection.active?
# => true

connection.execute <<-SQL
  SET TEMP_BUFFERS TO '512MB';
  -- do some memory intensive 
  CREATE TEMPORARY TABLE .....;
  UPDATE ....;
SQL

connection.disconnect!

# DEBUG:
puts connection.active?
# => false