Skip to content

Commit fba7f06

Browse files
committed
feat: use rows value to delete inserted row if primary key is filled
1 parent b65b3ee commit fba7f06

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

src/Codeception/Module/Db.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -801,8 +801,13 @@ private function addInsertedRow(string $table, array $row, $id): void
801801
$primaryKey = $this->_getDriver()->getPrimaryKey($table);
802802
$primary = [];
803803
if ($primaryKey !== []) {
804-
if ($id && count($primaryKey) === 1) {
805-
$primary [$primaryKey[0]] = $id;
804+
$filledKeys = array_intersect($primaryKey, array_keys($row));
805+
$primaryKeyIsFilled = count($filledKeys) === count($primaryKey);
806+
807+
if ($primaryKeyIsFilled) {
808+
$primary = array_intersect_key($row, array_flip($primaryKey));
809+
} elseif ($id && count($primaryKey) === 1) {
810+
$primary[$primaryKey[0]] = $id;
806811
} else {
807812
foreach ($primaryKey as $column) {
808813
if (isset($row[$column])) {

tests/data/dumps/mysql.sql

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,18 @@ CREATE TABLE `no_pk` (
9494
`status` varchar(255) NOT NULL
9595
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
9696

97+
CREATE TABLE `auto_increment_not_on_pk` (
98+
`id` int(11) NOT NULL,
99+
`counter` int(11) NOT NULL,
100+
PRIMARY KEY (`id`)
101+
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
102+
103+
CREATE INDEX counter ON `auto_increment_not_on_pk` (counter);
104+
ALTER TABLE `auto_increment_not_on_pk`
105+
MODIFY counter int AUTO_INCREMENT;
106+
97107
CREATE TABLE `empty_table` (
98108
`id` int(11) NOT NULL AUTO_INCREMENT,
99109
`field` varchar(255),
100110
PRIMARY KEY(`id`)
101-
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
111+
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

tests/unit/Codeception/Module/Db/MySqlDbTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,4 +101,16 @@ public function testGrabColumnFromDatabase()
101101
],
102102
$emails);
103103
}
104+
105+
public function testHaveInDatabaseAutoIncrementOnANonPrimaryKey()
106+
{
107+
$testData = [
108+
'id' => 777,
109+
];
110+
$this->module->haveInDatabase('auto_increment_not_on_pk', $testData);
111+
$this->module->seeInDatabase('auto_increment_not_on_pk', $testData);
112+
$this->module->_after(Stub::makeEmpty(TestInterface::class));
113+
114+
$this->module->dontSeeInDatabase('auto_increment_not_on_pk', $testData);
115+
}
104116
}

0 commit comments

Comments
 (0)