<?php

/**
 * @var $g_comp_database isys_component_database
 */
global $g_comp_database, $g_absdir, $g_mandator_info, $g_comp_database_system;

// Set migrationId
$migrationIdentifier = "connector-constraints";

// Check whether migration was executed before
if ($this->is_migration_done($migrationIdentifier)) {
    $g_migration_log[] = '<span class="bold">Migration of connector constraints has already been done.</span>';
} else {
    $g_migration_log[] = '<span class="bold">Starting Migration of connector constraints.</span>';
    $migration = new isys_update_migration();

    $foreingKeys = $migration->get_foreign_key('isys_catg_connector_list');

    if (!$foreingKeys) {
        $g_migration_log[] = '<span class="bold">Migration finished!</span>';

        $this->migration_done($migrationIdentifier);
        return;
    }

    $connectorTypeFk = $foreingKeys['isys_catg_connector_list__isys_connection_type__id'];

    if (!$connectorTypeFk || $connectorTypeFk[5]['DELETE'] === 'SET NULL') {
        $g_migration_log[] = '<span class="bold">Migration finished!</span>';

        $this->migration_done($migrationIdentifier);
        return;
    }

    $foreignKeyField = $connectorTypeFk[2];
    $migration->delete_foreign_key('isys_catg_connector_list', $foreignKeyField);
    $migration->add_foreign_key(
        'isys_catg_connector_list',
        'isys_catg_connector_list__isys_connection_type__id',
        'isys_connection_type',
        'isys_connection_type__id',
        'SET NULL',
        'CASCADE'
    );

    $g_migration_log[] = '<span class="bold">Migration finished!</span>';

    $this->migration_done($migrationIdentifier);
}
