class DbMeta::Oracle::Constraint

Attributes

columns[R]
constraint_type[R]
delete_rule[R]
referential_constraint[R]
search_condition[R]
table_name[R]

Public Class Methods

new(args = {}) click to toggle source
Calls superclass method DbMeta::Oracle::Base::new
# File lib/db_meta/oracle/types/constraint.rb, line 8
def initialize(args = {})
  super(args)

  @extract_type = :embedded
  @columns = []
end
sort_value(type) click to toggle source
# File lib/db_meta/oracle/types/constraint.rb, line 68
def self.sort_value(type)
  ["PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK"].index(type)
end

Public Instance Methods

extract(args = {}) click to toggle source
# File lib/db_meta/oracle/types/constraint.rb, line 43
def extract(args = {})
  buffer = []
  buffer << "ALTER TABLE #{@table_name} ADD ("
  buffer << "  CONSTRAINT #{@name}"

  case @constraint_type
    when "CHECK"
      buffer << "  #{@constraint_type} (#{@search_condition})"
    when "FOREIGN KEY"
      buffer << "  #{@constraint_type} (#{@columns.join(", ")})"
      buffer << "  REFERENCES #{@referential_constraint.table_name} (#{@referential_constraint.columns.join(", ")})"
    else
      buffer << "  #{@constraint_type} (#{@columns.join(", ")})"
  end

  buffer << "  ON DELETE CASCADE" if @delete_rule == "CASCADE"
  buffer << "  ENABLE VALIDATE"
  buffer << ");"

  (0..buffer.size - 1).each { |n| buffer[n] = ("-- " + buffer[n]) } if args[:comment] == true

  buffer << nil
  buffer.join("\n")
end
fetch(args = {}) click to toggle source
# File lib/db_meta/oracle/types/constraint.rb, line 15
def fetch(args = {})
  connection = Connection.instance.get
  cursor = connection.exec("select * from user_constraints where constraint_name = '#{@name}'")
  cursor.fetch_hash do |item|
    @constraint_type = translate_constraint_type(item["CONSTRAINT_TYPE"])
    @extract_type = :merged if @constraint_type == "FOREIGN KEY"
    @table_name = item["TABLE_NAME"]
    @search_condition = item["SEARCH_CONDITION"]
    @delete_rule = item["DELETE_RULE"]

    if @constraint_type == "FOREIGN KEY"
      constraint = Constraint.new("OBJECT_TYPE" => "CONSTRAINT", "OBJECT_NAME" => item["R_CONSTRAINT_NAME"])
      constraint.fetch
      @referential_constraint = constraint
    end
  end
  cursor.close

  # get affected columns
  cursor = connection.exec("select * from user_cons_columns where constraint_name = '#{@name}' order by position")
  cursor.fetch_hash do |item|
    @columns << item["COLUMN_NAME"]
  end
  cursor.close
ensure
  connection.logoff
end

Private Instance Methods

translate_constraint_type(type) click to toggle source
# File lib/db_meta/oracle/types/constraint.rb, line 74
def translate_constraint_type(type)
  case type
    when "P"
      "PRIMARY KEY"
    when "U"
      "UNIQUE"
    when "C"
      "CHECK"
    when "R"
      "FOREIGN KEY"
  end
end