Class: XMigra::DeclarativeSupport::Table

Inherits:
Object
  • Object
show all
Includes:
ImpdeclMigrationAdder::SupportedDatabaseObject
Defined in:
lib/xmigra/declarative_support/table.rb

Defined Under Namespace

Classes: CheckConstraint, Column, ColumnCreationFragment, ColumnListConstraint, Constraint, DefaultConstraint, Delta, ForeignKey, PrimaryKey, UniquenessConstraint

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ImpdeclMigrationAdder::SupportedDatabaseObject

included

Constructor Details

#initialize(name, structure) ⇒ Table

Returns a new instance of Table.



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
# File 'lib/xmigra/declarative_support/table.rb', line 320

def initialize(name, structure)
  structure = StructureReader.new(structure)
  @name = name
  constraints = {}
  @columns_by_name = (structure.array_fetch('columns', ->(c) {c['name']}) || raise(
    SpecificationError,
    "No columns specified for table #{@name}"
  )).inject({}) do |result, item|
    column = Column.new(item)
    result[column.name] = column
    
    if !(col_default = column.default_constraint).nil?
      constraints[col_default.name] = col_default
    end
    
    result
  end
  @primary_key = columns.select(&:primary_key?).tap do |cols|
    break nil if cols.empty?
    pk = PrimaryKey.new(
      "PK_#{name.gsub('.', '_')}", 
      StructureReader.new({'columns'=>cols.map(&:name)})
    )
    break (constraints[pk.name] = pk)
  end
  @constraints = (structure['constraints'] || []).inject(constraints) do |result, name_spec_pair|
    constraint = Constraint.deserialize(*name_spec_pair)
    
    if result.has_key?(constraint.name)
      raise SpecificationError, "Constraint #{constraint.name} is specified multiple times"
    end
    
    result[constraint.name] = constraint
    
    # Link DefaultConstraints to their respective Columns
    # because the constraint object is needed for column creation
    if constraint.kind_of? DefaultConstraint
      unless (col = get_column(constraint.column)).default_constraint.nil?
        raise SpecificationError, "Default constraint #{constraint.name} attempts to constrain #{constraint.column} which already has a default constraint"
      end
      col.default_constraint = constraint
    end
    
    result
  end
  errors = []
  @constraints.each_value do |constraint|
    if constraint.kind_of? PrimaryKey
      unless @primary_key.nil? || constraint.equal?(@primary_key)
        raise SpecificationError, "Multiple primary keys specified"
      end
      @primary_key = constraint
    end
    if constraint.kind_of? ColumnListConstraint
      unknown_cols = constraint.constrained_colnames.reject do |colname|
        has_column?(colname)
      end
      unless unknown_cols.empty?
        errors << "#{constraint.class::IDENTIFIER} constraint #{constraint.name} references unknown column(s): #{unknown_cols.join(', ')}"
      end
    end
  end
  
  structure.each_unused_standard_key do |k|
    errors << "Unrecognized standard key #{k.join('.')}"
  end
  
  unless errors.empty?
    raise SpecificationError, errors.join("\n")
  end
  
  @extensions = structure.each_extension.inject({}) do |result, kv_pair|
    key, value = kv_pair
    result[key] = value
    result
  end
end

Instance Attribute Details

#constraintsObject (readonly)

Returns the value of attribute constraints.



399
400
401
# File 'lib/xmigra/declarative_support/table.rb', line 399

def constraints
  @constraints
end

#extensionsObject (readonly)

Returns the value of attribute extensions.



399
400
401
# File 'lib/xmigra/declarative_support/table.rb', line 399

def extensions
  @extensions
end

#nameObject

Returns the value of attribute name.



398
399
400
# File 'lib/xmigra/declarative_support/table.rb', line 398

def name
  @name
end

Class Method Details

.decldocObject



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/xmigra/declarative_support/table.rb', line 9

def self.decldoc
  <<END_OF_HELP
The "!table" tag declares a table within the database using two standard top-
level keys: a required "columns" key and an optional "constraints" key.

The value of the "columns" key is a sequence of mappings, each giving "name"
and "type".  The value of the "type" key should be a type according to the
database system in use.  The "nullable" key (with a default value of true) can
map to false to indicate that the column should not accept null values.  The
key "primary key", whose value is interpreted as a Boolean, can be used to
indicate a primary key without using the more explicit "constraints" syntax.
Including a "default" key indicates a default constraint on the column, where
the value of the key is an expression to use for computing the default value
(which may be constrained by the database system in use).

The value of the "constraints" key is a mapping from constraint name to
constraint definition (itself a mapping).  The constraint type can either be
explicit through use of the "type" key in the constraint definition or
implicit through a prefix used to start the constraint name (and no explicit
constraint type).  The available constraint types are:

    Explicit type   Implicit prefix
    -------------   ---------------
    primary key     PK_
    unique          UQ_
    foreign key     FK_
    check           CK_
    default         DF_

Primary key and unique constraint definitions must have a "columns" key that
is a sequence of column names.  Only one primary key constraint may be
specified, whether through use of "primary key" keys in column mappings or
explicitly in the "constraints" section.  For foreign key constraint
definitions, the value of the "columns" key must be a mapping of referring
column name to referenced column name and a "link to" key, whose value gives
the name of the relation referenced, must be given.  Check constraint
definitions must have a "verify" key whose value is an SQL expression to be
checked for all records.  Default constraints (when given explicitly) must
have a "value" key giving the expression (with possible limitations imposed by
the database system in use) for the default value and an indication of the
constrained column: either a "column" key giving explicit reference to a
column or, if the constraint name starts with the implicit prefix, the part of
the constraint name after the prefix.

In addition to the required keys, foreign key constraints support two optional
keys: "on update" and "on delete".  These keys support generating "ON UPDATE"
and "ON DELETE" rules in the foreign key constraint creation SQL.  The value
associated with the key is used in the SQL.

When specifying SQL expressions in YAML, make sure to use appropriate quoting.
For example, where apostrophes delimit string literals in SQL and it might be
tempting to write a default expression with only one set of apostrophes around
it, YAML also uses apostrophes (or "single quotes") to mark a scalar value
(a string unless otherwise tagged), and so the apostrophes are consumed when
the YAML is parsed.  Either use a triple-apostrophe (YAML consumes the first,
converts the pair of second and third into a single apostrophe, and does the
reverse sequence at the end of the scalar) or use a block scalar (literal or
folded), preferably chopped (i.e. "|-" or ">-").  The rule is: whatever YAML
parsing sees as the value of the scalar, that is the SQL expression to be
used.

Extended information may be added to any standard-structure mapping in the
declarative document by using any string key beginning with "X-" (the LATIN
CAPITAL LETTER X followed by a HYPHEN-MINUS).  All other keys are reserved for
future expansion and may cause an error when generating implementing SQL.
END_OF_HELP
#'
end

Instance Method Details

#add_column(colspec) ⇒ Object



413
414
415
416
417
418
419
420
421
# File 'lib/xmigra/declarative_support/table.rb', line 413

def add_column(colspec)
  raise "Columns may not be added to the primary key after construction" if colspec['primary key']
  Column.new(colspec).tap do |col|
    @columns_by_name[col.name] = col
    if !(col_default = col.default_constraint).nil?
      @constraints[col_default.name] = col_default
    end
  end
end

#add_default(colname, expression, constr_name = nil) ⇒ Object



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# File 'lib/xmigra/declarative_support/table.rb', line 423

def add_default(colname, expression, constr_name=nil)
  col = get_column(colname)
  unless col.default_constraint.nil?
    raise "#{colname} already has a default constraint"
  end
  constr_name ||= "DF_#{colname}"
  if constraints[constr_name]
    raise "Constraint #{constr_name} already exists"
  end
  constraints[constr_name] = col.default_constraint = DefaultConstraint.new(
    constr_name,
    StructureReader.new({
      'column'=>colname,
      'value'=>expression,
    })
  )
end

#add_table_columns_sql_statements(columns) ⇒ Object



579
580
581
582
583
# File 'lib/xmigra/declarative_support/table.rb', line 579

def add_table_columns_sql_statements(columns)
  columns.map do |col|
    "ALTER TABLE #{name} ADD COLUMN #{column_creation_sql_fragment(col)};"
  end
end

#add_table_constraints_sql_statements(constraint_def_clauses) ⇒ Object



595
596
597
598
599
# File 'lib/xmigra/declarative_support/table.rb', line 595

def add_table_constraints_sql_statements(constraint_def_clauses)
  constraint_def_clauses.map do |create_clause|
    "ALTER TABLE #{name} ADD #{create_clause};"
  end
end

#alter_table_columns_sql_statements(column_name_type_pairs) ⇒ Object

Raises:

  • (NotImplementedError)


585
586
587
# File 'lib/xmigra/declarative_support/table.rb', line 585

def alter_table_columns_sql_statements(column_name_type_pairs)
  raise(NotImplementedError, "SQL 92 does not provide a standard way to alter a column's type") unless column_name_type_pairs.empty?
end

#column_alteration_occurs?(a, b) ⇒ Boolean

Returns:

  • (Boolean)


569
570
571
# File 'lib/xmigra/declarative_support/table.rb', line 569

def column_alteration_occurs?(a, b)
  [[a, b], [b, a]].map {|pair| alter_table_columns_sql_statements([pair])}.inject(&:!=)
end

#column_creation_sql_fragment(column) ⇒ Object



560
561
562
563
564
565
566
567
# File 'lib/xmigra/declarative_support/table.rb', line 560

def column_creation_sql_fragment(column)
  "#{column.name} #{column.type}".tap do |result|
    if dc = column.default_constraint
      result << " CONSTRAINT #{dc.name} DEFAULT #{dc.expression}"
    end
    result << " NOT NULL" unless column.nullable?
  end
end

#columnsObject



401
402
403
# File 'lib/xmigra/declarative_support/table.rb', line 401

def columns
  @columns_by_name.values
end

#creation_sqlObject



441
442
443
444
445
# File 'lib/xmigra/declarative_support/table.rb', line 441

def creation_sql
  "CREATE TABLE #{name} (\n" + \
  table_creation_items.map {|item| "  #{item.creation_sql}"}.join(",\n") + "\n" + \
  ");"
end

#destruction_sqlObject



601
602
603
# File 'lib/xmigra/declarative_support/table.rb', line 601

def destruction_sql
  "DROP TABLE #{name};"
end

#get_column(name) ⇒ Object



405
406
407
# File 'lib/xmigra/declarative_support/table.rb', line 405

def get_column(name)
  @columns_by_name[name]
end

#has_column?(name) ⇒ Boolean

Returns:

  • (Boolean)


409
410
411
# File 'lib/xmigra/declarative_support/table.rb', line 409

def has_column?(name)
  @columns_by_name.has_key? name
end

#remove_table_columns_sql_statements(column_names) ⇒ Object



589
590
591
592
593
# File 'lib/xmigra/declarative_support/table.rb', line 589

def remove_table_columns_sql_statements(column_names)
  column_names.map do |col_name|
    "ALTER TABLE #{name} DROP COLUMN #{col_name};"
  end
end

#remove_table_constraints_sql_statements(constraint_names) ⇒ Object



573
574
575
576
577
# File 'lib/xmigra/declarative_support/table.rb', line 573

def remove_table_constraints_sql_statements(constraint_names)
  constraint_names.map do |constr|
    "ALTER TABLE #{name} DROP CONSTRAINT #{constr};"
  end
end

#sql_to_effect_from(old_state) ⇒ Object



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
# File 'lib/xmigra/declarative_support/table.rb', line 457

def sql_to_effect_from(old_state)
  delta = Delta.new(old_state, self)
  parts = []
  
  # Remove constraints
  parts.concat remove_table_constraints_sql_statements(
    delta.constraints_to_drop
  )
  
  # Add new columns
  parts.concat add_table_columns_sql_statements(
    delta.new_columns
  ).to_a
  
  # Alter existing columns
  parts.concat alter_table_columns_sql_statements(
    delta.altered_column_pairs
  ).to_a
  
  # Remove columns
  parts.concat remove_table_columns_sql_statements(
    delta.removed_columns.lazy.map(&:name)
  ).to_a
  
  # Add constraints
  parts.concat add_table_constraints_sql_statements(
    delta.new_constraint_sql_clauses
  ).to_a
  
  (extensions.keys + old_state.extensions.keys).uniq.sort.each do |ext_key|
    case 
    when extensions.has_key?(ext_key) && !old_state.extensions.has_key?(ext_key)
      parts << "-- TODO: New extension #{ext_key}"
    when old_state.extensions.has_key?(ext_key) && !extensions.has_key?(ext_key)
      parts << "-- TODO: Extension #{ext_key} removed"
    else
      parts << "-- TODO: Modification to extension #{ext_key}"
    end
  end
  
  return parts.join("\n")
end

#table_creation_itemsObject



447
448
449
450
451
452
453
454
455
# File 'lib/xmigra/declarative_support/table.rb', line 447

def table_creation_items
  table_items = []
  table_items.concat(columns
    .map {|col| ColumnCreationFragment.new(self, col)}
  )
  table_items.concat(constraints.values
    .reject(&:only_on_column_at_creation?)
  )
end