Class: ActiveHarness::Memory::Adapter::Postgresql

Inherits:
Base
  • Object
show all
Defined in:
lib/active_harness/memory/adapter/postgresql.rb

Overview

PostgreSQL-backed memory adapter.

Requires the ‘pg’ gem — add it to your Gemfile yourself:

gem 'pg'

Connection options (one of):

connection:  — a PG::Connection instance you manage
url:         — connection string; adapter opens and closes the connection
host:, port:, dbname:, user:, password: — adapter opens and closes the connection

Storage options:

table_name:      — default "active_harness_memory_turns"
storage_size:    — max turns per session kept in the table (default 1000)
eviction_percent — % of oldest turns to drop when limit is hit (default 10)
on_trim:         — Proc called with evicted turns
namespace:       — isolates turns within a session

Constant Summary collapse

DEFAULT_TABLE =
"active_harness_memory_turns"
DEFAULT_STORAGE_SIZE =
1000
DEFAULT_TRIM_PERCENT =
10
TABLE_NAME_RE =
/\A[a-zA-Z_][a-zA-Z0-9_.]*\z/

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Postgresql

Returns a new instance of Postgresql.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 29

def initialize(opts = {})
  @table        = opts.fetch(:table_name, DEFAULT_TABLE).to_s
  @storage_size = opts.fetch(:storage_size, DEFAULT_STORAGE_SIZE)
  @trim_percent = opts.fetch(:eviction_percent, DEFAULT_TRIM_PERCENT)
  @on_trim      = opts[:on_trim]
  @namespace    = opts[:namespace]

  unless @table.match?(TABLE_NAME_RE)
    raise ArgumentError, "Invalid table_name: #{@table.inspect}"
  end

  # Connection source — one of: instance, url, keyword args.
  @borrowed_conn = opts[:connection]
  @conn_url      = opts[:url]
  @conn_kwargs   = opts.slice(:host, :port, :dbname, :user, :password)

  @owned_conn  = nil
  @session_id  = nil
  @turns       = []
end

Instance Method Details

#closeObject



66
67
68
69
70
71
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 66

def close
  if @owned_conn
    @owned_conn.close rescue nil
    @owned_conn = nil
  end
end

#deleteObject



73
74
75
76
77
78
79
80
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 73

def delete
  conn.exec_params(
    "DELETE FROM #{@table} " \
    "WHERE session_id = $1 AND (namespace IS NOT DISTINCT FROM $2)",
    [@session_id, @namespace]
  )
  @turns = []
end

#open(session_id) ⇒ Object



50
51
52
53
54
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 50

def open(session_id)
  @session_id = session_id
  ensure_connection!
  @turns = fetch_turns
end

#readObject



56
57
58
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 56

def read
  @turns.dup
end

#write(turn) ⇒ Object



60
61
62
63
64
# File 'lib/active_harness/memory/adapter/postgresql.rb', line 60

def write(turn)
  insert_turn(turn)
  @turns << turn
  trim_if_needed!
end