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
# 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 "CREATE INDEX #{range_idx} ON #{table} USING gist (#{range})"

    # 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.



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

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



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

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



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

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



71
72
73
# File 'lib/chrono_model/adapter/indexes.rb', line 71

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