Class: XMigra::DeclarativeSupport::Table
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
included
Constructor Details
#initialize(name, structure) ⇒ Table
Returns a new instance of Table.
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
|
# File 'lib/xmigra/declarative_support/table.rb', line 314
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
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
#constraints ⇒ Object
Returns the value of attribute constraints.
393
394
395
|
# File 'lib/xmigra/declarative_support/table.rb', line 393
def constraints
@constraints
end
|
#extensions ⇒ Object
Returns the value of attribute extensions.
393
394
395
|
# File 'lib/xmigra/declarative_support/table.rb', line 393
def extensions
@extensions
end
|
Returns the value of attribute name.
392
393
394
|
# File 'lib/xmigra/declarative_support/table.rb', line 392
def name
@name
end
|
Class Method Details
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
|
# File 'lib/xmigra/declarative_support/table.rb', line 9
def self.decldoc
"The \"!table\" tag declares a table within the database using two standard top-\nlevel keys: a required \"columns\" key and an optional \"constraints\" key.\n\nThe value of the \"columns\" key is a sequence of mappings, each giving \"name\"\nand \"type\". The value of the \"type\" key should be a type according to the\ndatabase system in use. The \"nullable\" key (with a default value of true) can\nmap to false to indicate that the column should not accept null values. The\nkey \"primary key\", whose value is interpreted as a Boolean, can be used to\nindicate a primary key without using the more explicit \"constraints\" syntax.\nIncluding a \"default\" key indicates a default constraint on the column, where\nthe value of the key is an expression to use for computing the default value\n(which may be constrained by the database system in use).\n\nThe value of the \"constraints\" key is a mapping from constraint name to\nconstraint definition (itself a mapping). The constraint type can either be\nexplicit through use of the \"type\" key in the constraint definition or\nimplicit through a prefix used to start the constraint name (and no explicit\nconstraint type). The available constraint types are:\n\n Explicit type Implicit prefix\n ------------- ---------------\n primary key PK_\n unique UQ_\n foreign key FK_\n check CK_\n default DF_\n\nPrimary key and unique constraint definitions must have a \"columns\" key that\nis a sequence of column names. Only one primary key constraint may be\nspecified, whether through use of \"primary key\" keys in column mappings or\nexplicitly in the \"constraints\" section. For foreign key constraint\ndefinitions, the value of the \"columns\" key must be a mapping of referring\ncolumn name to referenced column name. Check constraint definitions must have\na \"verify\" key whose value is an SQL expression to be checked for all records.\nDefault constraints (when given explicitly) must have a \"value\" key giving\nthe expression (with possible limitations imposed by the database system in\nuse) for the default value and an indication of the constrained column: either\na \"column\" key giving explicit reference to a column or, if the constraint\nname starts with the implicit prefix, the part of the constraint name after\nthe prefix.\n\nWhen specifying SQL expressions in YAML, make sure to use appropriate quoting.\nFor example, where apostrophes delimit string literals in SQL and it might be\ntempting to write a default expression with only one set of apostrophes around\nit, YAML also uses apostrophes (or \"single quotes\") to mark a scalar value\n(a string unless otherwise tagged), and so the apostrophes are consumed when\nthe YAML is parsed. Either use a triple-apostrophe (YAML consumes the first,\nconverts the pair of second and third into a single apostrophe, and does the\nreverse sequence at the end of the scalar) or use a block scalar (literal or\nfolded), preferably chopped (i.e. \"|-\" or \">-\"). The rule is: whatever YAML\nparsing sees as the value of the scalar, that is the SQL expression to be\nused.\n\nExtended information may be added to any standard-structure mapping in the\ndeclarative document by using any string key beginning with \"X-\" (the LATIN\nCAPITAL LETTER X followed by a HYPHEN-MINUS). All other keys are reserved for\nfuture expansion and may cause an error when generating implementing SQL.\n"
end
|
Instance Method Details
#add_default(colname, expression, constr_name = nil) ⇒ Object
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
|
# File 'lib/xmigra/declarative_support/table.rb', line 407
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(column_name_type_pairs) ⇒ Object
563
564
565
566
567
|
# File 'lib/xmigra/declarative_support/table.rb', line 563
def add_table_columns_sql_statements(column_name_type_pairs)
column_name_type_pairs.map do |col_name, col_type|
"ALTER TABLE #{name} ADD COLUMN #{col_name} #{col_type};"
end
end
|
#add_table_constraints_sql_statements(constraint_def_clauses) ⇒ Object
579
580
581
582
583
|
# File 'lib/xmigra/declarative_support/table.rb', line 579
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
569
570
571
|
# File 'lib/xmigra/declarative_support/table.rb', line 569
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
553
554
555
|
# File 'lib/xmigra/declarative_support/table.rb', line 553
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
544
545
546
547
548
549
550
551
|
# File 'lib/xmigra/declarative_support/table.rb', line 544
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
|
395
396
397
|
# File 'lib/xmigra/declarative_support/table.rb', line 395
def columns
@columns_by_name.values
end
|
#creation_sql ⇒ Object
425
426
427
428
429
|
# File 'lib/xmigra/declarative_support/table.rb', line 425
def creation_sql
"CREATE TABLE #{name} (\n" + \
table_creation_items.map {|item| " #{item.creation_sql}"}.join(",\n") + "\n" + \
");"
end
|
#destruction_sql ⇒ Object
585
586
587
|
# File 'lib/xmigra/declarative_support/table.rb', line 585
def destruction_sql
"DROP TABLE #{name};"
end
|
#get_column(name) ⇒ Object
399
400
401
|
# File 'lib/xmigra/declarative_support/table.rb', line 399
def get_column(name)
@columns_by_name[name]
end
|
#has_column?(name) ⇒ Boolean
403
404
405
|
# File 'lib/xmigra/declarative_support/table.rb', line 403
def has_column?(name)
@columns_by_name.has_key? name
end
|
#remove_table_columns_sql_statements(column_names) ⇒ Object
573
574
575
576
577
|
# File 'lib/xmigra/declarative_support/table.rb', line 573
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
557
558
559
560
561
|
# File 'lib/xmigra/declarative_support/table.rb', line 557
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
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
|
# File 'lib/xmigra/declarative_support/table.rb', line 441
def sql_to_effect_from(old_state)
delta = Delta.new(old_state, self)
parts = []
parts.concat remove_table_constraints_sql_statements(
delta.constraints_to_drop
)
parts.concat add_table_columns_sql_statements(
delta.new_columns.lazy.map {|col| [col.name, col.type]}
).to_a
parts.concat alter_table_columns_sql_statements(
delta.altered_column_pairs
).to_a
parts.concat remove_table_columns_sql_statements(
delta.removed_columns.lazy.map(&:name)
).to_a
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 ⇒ Object
431
432
433
434
435
436
437
438
439
|
# File 'lib/xmigra/declarative_support/table.rb', line 431
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
|