IT TIP

SQL을 사용하지 않고 Magento 설정 스크립트의 ALTER TABLE

itqueen 2021. 1. 9. 11:11
반응형

SQL을 사용하지 않고 Magento 설정 스크립트의 ALTER TABLE


Jonathon Day 라고

"업데이트는 SQL 명령 형식이어서는 안됩니다." Magento의 구성 구조를 통해 실행할 수없는 DDL 또는 DML 문을 본 적이 없습니다.

(질문 에서 구성 변경 사항을 개발에서 프로덕션 환경으로 마이그레이션 하려면 어떻게해야합니까? )

이러한 방식으로 테이블에 열 또는 인덱스를 추가 / 수정 / 제거하는 가장 좋은 방법을 알고 싶습니다. 그러나 SQL에 의존하지 않습니까? 가능할까요?

또한 SQL에서만 수행 할 수있는 다른 작업은 무엇입니까?


설정 스크립트 내에서 이러한 방법을 사용할 수 있습니다.

  • 사용 Varien_Db_Ddl_Table당신과 함께 모든 필드, 키, 관계를 구성 할 수있는 새로운 테이블을 생성하는 클래스를 $this->getConnection()->createTable($tableObject)예를 :

    /* @var $this Mage_Core_Model_Resource_Setup */
    $table = new Varien_Db_Ddl_Table();
    $table->setName($this->getTable('module/table'));
    $table->addColumn('id', Varien_Db_Ddl_Table::TYPE_INT, 10, 
                      array('unsigned' => true, 'primary' => true));
    
    $table->addColumn('name', Varien_Db_Ddl_Table::TYPE_VARCHAR, 255);
    $table->addIndex('name', 'name');
    $table->setOption('type', 'InnoDB');
    $table->setOption('charset', 'utf8');
    
    $this->getConnection()->createTable($table);
    
  • 설정 연결 ( $this->getConnection()) 방법 사용 :

    • addColumn()메소드는 기존 테이블에 새 열을 추가합니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -수정해야하는 테이블 이름
      • $columnName-추가해야하는 열의 이름
      • $definition- 컬럼의 정의 ( INT(10), DECIMAL(12,4)등)
    • addConstraint()메서드는 새로운 제약 외래 키를 만듭니다. 그런 매개 변수가 있습니다.
      • $fkName-외래 키 이름은 데이터베이스마다 고유해야하며 FK_접두사를 지정하지 않으면 자동으로 추가됩니다.
      • $tableName -외래 키를 추가하기위한 테이블 이름
      • $columnName -다른 테이블을 참조해야하는 열 이름, 복잡한 외래 키가있는 경우 쉼표를 사용하여 둘 이상의 열을 지정합니다.
      • $refTableName -처리 될 외부 테이블 이름
      • $refColumnName -외부 테이블의 열 이름
      • $onDelete-외부 테이블에서 행 제거에 대한 조치. 빈 문자열 (아무것도하지 않음) cascade,, set null. 이 필드는 선택 사항이며 지정되지 않은 경우 cascade값이 사용됩니다.
      • $onUpdate외부 테이블에서 행 키 업데이트에 대한 조치. 빈 문자열 (아무것도하지 않음) cascade,, set null. 이 필드는 선택 사항이며 지정되지 않은 경우 cascade값이 사용됩니다.
      • $purge -외래 키 추가 후 행 정리를 활성화하는 플래그 (예 : 참조되지 않은 레코드 제거)
    • addKey()메소드는 테이블에 인덱스를 추가하는 데 사용됩니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -인덱스를 추가해야하는 테이블 이름
      • $indexName -인덱스 이름
      • $fields -색인에 사용 된 열 이름
      • $indexType-인덱스 유형. 가능한 값은 다음과 같습니다 index, unique, primary, fulltext. 이 매개 변수는 선택 사항이므로 기본값은index
    • dropColumn()메서드는 기존 테이블에서 열을 제거하는 데 사용됩니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -수정해야하는 테이블 이름
      • $columnName-제거해야하는 열의 이름
    • dropForeignKey()방법은 외래 키를 제거하는 데 사용됩니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -외래 키를 제거하기위한 테이블 이름
      • $fkName -외래 키 이름
    • dropKey()메소드는 테이블 인덱스를 제거하는 데 사용됩니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -인덱스를 제거해야하는 테이블 이름
      • $keyName -인덱스 이름
    • modifyColumn메소드는 테이블의 기존 열을 수정하는 데 사용됩니다. 다음과 같은 매개 변수가 있습니다.
      • $tableName -수정해야하는 테이블 이름
      • $columnName-이름을 바꿔야하는 열의 이름
      • $definition- 컬럼의 새로운 정의 ( INT(10), DECIMAL(12,4), 등)
    • changeColumn method is used to modify and rename existing column in the table. It has such parameters:
      • $tableName - the table name that should be modified
      • $oldColumnName- the old name of the column, that should be renamed and modified
      • $newColumnName- a new name of the column
      • $definition - a new definition of the column (INT(10), DECIMAL(12,4), etc)
    • changeTableEngine method is used to change table engine, from MyISAM to InnoDB for instance. It has such parameters:
      • $tableName - the table name
      • $engine - new engine name (MEMORY, MyISAM, InnoDB, etc)

Also you can use tableColumnExists method to check existence of the column.

It is not the full list of methods that are available for you, to get rid of direct SQL queries writing. You can find more at Varien_Db_Adapter_Pdo_Mysql and Zend_Db_Adapter_Abstract classes.

Do not hesitate to look into the class definition which you are going to use, you can find a lot of interesting things for yourself :)


The idea that any Magento updates SHOULD NOT include SQL is based on the idea that

  1. Magento Objects provide abstractions on top of you database/datastore layer

  2. You should use the abstractions to update Magento, which ensures if the Magento team changes how the objects interact with the datastore, your updates will still work (assuming the core team maintains the original "contracts" implied by the Object methods)

So, the problem is an ALTER TABLE statement directly changes the datastore. If you subscribe exclusively to the above two ideas, you should never be changing the data store. (which, in the case of adding a column or an index means using EAV models exclusively, using the Setup Resources to manage changes, and accepting Magento's indexing).

A good general rule of thumb is, if you're changing or adding onto some core Magento functionality (Products, Reviews, etc.), stay away from directly changing the database structure unless you're willing to carefully manage it during upgrades.

If you're building new objects and functionality use whatever SQL you want to create and change your tables via Setup Resources. If you look at the installer/upgrade files you can see that the core Magento team does this themselves.


To alter table and add column with a foreign key, I have used this successfully using Magento CE v1.6.1.0 :

// Alter table to add column
$installer->getConnection()

        ->addColumn(
            $installer->getTable('modulekey/model'), 
            'column_name',  
            array(
                'type'      => Varien_Db_Ddl_Table::TYPE_INTEGER,
                'length'    => null,
                'unsigned'  => true,
                'nullable'  => true,
                'comment'   => 'Foreign key'
            )
        );

// Add foreign key constraint
$installer->getConnection()

        ->addForeignKey(
            $installer->getFkName( 
                'modulekey/model',  'column_name',
                'modulekey/foreign_model',  'foreign_column_name'
            ),
            $installer->getTable('modulekey/model'), 
            'column_name',
            $installer->getTable('modulekey/foreign_model'),
            'foreign_column_name',
            Varien_Db_Ddl_Table::ACTION_SET_NULL, 
            Varien_Db_Ddl_Table::ACTION_SET_NULL
        );

Those are methods from Varien_Db_Adapter_Pdo_Mysql.

ReferenceURL : https://stackoverflow.com/questions/4315660/alter-table-in-magento-setup-script-without-using-sql

반응형