Class: Perpetuity::Postgres

Inherits:
Object
  • Object
show all
Defined in:
lib/perpetuity/postgres.rb,
lib/perpetuity/postgres/index.rb,
lib/perpetuity/postgres/query.rb,
lib/perpetuity/postgres/table.rb,
lib/perpetuity/postgres/version.rb,
lib/perpetuity/postgres/json_hash.rb,
lib/perpetuity/postgres/nil_query.rb,
lib/perpetuity/postgres/sql_value.rb,
lib/perpetuity/postgres/connection.rb,
lib/perpetuity/postgres/expression.rb,
lib/perpetuity/postgres/json_array.rb,
lib/perpetuity/postgres/null_value.rb,
lib/perpetuity/postgres/serializer.rb,
lib/perpetuity/postgres/sql_select.rb,
lib/perpetuity/postgres/sql_update.rb,
lib/perpetuity/postgres/table_name.rb,
lib/perpetuity/postgres/text_value.rb,
lib/perpetuity/postgres/query_union.rb,
lib/perpetuity/postgres/sql_function.rb,
lib/perpetuity/postgres/boolean_value.rb,
lib/perpetuity/postgres/negated_query.rb,
lib/perpetuity/postgres/numeric_value.rb,
lib/perpetuity/postgres/connection_pool.rb,
lib/perpetuity/postgres/query_attribute.rb,
lib/perpetuity/postgres/serialized_data.rb,
lib/perpetuity/postgres/table/attribute.rb,
lib/perpetuity/postgres/timestamp_value.rb,
lib/perpetuity/postgres/index_collection.rb,
lib/perpetuity/postgres/query_expression.rb,
lib/perpetuity/postgres/json_string_value.rb,
lib/perpetuity/postgres/query_intersection.rb,
lib/perpetuity/postgres/value_with_attribute.rb

Defined Under Namespace

Classes: BooleanValue, Connection, ConnectionPool, Expression, Index, IndexCollection, JSONArray, JSONHash, JSONStringValue, NegatedQuery, NilQuery, NullValue, NumericValue, Query, QueryAttribute, QueryExpression, QueryIntersection, QueryUnion, SQLFunction, SQLSelect, SQLUpdate, SQLValue, SerializedData, Serializer, Table, TableName, TextValue, TimestampValue, ValueWithAttribute

Constant Summary collapse

VERSION =
"0.0.2"
InvalidTableName =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Postgres

Returns a new instance of Postgres.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/perpetuity/postgres.rb', line 19

def initialize options
  @host      = options.fetch(:host) { 'localhost' }
  @port      = options.fetch(:port) { 5432 }
  @db        = options.fetch(:db)
  @pool_size = options.fetch(:pool_size) { 5 }
  @username  = options.fetch(:username) { ENV['USER'] }
  @password  = options.fetch(:password) {}

  @connection ||= ConnectionPool.new(
    db:       db,
    host:     host,
    port:     port,
    username: username,
    password: password,
    pool_size: pool_size
  )
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def connection
  @connection
end

#dbObject (readonly)

Returns the value of attribute db.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def db
  @db
end

#hostObject (readonly)

Returns the value of attribute host.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def host
  @host
end

#passwordObject (readonly)

Returns the value of attribute password.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def password
  @password
end

#pool_sizeObject (readonly)

Returns the value of attribute pool_size.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def pool_size
  @pool_size
end

#portObject (readonly)

Returns the value of attribute port.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def port
  @port
end

#usernameObject (readonly)

Returns the value of attribute username.



16
17
18
# File 'lib/perpetuity/postgres.rb', line 16

def username
  @username
end

Instance Method Details

#activate_index!(index) ⇒ Object



148
149
150
151
152
153
154
155
156
157
# File 'lib/perpetuity/postgres.rb', line 148

def activate_index! index
  sql = "CREATE "
  sql << "UNIQUE " if index.unique?
  sql << "INDEX ON #{TableName.new(index.table)} (#{index.attribute_names.join(',')})"
  connection.execute(sql)
  index.activate!
rescue PG::UndefinedTable => e
  create_table_with_attributes index.table, index.attributes
  retry
end

#active_indexes(table) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/perpetuity/postgres.rb', line 159

def active_indexes table
  sql = "  SELECT pg_class.relname AS name,\n         ARRAY(\n           SELECT pg_get_indexdef(pg_index.indexrelid, k + 1, true)\n           FROM generate_subscripts(pg_index.indkey, 1) AS k\n           ORDER BY k\n         ) AS attributes,\n         pg_index.indisunique AS unique,\n         pg_index.indisready AS active\n  FROM pg_class\n  INNER JOIN pg_index ON pg_class.oid = pg_index.indexrelid\n  WHERE pg_class.relname ~ '^\#{table}.*idx$'\n  SQL\n\n  indexes = connection.execute(sql).map do |index|\n    Index.from_sql(index)\n  end\n  IndexCollection.new(table, indexes)\nend\n"

#add_column(table_name, column_name, attributes) ⇒ Object



260
261
262
263
264
265
266
# File 'lib/perpetuity/postgres.rb', line 260

def add_column table_name, column_name, attributes
  attr = attributes.detect { |a| a.name.to_s == column_name.to_s }
  column = Table::Attribute.new(attr.name, attr.type, attr.options)

  sql = %Q(ALTER TABLE "#{table_name}" ADD #{column.sql_declaration})
  connection.execute sql
end

#cast_id(id, id_attribute) ⇒ Object



230
231
232
233
234
235
236
237
238
# File 'lib/perpetuity/postgres.rb', line 230

def cast_id id, id_attribute
  return id if id_attribute.nil?

  if [Bignum, Fixnum, Integer].include? id_attribute.type
    id.to_i
  else
    id
  end
end

#count(klass, query = 'TRUE', options = {}, &block) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/perpetuity/postgres.rb', line 80

def count klass, query='TRUE', options={}, &block
  where = if block_given?
            query(&block)
          else
            query
          end
  options = translate_options(options).merge(from: klass, where: where)
  table = table_name(klass)
  sql = select 'COUNT(*)', options
  connection.execute(sql).to_a.first['count'].to_i
rescue PG::UndefinedTable
  # Table does not exist, so there are 0 records
  0
end

#create_table(name, attributes) ⇒ Object



210
211
212
# File 'lib/perpetuity/postgres.rb', line 210

def create_table name, attributes
  connection.execute Table.new(name, attributes).create_table_sql
end

#create_table_with_attributes(klass, attributes) ⇒ Object



250
251
252
253
254
255
256
257
258
# File 'lib/perpetuity/postgres.rb', line 250

def create_table_with_attributes klass, attributes
  table_attributes = attributes.map do |attr|
    name = attr.name
    type = attr.type
    options = attr.options
    Table::Attribute.new name, type, options
  end
  create_table klass.to_s, table_attributes
end

#delete(id, klass) ⇒ Object



73
74
75
76
77
78
# File 'lib/perpetuity/postgres.rb', line 73

def delete id, klass
  table = TableName.new(klass)
  id_string = TextValue.new(id)
  sql = "DELETE FROM #{table} WHERE id = #{id_string}"
  connection.execute(sql).to_a
end

#delete_all(klass) ⇒ Object



103
104
105
106
107
108
109
# File 'lib/perpetuity/postgres.rb', line 103

def delete_all klass
  table = table_name(klass)
  sql = "DELETE FROM #{table}"
  connection.execute(sql)
rescue PG::UndefinedTable
  # Do nothing. There is already nothing here.
end

#drop_table(name) ⇒ Object Also known as: drop_collection



205
206
207
# File 'lib/perpetuity/postgres.rb', line 205

def drop_table name
  connection.execute "DROP TABLE IF EXISTS #{table_name(name)}"
end

#find(klass, id) ⇒ Object



95
96
97
# File 'lib/perpetuity/postgres.rb', line 95

def find klass, id
  retrieve(klass, query { |o| o.id == id }.to_db).first
end

#has_table?(name) ⇒ Boolean

Returns:

  • (Boolean)


214
215
216
# File 'lib/perpetuity/postgres.rb', line 214

def has_table? name
  connection.tables.include? name
end

#increment(klass, id, attribute, count = 1) ⇒ Object



244
245
246
247
248
# File 'lib/perpetuity/postgres.rb', line 244

def increment klass, id, attribute, count=1
  table = TableName.new(klass)
  sql = %Q{UPDATE #{table} SET #{attribute} = #{attribute} + #{count} WHERE id = #{SQLValue.new(id)} RETURNING #{attribute}}
  connection.execute(sql).to_a
end

#index(klass, attributes, options = {}) ⇒ Object



133
134
135
136
137
138
139
140
141
# File 'lib/perpetuity/postgres.rb', line 133

def index klass, attributes, options={}
  name = "#{klass}_#{Array(attributes).map(&:name).join('_')}_idx"
  index = Index.new(name: name,
                    attributes: Array(attributes),
                    unique: !!options[:unique],
                    active: false)
  indexes(klass) << index
  index
end

#indexes(klass) ⇒ Object



143
144
145
146
# File 'lib/perpetuity/postgres.rb', line 143

def indexes klass
  @indexes ||= {}
  @indexes[klass] ||= IndexCollection.new(klass)
end

#insert(klass, serialized_objects, attributes) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/perpetuity/postgres.rb', line 37

def insert klass, serialized_objects, attributes
  table = TableName.new(klass)
  data = serialized_objects.reduce(:+)
  sql = "INSERT INTO #{table} #{data} RETURNING id"

  results = connection.execute(sql).to_a
  ids = results.map { |result| cast_id(result['id'], attributes[:id]) }

  ids
rescue PG::UndefinedTable => e # Table doesn't exist, so we create it.
  retries ||= 0
  retries += 1
  create_table_with_attributes klass, attributes
  retry unless retries > 1
  raise e
rescue PG::UndefinedColumn => e
  retries ||= 0
  retries += 1
  error ||= nil

  if retries > 1 && e.message == error
    # We've retried more than once and we're getting the same error
    raise
  end

  error = e.message
  if error =~ /column "(.+)" of relation "(.+)" does not exist/
    column_name = $1
    table_name = $2
    add_column table_name, column_name, attributes
    retry
  end

  raise
end

#negate_query(&block) ⇒ Object



115
116
117
# File 'lib/perpetuity/postgres.rb', line 115

def negate_query &block
  NegatedQuery.new(&block)
end

#postgresify(value) ⇒ Object



218
219
220
# File 'lib/perpetuity/postgres.rb', line 218

def postgresify value
  Serializer.new(nil).serialize_attribute value
end

#query(&block) ⇒ Object



111
112
113
# File 'lib/perpetuity/postgres.rb', line 111

def query &block
  Query.new(&block)
end

#remove_index(index) ⇒ Object



180
181
182
183
# File 'lib/perpetuity/postgres.rb', line 180

def remove_index index
  sql = %Q{DROP INDEX IF EXISTS #{TableName.new(index.name)}}
  connection.execute(sql)
end

#retrieve(klass, criteria, options = {}) ⇒ Object



119
120
121
122
123
124
125
126
# File 'lib/perpetuity/postgres.rb', line 119

def retrieve klass, criteria, options={}
  options = translate_options(options).merge from: klass, where: criteria

  sql = select options
  connection.execute(sql).to_a
rescue PG::UndefinedTable
  []
end

#select(*args) ⇒ Object



201
202
203
# File 'lib/perpetuity/postgres.rb', line 201

def select *args
  SQLSelect.new(*args).to_s
end

#serialize(object, mapper) ⇒ Object



222
223
224
# File 'lib/perpetuity/postgres.rb', line 222

def serialize object, mapper
  Serializer.new(mapper).serialize object
end

#serialize_changed_attributes(object, original, mapper) ⇒ Object



226
227
228
# File 'lib/perpetuity/postgres.rb', line 226

def serialize_changed_attributes object, original, mapper
  Serializer.new(mapper).serialize_changes object, original
end

#table_name(klass) ⇒ Object



99
100
101
# File 'lib/perpetuity/postgres.rb', line 99

def table_name klass
  TableName.new(klass)
end

#translate_options(options) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/perpetuity/postgres.rb', line 185

def translate_options options
  options = options.dup
  if options[:attribute]
    options[:order] = options.delete(:attribute)
    if direction = options.delete(:direction)
      direction = direction.to_s[/(asc|desc)/i]
      options[:order] = { options[:order] => direction }
    end
  end
  if options[:skip]
    options[:offset] = options.delete(:skip)
  end

  options
end

#unserialize(data, mapper) ⇒ Object



240
241
242
# File 'lib/perpetuity/postgres.rb', line 240

def unserialize data, mapper
  Serializer.new(mapper).unserialize data
end

#update(klass, id, attributes) ⇒ Object



128
129
130
131
# File 'lib/perpetuity/postgres.rb', line 128

def update klass, id, attributes
  sql = SQLUpdate.new(klass, id, attributes).to_s
  connection.execute(sql).to_a
end