Module: DynamicMigrations::Postgres::Server::Database::Differences::ToMigrations::Schemas::Tables::PrimaryKey

Included in:
DynamicMigrations::Postgres::Server::Database::Differences::ToMigrations
Defined in:
lib/dynamic_migrations/postgres/server/database/differences/to_migrations/schemas/tables/primary_key.rb

Instance Method Summary collapse

Instance Method Details

#process_primary_key(schema_name, table_name, configuration_primary_key, database_primary_key) ⇒ Object



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
# File 'lib/dynamic_migrations/postgres/server/database/differences/to_migrations/schemas/tables/primary_key.rb', line 12

def process_primary_key schema_name, table_name, configuration_primary_key, database_primary_key
  log.debug "    Processing Primary Key"
  configuration_primary_key_exists = configuration_primary_key && configuration_primary_key[:exists]
  database_primary_key_exists = database_primary_key && database_primary_key[:exists]

  # If the primary_key exists in the configuration but not in the database
  # then we have to create it.
  if configuration_primary_key_exists == true && database_primary_key_exists == false
    log.debug "    Primary Key exists in configuration but not in the database"

    # a migration to create the primary_key
    primary_key = @database.configured_schema(schema_name).table(table_name).primary_key
    @generator.add_primary_key primary_key

  # If the schema exists in the database but not in the configuration
  # then we need to delete it.
  elsif configuration_primary_key_exists == false && database_primary_key_exists == true
    log.debug "    Primary Key exists in database but not in the configuration"

    # a migration to create the primary_key
    primary_key = @database.loaded_schema(schema_name).table(table_name).primary_key
    @generator.remove_primary_key primary_key

  # If the primary_key exists in both the configuration and database representations
  elsif configuration_primary_key_exists == true && database_primary_key_exists == true
    log.debug "    Primary Key exists in both configuration and the database"

    # If the definition (i.e. the column names) is different then we need to update the primary key.
    if configuration_primary_key.except(:exists, :description).filter { |name, attributes| attributes[:matches] == false }.any?
      log.debug "      Primary Key is different"
      # recreate the primary_key
      original_primary_key = @database.loaded_schema(schema_name).table(table_name).primary_key
      updated_primary_key = @database.configured_schema(schema_name).table(table_name).primary_key
      @generator.recreate_primary_key original_primary_key, updated_primary_key
    end
  else
    log.debug "    Primary Key does not exist in either configuration or database"
  end
end