Class: WCC::Contentful::Store::PostgresStore

Inherits:
Object
  • Object
show all
Defined in:
lib/wcc/contentful/store/postgres_store.rb

Defined Under Namespace

Classes: Query

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_options = nil) ⇒ PostgresStore

Returns a new instance of PostgresStore.



8
9
10
11
12
# File 'lib/wcc/contentful/store/postgres_store.rb', line 8

def initialize(connection_options = nil)
  connection_options ||= { dbname: 'postgres' }
  @conn = PG.connect(connection_options)
  PostgresStore.ensure_schema(@conn)
end

Class Method Details

.ensure_schema(conn) ⇒ Object



115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/wcc/contentful/store/postgres_store.rb', line 115

def self.ensure_schema(conn)
  conn.exec(<<~HEREDOC
    CREATE TABLE IF NOT EXISTS contentful_raw (
      id char(22) PRIMARY KEY,
      data jsonb
    );
    CREATE INDEX IF NOT EXISTS contentful_raw_value_type ON contentful_raw ((data->'sys'->>'type'));
    CREATE INDEX IF NOT EXISTS contentful_raw_value_content_type ON contentful_raw ((data->'sys'->'contentType'->'sys'->>'id'));
HEREDOC
  )

  conn.prepare('index_entry', 'INSERT INTO contentful_raw (id, data) values ($1, $2) ' \
    'ON CONFLICT (id) DO UPDATE SET data = $2')
  conn.prepare('select_entry', 'SELECT * FROM contentful_raw WHERE id = $1')
  conn.prepare('select_ids', 'SELECT id FROM contentful_raw')
end

Instance Method Details

#find(key) ⇒ Object



26
27
28
29
30
# File 'lib/wcc/contentful/store/postgres_store.rb', line 26

def find(key)
  result = @conn.exec_prepared('select_entry', [key])
  return if result.num_tuples == 0
  JSON.parse(result.getvalue(0, 1))
end

#find_allObject



32
33
34
# File 'lib/wcc/contentful/store/postgres_store.rb', line 32

def find_all
  Query.new(@conn)
end

#find_by(content_type:) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/wcc/contentful/store/postgres_store.rb', line 36

def find_by(content_type:)
  statement = "WHERE data->'sys'->'contentType'->'sys'->>'id' = $1"
  Query.new(
    @conn,
    statement,
    [content_type]
  )
end

#index(key, value) ⇒ Object



14
15
16
17
# File 'lib/wcc/contentful/store/postgres_store.rb', line 14

def index(key, value)
  @conn.exec_prepared('index_entry', [key, value.to_json])
  true
end

#keysObject



19
20
21
22
23
24
# File 'lib/wcc/contentful/store/postgres_store.rb', line 19

def keys
  result = @conn.exec_prepared('select_ids')
  arr = []
  result.each { |r| arr << r['id'].strip }
  arr
end