phinx icon indicating copy to clipboard operation
phinx copied to clipboard

Support for primary key

Open djordje opened this issue 14 years ago • 15 comments

Support for defining custom primary key may be useful in some cases.

Currently phinx add ìd` column as auto increment primary key. It should be possible to override this behavior, so we can create tables w/out primary key, w/out auto increment.

djordje avatar Nov 18 '12 01:11 djordje

Hi @djordje,

Phinx already has this functionality but I never took the time to document it!

You can disable the auto id column by setting id to false when accessing the table via the Table API. You can specify a custom primary key including one that spans multiple columns by using the primary_key option.

e.g:

$table = $this->table('followers', array('id' => false, 'primary_key' => array('user_id', 'follower_id')));
$table->addColumn('user_id', 'integer')
      ->addColumn('follower_id', 'integer')
      ->addColumn('created', 'datetime')
      ->save();

I'll leave this issue open until I have updated the docs to include this information.

Cheers,

Rob

robmorgan avatar Nov 19 '12 02:11 robmorgan

@robmorgan Thanks a lot!

djordje avatar Nov 20 '12 18:11 djordje

doco added. closing.

robmorgan avatar Nov 21 '12 02:11 robmorgan

Hi, this doesn't work for me or I'm misunderstanding the docs.

Let's say I want to create a new auto incrementing primary key column. From the documentation I'm given the impression I should do something like this.

$inactivosQuerify = $this->table('utili',
            array(
                'id' => 'inactivo_id',
                'primary_key' => 'inactivo_id'
            )
        );
$inactivosQuerify->addColumn('inactivo_id', 'integer')
    ->save();

I end up with the column created, but no index.

pintomau avatar Feb 11 '14 17:02 pintomau

Also what happens if the table is originally created with a custom primary key. Later I want to remove that key & add a new primary key. I can remove the old primary key with removeIndex, but it is not obvious to me if its possible to add a new primary key, or what the exact syntax is.

I looked at the code for addIndex(), to see if there is an option I can pass for the 2nd param to specify auto increment. I found the setOptions() command which defines $validOptions to 'type' & 'unique'. So I can set the type as primary, but not sure how to force it to use auto increment?

I went ahead & ran this:

->addIndex('id', ['type'=>'primary'])

Every row just shows 0. So it doesn't make it primary, nor does it make it an auto increment.

FYI can work around this by using good 'old fashioned' SQL:

public function up()
    {
        $this->execute('ALTER TABLE `images` CHANGE id id INT(20) AUTO_INCREMENT PRIMARY KEY;');
    }

joshribakoff avatar Oct 10 '14 18:10 joshribakoff

I tried this and works super-cool: $this->table('table_uknow',array('id'=>false,'primary_key'=>array('PK_1','PK_2'))); $table->addColumn('PK_1','integer',array('signed'=>FALSE,'limit'=>10)); $table->addColumn('PK_2','integer',array('signed'=>FALSE,'limit'=>10)); $table->create();

I hope that can help you

fedegara avatar Dec 08 '14 18:12 fedegara

'id'=>false,'primary_key' => 'foo' does not work as expected.

it indeed creates primary key but the AUTO_INCRMENT is lost.

        $this->table('api_token', ['id' => false, 'primary_key' => ['apt_id']])
            ->addColumn('apt_id', 'integer', ['length' => 10, 'signed' => false])

this creates:


CREATE TABLE `api_token` (
  `apt_id` int(10) unsigned NOT NULL,
...
  PRIMARY KEY (`apt_id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8

but i need it to be:


CREATE TABLE `api_token` (
  `apt_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
...
  PRIMARY KEY (`apt_id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8

glensc avatar May 02 '17 16:05 glensc

so far i've solved the problem by finding primary key and adding identity flag to it so AUTO_INCREMENT would be added to DDL.


    public function change()
    {
        $table = $this->table('api_token', ['id' => false, 'primary_key' => 'apt_id'])
            ->addColumn('apt_id', 'integer', ['length' => 10, 'signed' => false]);
        $this->getPk($table)->setIdentity(true);
        $table->create();
    }

    /**
     * Get Primary Key column from Pending Table Operations.
     * Hack for AUTO_INCREMENT being lost when defining custom Primary Key column
     *
     * @link https://github.com/robmorgan/phinx/issues/28#issuecomment-298693426
     * @param Table $table
     * @return Table\Column
     */
    protected function getPk(Table $table)
    {
        $options = $table->getOptions();
        if (!isset($options['primary_key'])) {
            throw new LogicException('primary_key column required');
        }

        $name = $options['primary_key'];
        $columns = $table->getPendingColumns();
        foreach ($columns as $column) {
            if ($column->getName() == $name) {
                return $column;
            }
        }
        throw new LogicException('primary_key column not found');
    }

glensc avatar May 02 '17 17:05 glensc

$table->getPendingColumns() is gone, yet there's still no way to define custom primary key and have auto increment on it.

i.e the problem reported in this note: https://github.com/cakephp/phinx/issues/28#issuecomment-298693426

glensc avatar Jan 02 '19 21:01 glensc

I believe, you'd want to do something like:

$this->table('api_token', ['id' => 'apt_id', 'signed' => false])->create();

As a string for the id key will cause the adapter to fall into this branch of code: https://github.com/cakephp/phinx/blob/76c96c851b737f93598d7ae7765a5cd2cc99ae7a/src/Phinx/Db/Adapter/MysqlAdapter.php#L232-L242

which should give you a custom named auto increment primary key column.

MasterOdin avatar Jan 02 '19 22:01 MasterOdin

currently i kept the previous hack, but needed to hack even more because the actions is not accessible.

https://github.com/eventum/eventum/pull/388/commits/eb121e3d8f37cd745a613782f32b663bd6354fba

i'll check your solution next.

glensc avatar Jan 02 '19 22:01 glensc

okay. it works, but result is not identical

CREATE TABLE `api_token` (
  `apt_id` int(11) unsigned NOT NULL AUTO_INCREMENT,

the int(11) is incorrect, should be int(10), but it's kind of same to mysql anyway.

NOTE: adding length has no effect:

$table = $this->table('api_token', ['id' => 'apt_id', 'length' => 10, 'signed' => false])

glensc avatar Jan 02 '19 22:01 glensc

You can only specify the signed key there. You should be able to do this I believe to get what you want:

$this->table('api_token', ['id' => false, 'primary_key' => 'apt_id'])
    ->addColumn('apt_id', 'integer', ['limit' => 10, 'signed' => false, 'identity' => true])
    ->create();

MasterOdin avatar Jan 02 '19 23:01 MasterOdin

@MasterOdin indeed. that works now as the changes are batched together. thanks!

glensc avatar Jan 03 '19 21:01 glensc

i think this can be closed. at least problem i mentioned in comments is solved.

glensc avatar Jan 03 '19 22:01 glensc