Sha256: 5aa2c7d7f6fd0f1f365eff6847c15ba69962e585698d165860741cde2177d1f0

Contents?: true

Size: 1.67 KB

Versions: 3

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module TemporalTables
  # Uses the time from the "at" field stored in the record to filter queries
  # made to associations.
  module AssociationExtensions
    def target_scope
      # Kludge: Check +public_methods+ instead of using +responds_to?+ to
      # bypass +delegate_missing_to+ calls, as in +ActiveStorage::Attachment+.
      # Using responds_to? results in an infinite loop stack overflow.
      if @owner.public_methods.include?(:at_value)
        # If this is a history record but no at time was given,
        # assume the record's effective to date minus 1 microsecond
        # The logic here is to provide the association's history record at the end of
        # the parent record's effective period. Since effective ranges are exclusive of
        # the eff_to value, and the eff_* columns are datetime types with a precision of microseconds,
        # 1 microsecond before eff_to is the end of the inclusive boundary to accomplish this.
        super.at(@owner.at_value || (@owner.eff_to - TemporalTables::ONE_MICROSECOND))
      else
        super
      end
    end

    # There seems to be an issue with the statement cache for history associations.
    # This may be due to the at_value not being part of how the relations are hashed,
    # or that the cached statements are not parameterized. Will require further investigation.
    # In the meantime, we can workaround this issue by disabling the statement cache for History queries.
    def skip_statement_cache?(scope)
      klass.is_a?(TemporalTables::TemporalClass::ClassMethods) || super(scope)
    end
  end
end

ActiveRecord::Associations::Association.prepend TemporalTables::AssociationExtensions

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
temporal_tables-3.0.2 lib/temporal_tables/association_extensions.rb
temporal_tables-3.0.1 lib/temporal_tables/association_extensions.rb
temporal_tables-3.0.0 lib/temporal_tables/association_extensions.rb