Skip to content

How I can use mariadb’s `ON DUPLICATE KEY UPDATE` ability in magento upon mass insert of data?

Upon magento I am placing some values into the mariadb database via reading the csv:


use PcmagasEmailsModelEmailFactory;
use PcmagasEmailsModelEmail;

use MagentoFrameworkFileCsv ;

class MyController extends MagentoBackendAppAction
{

  // This is populated via constructor
  private Csv $csv;
  private EmailFactory $factory;

    public function __construct(
        MagentoBackendAppActionContext $context,
        EmailFactory $factory,
        Csv $csv
    ) {
        $this->csv=$csv;
        $this->factory = $factory;
        parent::__construct($context);
    }

  public function execute()
  {
     // Rest of code here

     $file = $this->getRequest()->getFiles("upload_csv");
     $csvData = $this->csv->getData($file['tmp_name']);

     foreach ( $csvData as $emails ) {
         $model = $this->factory->create();
         $model->setEmail($emails[0]);
         $model->setCustomerGroupId($emails[1]);
         $dataToSave[]=$model->getData();
     }

     $resource = $model->getResource();
     $connection = $resource->getConnection();
     $table = $resource->getMainTable();
     $connection->insertOnDuplicate($table,$dataToSave);
     // return value bello ommitted for simplicity in current question
  }

}

What I want is to perform a mass insert from csv using the mariadb’s ON DUPLICATE KEY UPDATE approach (I assume I have better performance):

insert into mytable(email,list_id) values ('user@lalala',1) ON DUPLICATE KEY UPDATE list_id=1

In my db_schema.xml I have the following:

<?xml version="1.0" ?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="mytable" resource="default" engine="innodb" comment="mytable">
        <column name="email" nullable="false" xsi:type="varchar" comment="Email" length="255"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="email"/>
        </constraint>
        <column xsi:type="int" name="list_id" padding="10" unsigned="true" nullable="false" identity="false" default="0" comment="Group id to assign" />
    </table>
</schema>

As you can see the email is primary key. Is there an approach somehow to massively insert models and use mariadb’s ability to update on duplicate?