Module: TimeRangeUniqueness::MigrationAdditions

Defined in:
lib/time_range_uniqueness/migration_additions.rb

Overview

This module provides methods for adding and managing time range uniqueness constraints in ActiveRecord migrations.

It allows you to add an exclusion constraint to ensure that time ranges do not overlap within a table.

Example

class AddEventTimeRangeUniqueness < ActiveRecord::Migration[6.1]
  def change
    add_time_range_uniqueness :events,
      with: :event_time_range,
      scope: :event_name,
      name: 'unique_event_time_ranges'
  end
end

Options

  • :with - The name of the column that stores the time range (required).

  • :scope - (Optional) An array of columns to scope the uniqueness check.

  • :name - (Optional) The name of the constraint.

Methods

  • add_time_range_uniqueness(table, options = {}) - Adds the time range column and the exclusion constraint.

  • CommandRecorder - Records the ‘add_time_range_uniqueness` command so it can be replayed during rollback.

Defined Under Namespace

Modules: CommandRecorder

Constant Summary collapse

COLUMN_TYPE =
:tstzrange
MAX_IDENTIFIER_LENGTH =

PostgreSQL truncates identifiers to 63 bytes (NAMEDATALEN - 1).

63

Instance Method Summary collapse

Instance Method Details

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

Adds a time range column and an exclusion constraint to the specified table.

This method creates or modifies a column to store time ranges and ensures that no two time ranges overlap for records with the same scoped columns.

Parameters:

  • table (Symbol, String)

    The name of the table to which the time range uniqueness constraint will be added.

  • options (Hash) (defaults to: {})

    The options for the constraint.

Options Hash (options):

  • :with (Symbol)

    The name of the time range column.

  • :scope (Array<Symbol>) — default: Optional

    Columns to scope the uniqueness check.

  • :name (String) — default: Optional

    The name of the constraint.



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/time_range_uniqueness/migration_additions.rb', line 49

def add_time_range_uniqueness(table, options = {})
  validate_options!(options)

  time_range_column = options[:with]
  scope_columns = Array(options[:scope])
  constraint_name = options[:name] || generate_constraint_name(table, scope_columns, time_range_column)

  reversible do |dir|
    dir.up { apply_up_migration(table, time_range_column, options, constraint_name, scope_columns) }
    dir.down { apply_down_migration(table, time_range_column, constraint_name) }
  end
end