codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.38k stars 1.9k forks source link

Bug: insertBatch throws a non catchable mysqli_sql_exception #9213

Open mentorduncan opened 1 month ago

mentorduncan commented 1 month ago

PHP Version

8.3

CodeIgniter4 Version

4.5.5

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

Windows

Which server did you use?

apache

Database

MariaDB 11.4.2

What happened?

ERROR - 2024-10-02 16:17:07 --> mysqli_sql_exception: Duplicate entry '620-43' for key 'fk_UNIQUE'

Steps to Reproduce

Create a pivot table, where the combination of the two fk columns is unique.

Feed it with some combinations of fks And do an insertBatch where there is a collision.

Despite logging the error above, the script will run until the end. And it was not possible to capture the error even with: catch (DatabaseException $e) catch (\mysqli_sql_exception $e) or catch (\Exception $e)

Expected Output

a more user-friendly or catchable error for me to deal with.

Anything else?

No response

ping-yee commented 1 day ago

Cannot reproduce this error.

My steps to reproduce:

CREATE TABLE pivot_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    foreign_key_1 INT NOT NULL,
    foreign_key_2 INT NOT NULL,
    UNIQUE KEY fk_UNIQUE (foreign_key_1, foreign_key_2)
);
<?php

namespace App\Controllers;

class Home extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('pivot_table');

        $data = [
            ['foreign_key_1' => 5, 'foreign_key_2' => 6],
            ['foreign_key_1' => 5, 'foreign_key_2' => 6],
        ];

        $builder->insertBatch($data);
        echo "Data inserted successfully.";
    }
}

And it'll throw the DatabaseException.

image