class XMigra::DeclarativeSupport::Table

Attributes

constraints[R]
extensions[R]
name[RW]

Public Class Methods

decldoc() click to toggle source
# 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
new(name, structure) click to toggle source
# 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

Public Instance Methods

add_column(colspec) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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
columns() click to toggle source
# File lib/xmigra/declarative_support/table.rb, line 401
def columns
  @columns_by_name.values
end
creation_sql() click to toggle source
# 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_sql() click to toggle source
# File lib/xmigra/declarative_support/table.rb, line 601
def destruction_sql
  "DROP TABLE #{name};"
end
get_column(name) click to toggle source
# File lib/xmigra/declarative_support/table.rb, line 405
def get_column(name)
  @columns_by_name[name]
end
has_column?(name) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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_items() click to toggle source
# 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