2011-03-17 17 views
12

Anteriormente le pregunté cómo ALTER TABLE in Magento setup script without using SQL. Allí, Ivan dio una excelente respuesta a la que todavía me refiero incluso ahora.Agregue una columna auto_increment en la secuencia de comandos de instalación de Magento sin usar SQL

Sin embargo, todavía tengo que descubrir cómo usar Varien_Db_Ddl_Table::addColumn() para especificar una columna auto_increment. Creo que tiene algo que ver con una opción llamada identity, pero hasta ahora no ha tenido suerte.

¿Esto es posible o la funcionalidad está incompleta?

Respuesta

14

Uno puede crear una columna de incremento automático como que (por lo menos desde Magento 1.6, tal vez incluso antes):

/** @var $table Varien_Db_Ddl_Table */ 
$table->addColumn('id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
    'auto_increment' => true, 
    'unsigned' => true, 
    'nullable' => false, 
    'primary' => true, 
), 'ID'); 

En lugar de "AUTO_INCREMENT", también se puede utilizar la palabra clave "identidad".

+0

En el año transcurrido desde esta pregunta original, parece que el autoincrement se ha introducido después de todo. – clockworkgeek

+0

¿Alguna forma de decirle al incremento automático que comience en 10000? –

10

Creo que eso es algo que aún no se ha implementado.

Si mira la fuente a addColumn, puede ver que busca una opción identity/auto_increment y establece un atributo IDENTITY en la representación de la columna interna.

#File: lib/Varien/Db/Ddl/Table.php 
if (!empty($options['identity']) || !empty($options['auto_increment'])) { 
    $identity = true; 
} 

$upperName = strtoupper($name); 
$this->_columns[$upperName] = array(
    'COLUMN_NAME'  => $name, 
    'COLUMN_TYPE'  => $type, 
    'COLUMN_POSITION' => $position, 
    'DATA_TYPE'   => $type, 
    'DEFAULT'   => $default, 
    'NULLABLE'   => $nullable, 
    'LENGTH'   => $length, 
    'SCALE'    => $scale, 
    'PRECISION'   => $precision, 
    'UNSIGNED'   => $unsigned, 
    'PRIMARY'   => $primary, 
    'PRIMARY_POSITION' => $primaryPosition, 
    'IDENTITY'   => $identity 
); 

Sin embargo, si nos fijamos en el método createTable en el objeto de conexión

#File: lib/Varien/Db/Adapter/Pdo/Mysql.php 
public function createTable(Varien_Db_Ddl_Table $table) 
{ 
    $sqlFragment = array_merge(
     $this->_getColumnsDefinition($table), 
     $this->_getIndexesDefinition($table), 
     $this->_getForeignKeysDefinition($table) 
    ); 
    $tableOptions = $this->_getOptionsDefination($table); 

    $sql = sprintf("CREATE TABLE %s (\n%s\n) %s", 
     $this->quoteIdentifier($table->getName()), 
     implode(",\n", $sqlFragment), 
     implode(" ", $tableOptions)); 

    return $this->query($sql); 
} 

se puede ver _getColumnsDefinition, _getIndexesDefinition y _getForeignKeysDefinition se utiliza para crear un fragmento CREATE SQL. Ninguno de estos métodos hace referencia a identity o auto_increment, ni parece generar ningún SQL que cree un incremento automático.

Los únicos candidatos posibles en esta clase son

/** 
* Autoincrement for bind value 
* 
* @var int 
*/ 
protected $_bindIncrement  = 0; 

que se utiliza para controlar el número de incrementos de un parámetro ligado DOP (nada que ver con auto_increment).

También hay una mención de auto_increment aquí

protected function _getOptionsDefination(Varien_Db_Ddl_Table $table) 
{ 
    $definition = array(); 
    $tableProps = array(
     'type'    => 'ENGINE=%s', 
     'checksum'   => 'CHECKSUM=%d', 
     'auto_increment' => 'AUTO_INCREMENT=%d', 
     'avg_row_length' => 'AVG_ROW_LENGTH=%d', 
     'comment'   => 'COMMENT=\'%s\'', 
     'max_rows'   => 'MAX_ROWS=%d', 
     'min_rows'   => 'MIN_ROWS=%d', 
     'delay_key_write' => 'DELAY_KEY_WRITE=%d', 
     'row_format'  => 'row_format=%s', 
     'charset'   => 'charset=%s', 
     'collate'   => 'COLLATE=%s' 
    ); 
    foreach ($tableProps as $key => $mask) { 
     $v = $table->getOption($key); 
     if (!is_null($v)) { 
      $definition[] = sprintf($mask, $v); 
     } 
    } 

    return $definition; 
} 

pero esto se utiliza para procesar las opciones establecidas en la mesa. Este auto_increment controla las opciones de tabla AUTO_INCREMENT, que se pueden usar para controlar a partir del cual comienza un número AUTO_INCREMENT.

Cuestiones relacionadas