Module: ChronoModel::Adapter::Indexes

Included in:
ChronoModel::Adapter
Defined in:
lib/chrono_model/adapter/indexes.rb

Instance Method Summary collapse

Instance Method Details

#add_temporal_indexes(table, range, options = {}) ⇒ Object

Create temporal indexes for timestamp search.

This index is used by TimeMachine.at, ‘.current` and `.past` to build the temporal WHERE clauses that fetch the state of records at a single point in time.

Parameters:

`table`: the table where to create indexes on
`range`: the tsrange field

Options:

`:name`: the index name prefix, defaults to
         index_{table}_temporal_on_{range / lower_range / upper_range}


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/chrono_model/adapter/indexes.rb', line 22

def add_temporal_indexes(table, range, options = {})
  range_idx, lower_idx, upper_idx =
    temporal_index_names(table, range, options)

  chrono_alter_index(table, options) do
    execute <<-SQL.squish
      CREATE INDEX #{range_idx} ON #{table} USING gist ( #{range} )
    SQL

    # Indexes used for precise history filtering, sorting and, in history
    # tables, by UPDATE / DELETE triggers.
    #
    execute "CREATE INDEX #{lower_idx} ON #{table} ( lower(#{range}) )"
    execute "CREATE INDEX #{upper_idx} ON #{table} ( upper(#{range}) )"
  end
end

#add_timeline_consistency_constraint(table, range, options = {}) ⇒ Object

Adds an EXCLUDE constraint to the given table, to assure that no more than one record can occupy a definite segment on a timeline.



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/chrono_model/adapter/indexes.rb', line 51

def add_timeline_consistency_constraint(table, range, options = {})
  name = timeline_consistency_constraint_name(table)
  id   = options[:id] || primary_key(table)

  chrono_alter_constraint(table, options) do
    execute <<-SQL.squish
      ALTER TABLE #{table} ADD CONSTRAINT #{name}
        EXCLUDE USING gist ( #{id} WITH =, #{range} WITH && )
    SQL
  end
end

#remove_temporal_indexes(table, range, options = {}) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/chrono_model/adapter/indexes.rb', line 39

def remove_temporal_indexes(table, range, options = {})
  indexes = temporal_index_names(table, range, options)

  chrono_alter_index(table, options) do
    indexes.each { |idx| execute "DROP INDEX #{idx}" }
  end
end

#remove_timeline_consistency_constraint(table, options = {}) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'lib/chrono_model/adapter/indexes.rb', line 63

def remove_timeline_consistency_constraint(table, options = {})
  name = timeline_consistency_constraint_name(table)

  chrono_alter_constraint(table, options) do
    execute <<-SQL.squish
      ALTER TABLE #{table} DROP CONSTRAINT #{name}
    SQL
  end
end

#timeline_consistency_constraint_name(table) ⇒ Object



73
74
75
# File 'lib/chrono_model/adapter/indexes.rb', line 73

def timeline_consistency_constraint_name(table)
  "#{table}_timeline_consistency"
end