Repository: codeigniter4/CodeIgniter4 (PHP)

Issue:
Bug: Issue with Composite Primary Keys in _upsertBatch for PostgreSQL – Only the First Index Field Is Considered
### PHP Version

8.4

### CodeIgniter4 Version

4.6.0

### CodeIgniter4 Installation Method

Composer (using `codeigniter4/appstarter`)

### Which operating systems have you tested for this bug?

macOS

### Which server did you use?

apache

### Database

PostgreSQL 17.2

### What happened?

Hello,

I'm reporting a potential bug in CodeIgniter 4 related to the _upsertBatch function when used with PostgreSQL. It appears that the function only considers the first field of an index for conflict resolution, which causes issues when dealing with composite primary keys or tables with multiple unique indexes.

### **Details:**
In the _upsertBatch function, the following code snippet suggests that only one index (and, in practice, only the first field of that index) is used:

```
foreach (array_map(static fn($index) => $index->fields, $allIndexes) as $index) {
    $constraints[] = current($index);
    // only one index can be used?
    break;
}
```
Because of this, if a table has a composite primary key (or multiple unique constraints), the generated SQL will include only the first field from the index in the ON CONFLICT clause. This behavior may lead to unexpected failures or incorrect updates during upsert operations.

### Steps to Reproduce

Create a PostgreSQL table with a composite primary key or with multiple unique indexes.
Use the upsertBatch method to insert/update data in this table.
Observe that the conflict resolution logic only uses the first field of the composite key, which can lead to errors or improper upsert behavior.

### Expected Output

All relevant fields of the composite key (or the chosen unique index) should be used in the ON CONFLICT clause to correctly identify conflicts and perform the update action.

### Anything else?

This issue might be related to the comment // only one index can be used? present in the code. It suggests that the current implementation might be a temporary workaround or an oversight that did not fully account for composite keys.


Discussion:

Patch:
diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php
index 27a72b58c333..8d0d569d5e28 100644
--- a/system/Database/Postgre/Builder.php
+++ b/system/Database/Postgre/Builder.php
@@ -469,9 +469,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
                     return ($index->type === 'UNIQUE' || $index->type === 'PRIMARY') && $hasAllFields;
                 });
 
-                foreach (array_map(static fn ($index) => $index->fields, $allIndexes) as $index) {
-                    $constraints[] = current($index);
-                    // only one index can be used?
+                foreach ($allIndexes as $index) {
+                    $constraints = $index->fields;
                     break;
                 }
 
diff --git a/system/Database/SQLite3/Builder.php b/system/Database/SQLite3/Builder.php
index 6e62907ac1aa..3aa13edeb96a 100644
--- a/system/Database/SQLite3/Builder.php
+++ b/system/Database/SQLite3/Builder.php
@@ -151,8 +151,8 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
                     return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields;
                 });
 
-                foreach (array_map(static fn ($index) => $index->fields, $allIndexes) as $index) {
-                    $constraints[] = current($index);
+                foreach ($allIndexes as $index) {
+                    $constraints = $index->fields;
                     break;
                 }
 
diff --git a/user_guide_src/source/changelogs/v4.6.1.rst b/user_guide_src/source/changelogs/v4.6.1.rst
index 9a3ccfe76490..9a5ea391d4f3 100644
--- a/user_guide_src/source/changelogs/v4.6.1.rst
+++ b/user_guide_src/source/changelogs/v4.6.1.rst
@@ -32,6 +32,7 @@ Bugs Fixed
 
 - **CURLRequest:** Fixed an issue where multiple header sections appeared in the CURL response body during multiple redirects from the target server.
 - **Cors:** Fixed a bug in the Cors filter that caused the appropriate headers to not be added when another filter returned a response object in the ``before`` filter.
+- **Database:** Fixed a bug in ``Postgre`` and ``SQLite3`` handlers where composite unique keys were not fully taken into account for ``upsert`` type of queries.
 
 See the repo's
 `CHANGELOG.md <https://github.com/codeigniter4/CodeIgniter4/blob/develop/CHANGELOG.md>`_
diff --git a/user_guide_src/source/database/query_builder.rst b/user_guide_src/source/database/query_builder.rst
index 6e4b1359c898..31515768d530 100644
--- a/user_guide_src/source/database/query_builder.rst
+++ b/user_guide_src/source/database/query_builder.rst
@@ -937,6 +937,10 @@ constraint by default. Here is an example using an array:
 
 .. literalinclude:: query_builder/112.php
 
+.. note:: For databases other than MySQL, if a table has multiple keys (primary or unique),
+    the primary key will be prioritized by default when handling constraints. If you prefer
+    to use a different unique key instead of the primary key, use the ``onConstraint()`` method.
+
 The first parameter is an associative array of values.
 
 Here is an example using an object:


Test patch:
diff --git a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php
index 8a7cb5b7d11c..6af55fa7c9c9 100644
--- a/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php
+++ b/tests/_support/Database/Migrations/20160428212500_Create_test_tables.php
@@ -47,6 +47,15 @@ public function up(): void
             'value' => ['type' => 'VARCHAR', 'constraint' => 400, 'null' => true],
         ])->addKey('id', true)->createTable('misc', true);
 
+        // Team members Table (composite key)
+        $this->forge->addField([
+            'team_id'    => ['type' => 'INTEGER', 'constraint' => 3],
+            'person_id'  => ['type' => 'INTEGER', 'constraint' => 3],
+            'role'       => ['type' => 'VARCHAR', 'constraint' => 40],
+            'status'     => ['type' => 'VARCHAR', 'constraint' => 40],
+            'created_at' => ['type' => 'DATETIME', 'null' => true],
+        ])->addUniqueKey(['team_id', 'person_id'])->createTable('team_members', true);
+
         // Database Type test table
         // missing types:
         //   TINYINT,MEDIUMINT,BIT,YEAR,BINARY,VARBINARY,TINYTEXT,LONGTEXT,
diff --git a/tests/_support/Database/Seeds/CITestSeeder.php b/tests/_support/Database/Seeds/CITestSeeder.php
index 9ce0bce4f1c3..09dba65f155b 100644
--- a/tests/_support/Database/Seeds/CITestSeeder.php
+++ b/tests/_support/Database/Seeds/CITestSeeder.php
@@ -107,6 +107,20 @@ public function run(): void
                     'value' => 'ടൈപ്പ്',
                 ],
             ],
+            'team_members' => [
+                [
+                    'team_id'   => 1,
+                    'person_id' => 22,
+                    'role'      => 'member',
+                    'status'    => 'active',
+                ],
+                [
+                    'team_id'   => 1,
+                    'person_id' => 33,
+                    'role'      => 'mentor',
+                    'status'    => 'active',
+                ],
+            ],
             'type_test' => [
                 [
                     'type_varchar'    => 'test',
diff --git a/tests/system/Database/Live/MetadataTest.php b/tests/system/Database/Live/MetadataTest.php
index 0488dd2f4a51..643d0689fdad 100644
--- a/tests/system/Database/Live/MetadataTest.php
+++ b/tests/system/Database/Live/MetadataTest.php
@@ -47,6 +47,7 @@ protected function setUp(): void
             $prefix . 'user',
             $prefix . 'job',
             $prefix . 'misc',
+            $prefix . 'team_members',
             $prefix . 'type_test',
             $prefix . 'empty',
             $prefix . 'secondary',
diff --git a/tests/system/Database/Live/UpsertTest.php b/tests/system/Database/Live/UpsertTest.php
index a702ff5e1b8d..000fa6fec7cb 100644
--- a/tests/system/Database/Live/UpsertTest.php
+++ b/tests/system/Database/Live/UpsertTest.php
@@ -448,7 +448,7 @@ public function testUpsertBatchWithOnConflictAndUpdateFields(): void
         $this->assertSame('El Salvador', $data[4]->country);
     }
 
-    public function testUpsertWithMatchingDataOnUniqueIndexandPrimaryKey(): void
+    public function testUpsertWithMatchingDataOnUniqueIndexAndPrimaryKey(): void
     {
         $data = [
             'id'      => 6,
@@ -607,6 +607,36 @@ public function testUpsertBatchMultipleConstraints(): void
         }
     }
 
+    /**
+     * @see https://github.com/codeigniter4/CodeIgniter4/issues/9450
+     */
+    public function testUpsertBatchCompositeUniqueIndex(): void
+    {
+        $data = [
+            [
+                'team_id'   => 1,
+                'person_id' => 22,
+                'role'      => 'leader',
+                'status'    => 'active',
+            ],
+            [
+                'team_id'   => 1,
+                'person_id' => 33,
+                'role'      => 'member',
+                'status'    => 'active',
+            ],
+        ];
+
+        // uses (team_id, person_id) - composite unique index
+        $this->db->table('team_members')->upsertBatch($data);
+
+        $this->seeInDatabase('team_members', ['team_id' => 1, 'person_id' => 22, 'role' => 'leader']);
+        $this->dontSeeInDatabase('team_members', ['team_id' => 1, 'person_id' => 22, 'role' => 'member']);
+
+        $this->seeInDatabase('team_members', ['team_id' => 1, 'person_id' => 33, 'role' => 'member']);
+        $this->dontSeeInDatabase('team_members', ['team_id' => 1, 'person_id' => 33, 'role' => 'mentor']);
+    }
+
     public function testSetBatchOneRow(): void
     {
         $data = [