yiisoft / yiisoft/db

Upsert doesn't work when there's unique index

Open
#1,142 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
216
Forks
51
Avg merge
3d 10h
Merged PRs (30d)
2

Description

Description

I've got the bug using PostgreSQL.

Create a table

$b->createTable('page', [
    'id' => $cb::uuidPrimaryKey(),
    'title' => $cb::string()->notNull(),
    'slug' => $cb::string()->notNull()->unique(),
    'text' => $cb::text()->notNull(),
    'created_at' => $cb::dateTime(),
    'updated_at' => $cb::dateTime(),
]);

Do upsert:

$this->connection->createCommand()->upsert('{{%page}}', [
    'id' => $page->id,
    'title' => $page->title,
    'slug' => $page->getSlug(),
    'text' => $page->text,
    'created_at' => $page->createdAt,
    'updated_at' => $page->updatedAt,
])->execute();

Get the error:

QLSTATE[42P10]: Invalid column reference: 7 ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification
The SQL being executed was: INSERT INTO "page" ("id", "title", "slug", "text", "created_at", "updated_at") VALUES ('019b5c77-1c8b-72bd-a0c9-547987f9cf9c', 'Test', 'test', 'test', '2025-12-26 21:01:08', '2025-12-26 21:01:08') ON CONFLICT ("id", "slug") DO UPDATE SET "title"=EXCLUDED."title", "text"=EXCLUDED."text", "created_at"=EXCLUDED."created_at", "updated_at"=EXCLUDED."updated_at"
Package version

2.0.0

PHP version

8.2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The relevant entry point is createCommand()->upsert(); start by reproducing the PostgreSQL example with the unique slug index and inspect how the ON CONFLICT specification is generated. Done means the shown schema can be upserted successfully without the invalid constraint error, with regression coverage for this case.

Written by the indexing model from the issue text.

Assessment

Tech stack
php, postgresql
Domain
databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.