sql >> Base de Datos >  >> RDS >> Mysql

¿Forma eficiente de enumerar claves externas para una tabla MySQL?

SequelPro y Magento utilizan la consulta SHOW CREATE TABLE para cargar la información de la clave externa. Voy a hacer referencia a la implementación de Magento, ya que es un sistema basado en PHP y uno con el que ambos estamos muy familiarizados. Sin embargo, los siguientes fragmentos de código se pueden aplicar a cualquier sistema basado en PHP.

El análisis se realiza en el Varien_Db_Adapter_Pdo_Mysql::getForeignKeys() método (el código para esta clase se puede encontrar aquí ) usando un RegEx relativamente simple:


    $createSql = $this->getCreateTable($tableName, $schemaName);

    // collect CONSTRAINT
    $regExp  = '#,\s+CONSTRAINT `([^`]*)` FOREIGN KEY \(`([^`]*)`\) '
        . 'REFERENCES (`[^`]*\.)?`([^`]*)` \(`([^`]*)`\)'
        . '( ON DELETE (RESTRICT|CASCADE|SET NULL|NO ACTION))?'
        . '( ON UPDATE (RESTRICT|CASCADE|SET NULL|NO ACTION))?#';
    $matches = array();
    preg_match_all($regExp, $createSql, $matches, PREG_SET_ORDER);
    foreach ($matches as $match) {
        $ddl[strtoupper($match[1])] = array(
            'FK_NAME'           => $match[1],
            'SCHEMA_NAME'       => $schemaName,
            'TABLE_NAME'        => $tableName,
            'COLUMN_NAME'       => $match[2],
            'REF_SHEMA_NAME'    => isset($match[3]) ? $match[3] : $schemaName,
            'REF_TABLE_NAME'    => $match[4],
            'REF_COLUMN_NAME'   => $match[5],
            'ON_DELETE'         => isset($match[6]) ? $match[7] : '',
            'ON_UPDATE'         => isset($match[8]) ? $match[9] : ''
        );
    }

En el bloque de documentación, describe la matriz resultante de la siguiente manera:


    /**
     * The return value is an associative array keyed by the UPPERCASE foreign key,
     * as returned by the RDBMS.
     *
     * The value of each array element is an associative array
     * with the following keys:
     *
     * FK_NAME          => string; original foreign key name
     * SCHEMA_NAME      => string; name of database or schema
     * TABLE_NAME       => string;
     * COLUMN_NAME      => string; column name
     * REF_SCHEMA_NAME  => string; name of reference database or schema
     * REF_TABLE_NAME   => string; reference table name
     * REF_COLUMN_NAME  => string; reference column name
     * ON_DELETE        => string; action type on delete row
     * ON_UPDATE        => string; action type on update row
     */

Sé que no es exactamente lo que estaba pidiendo ya que está usando la salida SHOW CREATE TABLE, pero según mis hallazgos, parece ser la forma generalmente aceptada de hacer las cosas.