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

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

Instance Method Details

#absorbed_viaObject

A Reference from an entity type that fully absorbs this one



60
# File 'lib/activefacts/persistence/tables.rb', line 60

def absorbed_via; @absorbed_via; end

#absorbed_via=(r) ⇒ Object

:nodoc:



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

def absorbed_via=(r) #:nodoc:
  @absorbed_via = r
end

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



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
372
373
374
375
376
377
# File 'lib/activefacts/persistence/columns.rb', line 346

def all_columns(excluded_supertypes)    #:nodoc:
  debug :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|
      debug :columns, "Columns absorbed via #{ref}" do
        if (ref.role_type == :supertype)
          if excluded_supertypes[ref.to]
            debug :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



445
446
447
448
449
# File 'lib/activefacts/vocabulary/extensions.rb', line 445

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

#assimilationObject



273
274
275
276
277
278
279
# File 'lib/activefacts/vocabulary/extensions.rb', line 273

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

#create_implicit_fact_typesObject

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



479
480
481
482
483
484
485
486
487
488
# File 'lib/activefacts/vocabulary/extensions.rb', line 479

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)
    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



268
269
270
271
# File 'lib/activefacts/vocabulary/extensions.rb', line 268

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



299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/activefacts/persistence/columns.rb', line 299

def identifier_columns
  debug :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



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

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



466
467
468
469
470
471
472
473
474
475
476
# File 'lib/activefacts/vocabulary/extensions.rb', line 466

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

#inject_surrogateObject



159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/activefacts/generate/transform/surrogate.rb', line 159

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

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

	add_surrogate

	debug :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_independent
    debug :absorption, "EntityType #{name} is declared independent"
    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 }
    debug :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
      debug :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)
        debug :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
    }
    debug :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



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
# File 'lib/activefacts/generate/transform/surrogate.rb', line 96

def needs_surrogate

	# A recursive proc to replace any reference to an Entity Type by its identifying references:
	debug :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
	    debug :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
	    debug :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

		debug :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)

	debug :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) and the object is not the target of a foreign key:
	  if irf.size >= 2
	    if pk_fks.include?(nil)
 debug :transform_surrogate, "#{self.name} needs a surrogate because its multi-part key contains a non-table"
 return true
	    elsif references_to.size != 0
 debug :transform_surrogate, "#{self.name} is a join table between #{pk_fks.map(&:name).inspect} but is also an FK target"
 return true
	    else
 debug :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
	    debug :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:



371
372
373
374
375
376
377
378
379
# File 'lib/activefacts/persistence/reference.rb', line 371

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



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
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
372
373
374
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/activefacts/vocabulary/extensions.rb', line 281

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)
    debug :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
      debug :pi, "Got PI #{pi.name||pi.object_id} for nested #{name}" if pi
      debug :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

  debug :pi, "Looking for PI for ordinary entity #{name} with #{all_role.size} roles:" do
    debug :pi, "Roles are in fact types #{all_role.map{|r| r.fact_type.describe(r)}*", "}"
    pi = catch :pi do
        all_supertypes = supertypes_transitive
        debug :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

            debug :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
            debug :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

                debug :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.
                #debug :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
                    debug :pi, "      Role Sequence touches #{fact_type.describe(pi_role)}"

                    fact_type_roles = fact_type.all_role
                    debug :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|
                        debug :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)
                      }
                  }
                  debug :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
                      debug :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)
    debug :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.
        #debug :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
		debug :pi, "Using existing PC as PI for #{name}"
		pi = possible_pi
 end
      else
        debug :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



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/activefacts/persistence/columns.rb', line 318

def reference_columns(excluded_supertypes)    #:nodoc:
  debug :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, ans also in object_type.rb
      debug :columns, "Skipping #{absorbed_via}"
      #rc.each{|col| col.prepend(absorbed_via)}
      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:



436
437
438
439
# File 'lib/activefacts/vocabulary/extensions.rb', line 436

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

#subtypes_transitiveObject



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

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

#supertypesObject

An array all direct supertypes



452
453
454
455
456
# File 'lib/activefacts/vocabulary/extensions.rb', line 452

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

#supertypes_transitiveObject

An array of self followed by all supertypes in order:



459
460
461
462
463
# File 'lib/activefacts/vocabulary/extensions.rb', line 459

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