Class: DbMemoize::Value

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/db_memoize/value.rb

Constant Summary collapse

SQL =
::Simple::SQL

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.delete_all_orderedObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/db_memoize/value.rb', line 31

def self.delete_all_ordered
  relation = self
  relation = all unless is_a?(ActiveRecord::Relation)

  sql = relation.select(:ctid).to_sql
  SQL.ask <<-SQL
    DO $$DECLARE c record;
    BEGIN
      FOR c IN #{sql} ORDER BY ctid LOOP
        DELETE FROM #{DbMemoize::Value.table_name} WHERE ctid = c.ctid;
      END LOOP;
    END$$;
  SQL
end

.fast_create(entity_table_name, id, method_name, value) ⇒ Object



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
72
73
74
75
# File 'lib/db_memoize/value.rb', line 46

def self.fast_create(entity_table_name, id, method_name, value)
  method_name = method_name.to_s

  # clear out old entry (if any). This makes sure that any existing value
  # is cleared out properly.
  SQL.ask "DELETE FROM #{table_name} WHERE(entity_table_name, entity_id, method_name) = ($1, $2, $3)",
          entity_table_name, id, method_name

  dest_column = case value
                when String   then :val_string
                when Integer  then :val_integer
                when Float    then :val_float
                when Time     then :val_time
                when false    then :val_boolean
                when nil      then :val_nil
                when Hash     then :val_object
                when Array    then :val_object
                else
                  raise "Unsupported value of type #{value.class.name}: #{value.inspect}"
                end

  value = JSON.generate(value) if dest_column == :val_object
  sql = <<~SQL.freeze
    INSERT INTO #{table_name}
      (entity_table_name, entity_id, method_name, #{dest_column}, created_at)
      VALUES($1,$2,$3,$4,NOW())
  SQL

  SQL.ask sql, entity_table_name, id, method_name, value
end

Instance Method Details

#valueObject



26
27
28
29
# File 'lib/db_memoize/value.rb', line 26

def value
  # Note: val_boolean should come last.
  val_string || val_integer || val_float || val_time || val_object || val_boolean
end

#value=(value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/db_memoize/value.rb', line 12

def value=(value)
  self.val_integer = self.val_float = self.val_string = self.val_boolean = self.val_time = nil

  case value
  when String   then self.val_string = value
  when Integer  then self.val_integer = value
  when Float    then self.val_float = value
  when Time     then self.val_time = value
  when false    then self.val_boolean = value
  when true     then self.val_boolean = value
  when nil      then :nop
  end
end