Class: ActiveFacts::Metamodel::EntityType

Inherits:
DomainObjectType show all
Defined in:
lib/activefacts/persistence/columns.rb,
lib/activefacts/persistence/index.rb,
lib/activefacts/persistence/tables.rb,
lib/activefacts/vocabulary/metamodel.rb,
lib/activefacts/persistence/reference.rb,
lib/activefacts/vocabulary/extensions.rb,
lib/activefacts/generate/transform/surrogate.rb

Overview

The EntityType class is defined in the metamodel; full documentation is not generated. This section shows the features relevant to relational Persistence.

Instance Attribute Summary collapse

Attributes inherited from ObjectType

#injected_surrogate_role, #tentative

Instance Method Summary collapse

Methods inherited from ObjectType

#add_surrogate, #all_absorbed_foreign_key_reference_path, #clear_indices, #clear_references, #columns, #definitely_not_table, #definitely_table, #foreign_keys, #foreign_keys_to, #has_references, #indices, #is_separate, #populate_columns, #populate_indices, #populate_reference, #probably_not_table, #probably_table, #rails_class_name, #rails_name, #rails_singular_name, #references_from, #references_to, #show_tabular, #wipe_columns

Instance Attribute Details

#absorbed_mirrorObject

:nodoc:



63
64
65
# File 'lib/activefacts/persistence/tables.rb', line 63

def absorbed_mirror
  @absorbed_mirror
end

#absorbed_viaObject

A Reference from an entity type that fully absorbs this one



62
63
64
# File 'lib/activefacts/persistence/tables.rb', line 62

def absorbed_via
  @absorbed_via
end

Instance Method Details

#all_columns(excluded_supertypes) ⇒ Object

When absorbing this EntityType, what columns must be absorbed? This must be a fresh copy, because the columns will have References prepended.



375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/activefacts/persistence/columns.rb', line 375

def all_columns(excluded_supertypes)    #:nodoc:
  trace :columns, "All Columns for #{name}" do
    columns = []
    sups = supertypes
    pi_roles = preferred_identifier.role_sequence.all_role_ref.map{|rr| rr.role}
    references_from.sort_by do |ref|
      # Put supertypes first, in order, then PI roles, non-subtype references by name, then subtypes by name:
      next [0, p] if p = sups.index(ref.to)
      if !ref.fact_type.is_a?(ActiveFacts::Metamodel::TypeInheritance)
        next [1, p] if p = pi_roles.index(ref.to_role)
        next [2, ref.to_names]
      end
      [3, ref.to_names]
    end.each do |ref|
      trace :columns, "Columns absorbed via #{ref}" do
        if (ref.role_type == :supertype)
          if excluded_supertypes[ref.to]
            trace :columns, "Exclude #{ref.to.name}, we already inherited it"
            next
          end

          next if (ref.to.absorbed_via != ref)
          excluded_supertypes[ref.to] = true
          columns += ref.columns(excluded_supertypes)
        else
          columns += ref.columns({})
        end
      end
    end
    columns
  end
end

#all_supertype_inheritanceObject



620
621
622
623
624
# File 'lib/activefacts/vocabulary/extensions.rb', line 620

def all_supertype_inheritance
  all_type_inheritance_as_subtype.sort_by{|ti|
      [ti.provides_identification ? 0 : 1, ti.supertype.name]
    }
end

#assimilationObject



447
448
449
450
451
452
453
# File 'lib/activefacts/vocabulary/extensions.rb', line 447

def assimilation
  if rr = identification_is_inherited
    rr.role.fact_type.assimilation
  else
    nil
  end
end

#common_supertype(other) ⇒ Object



653
654
655
656
657
658
# File 'lib/activefacts/vocabulary/extensions.rb', line 653

def common_supertype(other)
  return nil unless other.is_?(ActiveFacts::Metamodel::EntityType)
  candidates = supertypes_transitive & other.supertypes_transitive
  return candidates[0] if candidates.size <= 1
  candidates[0] # REVISIT: This might not be the closest supertype
end

#create_implicit_fact_typesObject

This entity type has just objectified a fact type. Create the necessary ImplicitFactTypes with phantom roles



661
662
663
664
665
666
667
668
669
670
671
# File 'lib/activefacts/vocabulary/extensions.rb', line 661

def create_implicit_fact_types
  fact_type.all_role.map do |role|
    next if role.link_fact_type     # Already exists
    link_fact_type = @constellation.LinkFactType(:new, :implying_role => role)
    link_fact_type.concept.implication_rule = 'objectification'
    phantom_role = @constellation.Role(link_fact_type, 0, :object_type => self, :concept => :new)
    # We could create a copy of the visible external role here, but there's no need yet...
    # Nor is there a need for a presence constraint, readings, etc.
    link_fact_type
  end
end

#identification_is_inheritedObject



442
443
444
445
# File 'lib/activefacts/vocabulary/extensions.rb', line 442

def identification_is_inherited
  preferred_identifier and
    preferred_identifier.role_sequence.all_role_ref.detect{|rr| rr.role.fact_type.is_a?(ActiveFacts::Metamodel::TypeInheritance) }
end

#identifier_columnsObject

The identifier_columns for an EntityType are the columns that result from the identifying roles



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/activefacts/persistence/columns.rb', line 327

def identifier_columns
  trace :columns, "Identifier Columns for #{name}" do
    if absorbed_via and
      # If this is a subtype that has its own identification, use that.
      (all_type_inheritance_as_subtype.size == 0 ||
        all_type_inheritance_as_subtype.detect{|ti| ti.provides_identification })
      return absorbed_via.from.identifier_columns
    end

    preferred_identifier.role_sequence.all_role_ref.map do |role_ref|
      ref = references_from.detect {|ref| ref.to_role == role_ref.role}

      columns.select{|column| column.references[0] == ref}
    end.flatten
  end
end

#identifying_refs_fromObject



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/activefacts/generate/transform/surrogate.rb', line 79

def identifying_refs_from
  pi = preferred_identifier
  rrs = pi.role_sequence.all_role_ref

#       REVISIT: This is actually a ref to us, not from
#       if absorbed_via
#         return [absorbed_via]
#       end

  rrs.map do |rr|
    r = references_from.detect{|ref| rr.role == ref.to_role }
    raise "failed to find #{name} identifying reference for #{rr.role.object_type.name} in #{references_from.inspect}" unless r
    r
  end
end

#identifying_supertypeObject

A subtype does not have a identifying_supertype if it defines its own identifier



641
642
643
644
645
646
647
648
649
650
651
# File 'lib/activefacts/vocabulary/extensions.rb', line 641

def identifying_supertype
  trace "Looking for identifying_supertype of #{name}"
  all_type_inheritance_as_subtype.detect{|ti|
      trace "considering supertype #{ti.supertype.name}"
      next unless ti.provides_identification
      trace "found identifying supertype of #{name}, it's #{ti.supertype.name}"
      return ti.supertype
    }
  trace "Failed to find identifying supertype of #{name}"
  return nil
end

#inject_surrogateObject



164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/activefacts/generate/transform/surrogate.rb', line 164

def inject_surrogate
  trace :transform_surrogate, "Injecting a surrogate key into #{self.name}"

  # Disable the preferred identifier:
  pi = preferred_identifier
  trace :transform_surrogate, "pi for #{name} was '#{pi.describe}'"
  pi.is_preferred_identifier = false
  @preferred_identifier = nil   # Kill the cache

  add_surrogate

  trace :transform_surrogate, "pi for #{name} is now '#{preferred_identifier.describe}'"
end

#is_auto_assignedObject

:nodoc:



65
66
67
# File 'lib/activefacts/persistence/tables.rb', line 65

def is_auto_assigned  #:nodoc:
  false
end

#is_tableObject

Returns true if this EntityType is a table



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/activefacts/persistence/tables.rb', line 70

def is_table
  return @is_table if @is_table != nil  # We already make a guess or decision

  @tentative = false

  # Always a table if marked so
  if is_separate
    trace :absorption, "EntityType #{name} is declared independent or separate"
    return @is_table = true
  end

  # Always a table if nowhere else to go, and has no one-to-ones that might flip:
  if references_to.empty? and
      !references_from.detect{|ref| ref.role_type == :one_one }
    trace :absorption, "EntityType #{name} is presumed independent as it has nowhere to go"
    return @is_table = true
  end

  # Subtypes may be partitioned or separate, in which case they're definitely tables.
  # Otherwise, if their identification is inherited from a supertype, they're definitely absorbed.
  # If theey have separate identification, it might absorb them.
  if (!supertypes.empty?)
    as_ti = all_supertype_inheritance.detect{|ti| ti.assimilation}
    @is_table = as_ti != nil
    if @is_table
      trace :absorption, "EntityType #{name} is #{as_ti.assimilation} from supertype #{as_ti.supertype}"
    else
      identifying_fact_type = preferred_identifier.role_sequence.all_role_ref.to_a[0].role.fact_type
      if identifying_fact_type.is_a?(TypeInheritance)
        trace :absorption, "EntityType #{name} is absorbed into supertype #{supertypes[0].name}"
        @is_table = false
      else
        # Possibly absorbed, we'll have to see how that pans out
        @tentative = true
      end
    end
    return @is_table
  end

  # If the preferred_identifier includes an auto_assigned ValueType
  # and this object is absorbed in more than one place, we need a table
  # to manage the auto-assignment.
  if references_to.size > 1 and
    preferred_identifier.role_sequence.all_role_ref.detect {|rr|
      next false unless rr.role.object_type.is_a? ValueType
      rr.role.object_type.is_auto_assigned
    }
    trace :absorption, "#{name} has an auto-assigned counter in its ID, so must be a table"
    @tentative = false
    return @is_table = true
  end

  @tentative = true
  @is_table = true
end

#needs_surrogateObject



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/activefacts/generate/transform/surrogate.rb', line 95

def needs_surrogate

  # A recursive proc to replace any reference to an Entity Type by its identifying references:
  trace :transform_surrogate_expansion, "Expanding key for #{name}"
  substitute_identifying_refs = proc do |object|
    if ref = object.absorbed_via
      # This shouldn't be necessary, but see the absorbed_via comment above.
      absorbed_into = ref.from
      trace :transform_surrogate_expansion, "recursing to handle absorption of #{object.name} into #{absorbed_into.name}"
      [substitute_identifying_refs.call(absorbed_into)]
    else
      irf = object.identifying_refs_from
      trace :transform_surrogate_expansion, "Iterating for #{object.name} over #{irf.inspect}" do
        irf.each_with_index do |ref, i|
          next if ref.is_unary
          next if ref.to_role.object_type.kind_of?(ActiveFacts::Metamodel::ValueType)
          recurse_to = ref.to_role.object_type

          trace :transform_surrogate_expansion, "#{i}: recursing to expand #{recurse_to.name} key in #{ref}" do
            irf[i] = substitute_identifying_refs.call(recurse_to)
          end
        end
      end
      irf
    end
  end
  irf = substitute_identifying_refs.call(self)

  trace :transform_surrogate, "Does #{name} need a surrogate? it's identified by #{irf.inspect}" do

    pk_fks = identifying_refs_from.map do |ref|
      ref.to && ref.to.is_table ? ref.to : nil
    end

    irf.flatten!

    # Multi-part identifiers are only allowed if:
    # * each part is a foreign key (i.e. it's a join table),
    # * there are no other columns (that might require updating) and
    # * the object is not the target of a foreign key:
    if irf.size >= 2
      if pk_fks.include?(nil)
        trace :transform_surrogate, "#{self.name} needs a surrogate because its multi-part key contains a non-table"
        return true
      elsif references_to.size != 0
        trace :transform_surrogate, "#{self.name} is a join table between #{pk_fks.map(&:name).inspect} but is also an FK target"
        return true
      elsif (references_from-identifying_refs_from).size > 0
        # There are other attributes to worry about
        return true
      else
        trace :transform_surrogate, "#{self.name} is a join table between #{pk_fks.map(&:name).inspect}"
        return false
      end
      return true
    end

    # Single-part key. It must be an Auto Counter, or we will add a surrogate

    identifying_type = irf[0].to
    if identifying_type.needs_surrogate
      trace :transform_surrogate, "#{self.name} needs a surrogate because #{irf[0].to.name} is not an AutoCounter, but #{identifying_type.supertypes_transitive.map(&:name).inspect}"
      return true
    end

    false
  end
end

#populate_referencesObject

:nodoc:



394
395
396
397
398
399
400
401
402
# File 'lib/activefacts/persistence/reference.rb', line 394

def populate_references          #:nodoc:
  if fact_type && fact_type.all_role.size > 1
    # NOT: fact_type.all_role.each do |role|  # Place roles in the preferred order instead:
    fact_type.preferred_reading.role_sequence.all_role_ref.map(&:role).each do |role|
      populate_reference role     # Objectified fact role, handled specially
    end
  end
  super
end

#preferred_identifierObject



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
# File 'lib/activefacts/vocabulary/extensions.rb', line 455

def preferred_identifier
  return @preferred_identifier if @preferred_identifier
  if fact_type
    # When compiling a fact instance, the delayed creation of a preferred identifier might be necessary
    if c = fact_type.check_and_add_spanning_uniqueness_constraint
      fact_type.check_and_add_spanning_uniqueness_constraint = nil
      c.call
    end

    # For a nested fact type, the PI is a unique constraint over N or N-1 roles
    fact_roles = Array(fact_type.all_role)
    trace :pi, "Looking for PI on nested fact type #{name}" do
      pi = catch :pi do
          fact_roles[0,2].each{|r|                  # Try the first two roles of the fact type, that's enough
              r.all_role_ref.map{|rr|               # All role sequences that reference this role
                  role_sequence = rr.role_sequence

                  # The role sequence is only interesting if it cover only this fact's roles
                  # or roles of the objectification
                  next if role_sequence.all_role_ref.size < fact_roles.size-1 # Not enough roles
                  next if role_sequence.all_role_ref.size > fact_roles.size   # Too many roles
                  next if role_sequence.all_role_ref.detect do |rsr|
                      if (of = rsr.role.fact_type) != fact_type
                        case of.all_role.size
                        when 1    # A unary FT must be played by the objectification of this fact type
                          next rsr.role.object_type != fact_type.entity_type
                        when 2    # A binary FT must have the objectification of this FT as the other player
                          other_role = (of.all_role-[rsr.role])[0]
                          next other_role.object_type != fact_type.entity_type
                        else
                          next true # A role in a ternary (or higher) cannot be usd in our identifier
                        end
                      end
                      rsr.role.fact_type != fact_type
                    end

                  # This role sequence is a candidate
                  pc = role_sequence.all_presence_constraint.detect{|c|
                      c.max_frequency == 1 && c.is_preferred_identifier
                    }
                  throw :pi, pc if pc
                }
            }
          throw :pi, nil
        end
      trace :pi, "Got PI #{pi.name||pi.object_id} for nested #{name}" if pi
      trace :pi, "Looking for PI on entity that nests this fact" unless pi
      raise "Oops, pi for nested fact is #{pi.class}" unless !pi || pi.is_a?(ActiveFacts::Metamodel::PresenceConstraint)
      return @preferred_identifier = pi if pi
    end
  end

  trace :pi, "Looking for PI for ordinary entity #{name} with #{all_role.size} roles:" do
    trace :pi, "Roles are in fact types #{all_role.map{|r| r.fact_type.describe(r)}*", "}"
    pi = catch :pi do
        all_supertypes = supertypes_transitive
        trace :pi, "PI roles must be played by one of #{all_supertypes.map(&:name)*", "}" if all_supertypes.size > 1
        all_role.each{|role|
            next unless role.unique || fact_type
            ftroles = Array(role.fact_type.all_role)

            # Skip roles in ternary and higher fact types, they're objectified, and in unaries, they can't identify us.
            next if ftroles.size != 2

            trace :pi, "Considering role in #{role.fact_type.describe(role)}"

            # Find the related role which must be included in any PI:
            # Note this works with unary fact types:
            pi_role = ftroles[ftroles[0] != role ? 0 : -1]

            next if ftroles.size == 2 && pi_role.object_type == self
            trace :pi, "  Considering #{pi_role.object_type.name} as a PI role"

            # If this is an identifying role, the PI is a PC whose role_sequence spans the role.
            # Walk through all role_sequences that span this role, and test each:
            pi_role.all_role_ref.each{|rr|
                role_sequence = rr.role_sequence  # A role sequence that includes a possible role

                trace :pi, "    Considering role sequence #{role_sequence.describe}"

                # All roles in this role_sequence must be in fact types which
                # (apart from that role) only have roles played by the original
                # entity type or a supertype.
                #trace :pi, "      All supertypes #{all_supertypes.map{|st| "#{st.object_id}=>#{st.name}"}*", "}"
                if role_sequence.all_role_ref.detect{|rsr|
                    fact_type = rsr.role.fact_type
                    trace :pi, "      Role Sequence touches #{fact_type.describe(pi_role)}"

                    fact_type_roles = fact_type.all_role
                    trace :pi, "      residual is #{fact_type_roles.map{|r| r.object_type.name}.inspect} minus #{rsr.role.object_type.name}"
                    residual_roles = fact_type_roles-[rsr.role]
                    residual_roles.detect{|rfr|
                        trace :pi, "        Checking residual role #{rfr.object_type.object_id}=>#{rfr.object_type.name}"
# This next line looks right, but breaks things. Find out what and why:
#                              !rfr.unique or
                          !all_supertypes.include?(rfr.object_type)
                      }
                  }
                  trace :pi, "      Discounting this role_sequence because it includes alien roles"
                  next
                end

                # Any presence constraint over this role sequence is a candidate
                rr.role_sequence.all_presence_constraint.detect{|pc|
                    # Found it!
                    if pc.is_preferred_identifier
                      trace :pi, "found PI #{pc.name||pc.object_id}, is_preferred_identifier=#{pc.is_preferred_identifier.inspect} over #{pc.role_sequence.describe}"
                      throw :pi, pc
                    end
                  }
              }
          }
        throw :pi, nil
      end
    raise "Oops, pi for entity is #{pi.class}" if pi && !pi.is_a?(ActiveFacts::Metamodel::PresenceConstraint)
    trace :pi, "Got PI #{pi.name||pi.object_id} for #{name}" if pi

    if !pi
      if (supertype = identifying_supertype)
        # This shouldn't happen now, as an identifying supertype is connected by a fact type
        # that has a uniqueness constraint marked as the preferred identifier.
        #trace :pi, "PI not found for #{name}, looking in supertype #{supertype.name}"
        #pi = supertype.preferred_identifier
        #return nil
      elsif fact_type
        possible_pi = nil
        fact_type.all_role.each{|role|
          role.all_role_ref.each{|role_ref|
            # Discount role sequences that contain roles not in this fact type:
            next if role_ref.role_sequence.all_role_ref.detect{|rr| rr.role.fact_type != fact_type }
            role_ref.role_sequence.all_presence_constraint.each{|pc|
              next unless pc.max_frequency == 1
              possible_pi = pc
              next unless pc.is_preferred_identifier
              pi = pc
              break
            }
            break if pi
          }
          break if pi
        }
        if !pi && possible_pi
          trace :pi, "Using existing PC as PI for #{name}"
          pi = possible_pi
        end
      else
        byebug
        trace :pi, "No PI found for #{name}"
      end
    end
    raise "No PI found for #{name}" unless pi
    @preferred_identifier = pi
  end
end

#reference_columns(excluded_supertypes) ⇒ Object

When creating a foreign key to this EntityType, what columns must we include (the identifier columns)? This must be a fresh copy, because the columns will have References prepended



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/activefacts/persistence/columns.rb', line 346

def reference_columns(excluded_supertypes)    #:nodoc:
  trace :columns, "Reference Columns for #{name}" do

    if absorbed_via and
      # If this is not a subtype, or is a subtype that has its own identification, use the id.
      (all_type_inheritance_as_subtype.size == 0 ||
        all_type_inheritance_as_subtype.detect{|ti| ti.provides_identification })
      rc = absorbed_via.from.reference_columns(excluded_supertypes)
      # The absorbed_via reference gets skipped here, and also in object_type.rb
      trace :columns, "Skipping #{absorbed_via}"
      absorbed_mirror ||= absorbed_via.reversed
      rc.each{|col| col.prepend(absorbed_mirror)}
      return rc
    end

    # REVISIT: Should have built preferred_identifier_references
    preferred_identifier.role_sequence.all_role_ref.map do |role_ref|
      # REVISIT: Should index references by to_role:
      ref = references_from.detect {|ref| ref.to_role == role_ref.role}

      raise "reference for role #{role_ref.describe} not found on #{name} in #{references_from.size} references:\n\t#{references_from.map(&:to_s)*"\n\t"}" unless ref

      ref.columns({})
    end.flatten
  end
end

#self_indexObject



87
88
89
# File 'lib/activefacts/persistence/index.rb', line 87

def self_index
	nil
end

#subtypesObject

An array of all direct subtypes:



611
612
613
614
# File 'lib/activefacts/vocabulary/extensions.rb', line 611

def subtypes
  # REVISIT: There's no sorting here. Should there be?
  all_type_inheritance_as_supertype.map{|ti| ti.subtype }
end

#subtypes_transitiveObject



616
617
618
# File 'lib/activefacts/vocabulary/extensions.rb', line 616

def subtypes_transitive
  [self] + subtypes.map{|st| st.subtypes_transitive}.flatten.uniq
end

#supertypesObject

An array all direct supertypes



627
628
629
630
631
# File 'lib/activefacts/vocabulary/extensions.rb', line 627

def supertypes
  all_supertype_inheritance.map{|ti|
      ti.supertype
    }
end

#supertypes_transitiveObject

An array of self followed by all supertypes in order:



634
635
636
637
638
# File 'lib/activefacts/vocabulary/extensions.rb', line 634

def supertypes_transitive
  ([self] + all_type_inheritance_as_subtype.map{|ti|
      ti.supertype.supertypes_transitive
    }).flatten.uniq
end