vendor/doctrine/orm/src/Persisters/Entity/BasicEntityPersister.php line 259

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\ORM\Persisters\Entity;
  4. use BackedEnum;
  5. use Doctrine\Common\Collections\Criteria;
  6. use Doctrine\Common\Collections\Expr\Comparison;
  7. use Doctrine\DBAL\Connection;
  8. use Doctrine\DBAL\LockMode;
  9. use Doctrine\DBAL\Platforms\AbstractPlatform;
  10. use Doctrine\DBAL\Result;
  11. use Doctrine\DBAL\Types\Type;
  12. use Doctrine\DBAL\Types\Types;
  13. use Doctrine\Deprecations\Deprecation;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Doctrine\ORM\Mapping\ClassMetadata;
  16. use Doctrine\ORM\Mapping\MappingException;
  17. use Doctrine\ORM\Mapping\QuoteStrategy;
  18. use Doctrine\ORM\OptimisticLockException;
  19. use Doctrine\ORM\PersistentCollection;
  20. use Doctrine\ORM\Persisters\Exception\CantUseInOperatorOnCompositeKeys;
  21. use Doctrine\ORM\Persisters\Exception\InvalidOrientation;
  22. use Doctrine\ORM\Persisters\Exception\UnrecognizedField;
  23. use Doctrine\ORM\Persisters\SqlExpressionVisitor;
  24. use Doctrine\ORM\Persisters\SqlValueVisitor;
  25. use Doctrine\ORM\Proxy\DefaultProxyClassNameResolver;
  26. use Doctrine\ORM\Query;
  27. use Doctrine\ORM\Query\QueryException;
  28. use Doctrine\ORM\Repository\Exception\InvalidFindByCall;
  29. use Doctrine\ORM\UnitOfWork;
  30. use Doctrine\ORM\Utility\IdentifierFlattener;
  31. use Doctrine\ORM\Utility\LockSqlHelper;
  32. use Doctrine\ORM\Utility\PersisterHelper;
  33. use LengthException;
  34. use function array_combine;
  35. use function array_keys;
  36. use function array_map;
  37. use function array_merge;
  38. use function array_search;
  39. use function array_unique;
  40. use function array_values;
  41. use function assert;
  42. use function count;
  43. use function implode;
  44. use function is_array;
  45. use function is_object;
  46. use function reset;
  47. use function spl_object_id;
  48. use function sprintf;
  49. use function str_contains;
  50. use function strtoupper;
  51. use function trim;
  52. /**
  53.  * A BasicEntityPersister maps an entity to a single table in a relational database.
  54.  *
  55.  * A persister is always responsible for a single entity type.
  56.  *
  57.  * EntityPersisters are used during a UnitOfWork to apply any changes to the persistent
  58.  * state of entities onto a relational database when the UnitOfWork is committed,
  59.  * as well as for basic querying of entities and their associations (not DQL).
  60.  *
  61.  * The persisting operations that are invoked during a commit of a UnitOfWork to
  62.  * persist the persistent entity state are:
  63.  *
  64.  *   - {@link addInsert} : To schedule an entity for insertion.
  65.  *   - {@link executeInserts} : To execute all scheduled insertions.
  66.  *   - {@link update} : To update the persistent state of an entity.
  67.  *   - {@link delete} : To delete the persistent state of an entity.
  68.  *
  69.  * As can be seen from the above list, insertions are batched and executed all at once
  70.  * for increased efficiency.
  71.  *
  72.  * The querying operations invoked during a UnitOfWork, either through direct find
  73.  * requests or lazy-loading, are the following:
  74.  *
  75.  *   - {@link load} : Loads (the state of) a single, managed entity.
  76.  *   - {@link loadAll} : Loads multiple, managed entities.
  77.  *   - {@link loadOneToOneEntity} : Loads a one/many-to-one entity association (lazy-loading).
  78.  *   - {@link loadOneToManyCollection} : Loads a one-to-many entity association (lazy-loading).
  79.  *   - {@link loadManyToManyCollection} : Loads a many-to-many entity association (lazy-loading).
  80.  *
  81.  * The BasicEntityPersister implementation provides the default behavior for
  82.  * persisting and querying entities that are mapped to a single database table.
  83.  *
  84.  * Subclasses can be created to provide custom persisting and querying strategies,
  85.  * i.e. spanning multiple tables.
  86.  *
  87.  * @psalm-import-type AssociationMapping from ClassMetadata
  88.  */
  89. class BasicEntityPersister implements EntityPersister
  90. {
  91.     use LockSqlHelper;
  92.     /** @var array<string,string> */
  93.     private static $comparisonMap = [
  94.         Comparison::EQ          => '= %s',
  95.         Comparison::NEQ         => '!= %s',
  96.         Comparison::GT          => '> %s',
  97.         Comparison::GTE         => '>= %s',
  98.         Comparison::LT          => '< %s',
  99.         Comparison::LTE         => '<= %s',
  100.         Comparison::IN          => 'IN (%s)',
  101.         Comparison::NIN         => 'NOT IN (%s)',
  102.         Comparison::CONTAINS    => 'LIKE %s',
  103.         Comparison::STARTS_WITH => 'LIKE %s',
  104.         Comparison::ENDS_WITH   => 'LIKE %s',
  105.     ];
  106.     /**
  107.      * Metadata object that describes the mapping of the mapped entity class.
  108.      *
  109.      * @var ClassMetadata
  110.      */
  111.     protected $class;
  112.     /**
  113.      * The underlying DBAL Connection of the used EntityManager.
  114.      *
  115.      * @var Connection $conn
  116.      */
  117.     protected $conn;
  118.     /**
  119.      * The database platform.
  120.      *
  121.      * @var AbstractPlatform
  122.      */
  123.     protected $platform;
  124.     /**
  125.      * The EntityManager instance.
  126.      *
  127.      * @var EntityManagerInterface
  128.      */
  129.     protected $em;
  130.     /**
  131.      * Queued inserts.
  132.      *
  133.      * @psalm-var array<int, object>
  134.      */
  135.     protected $queuedInserts = [];
  136.     /**
  137.      * The map of column names to DBAL mapping types of all prepared columns used
  138.      * when INSERTing or UPDATEing an entity.
  139.      *
  140.      * @see prepareInsertData($entity)
  141.      * @see prepareUpdateData($entity)
  142.      *
  143.      * @var mixed[]
  144.      */
  145.     protected $columnTypes = [];
  146.     /**
  147.      * The map of quoted column names.
  148.      *
  149.      * @see prepareInsertData($entity)
  150.      * @see prepareUpdateData($entity)
  151.      *
  152.      * @var mixed[]
  153.      */
  154.     protected $quotedColumns = [];
  155.     /**
  156.      * The INSERT SQL statement used for entities handled by this persister.
  157.      * This SQL is only generated once per request, if at all.
  158.      *
  159.      * @var string|null
  160.      */
  161.     private $insertSql;
  162.     /**
  163.      * The quote strategy.
  164.      *
  165.      * @var QuoteStrategy
  166.      */
  167.     protected $quoteStrategy;
  168.     /**
  169.      * The IdentifierFlattener used for manipulating identifiers
  170.      *
  171.      * @var IdentifierFlattener
  172.      */
  173.     protected $identifierFlattener;
  174.     /** @var CachedPersisterContext */
  175.     protected $currentPersisterContext;
  176.     /** @var CachedPersisterContext */
  177.     private $limitsHandlingContext;
  178.     /** @var CachedPersisterContext */
  179.     private $noLimitsContext;
  180.     /**
  181.      * Initializes a new <tt>BasicEntityPersister</tt> that uses the given EntityManager
  182.      * and persists instances of the class described by the given ClassMetadata descriptor.
  183.      */
  184.     public function __construct(EntityManagerInterface $emClassMetadata $class)
  185.     {
  186.         $this->em                    $em;
  187.         $this->class                 $class;
  188.         $this->conn                  $em->getConnection();
  189.         $this->platform              $this->conn->getDatabasePlatform();
  190.         $this->quoteStrategy         $em->getConfiguration()->getQuoteStrategy();
  191.         $this->identifierFlattener   = new IdentifierFlattener($em->getUnitOfWork(), $em->getMetadataFactory());
  192.         $this->noLimitsContext       $this->currentPersisterContext = new CachedPersisterContext(
  193.             $class,
  194.             new Query\ResultSetMapping(),
  195.             false
  196.         );
  197.         $this->limitsHandlingContext = new CachedPersisterContext(
  198.             $class,
  199.             new Query\ResultSetMapping(),
  200.             true
  201.         );
  202.     }
  203.     /**
  204.      * {@inheritDoc}
  205.      */
  206.     public function getClassMetadata()
  207.     {
  208.         return $this->class;
  209.     }
  210.     /**
  211.      * {@inheritDoc}
  212.      */
  213.     public function getResultSetMapping()
  214.     {
  215.         return $this->currentPersisterContext->rsm;
  216.     }
  217.     /**
  218.      * {@inheritDoc}
  219.      */
  220.     public function addInsert($entity)
  221.     {
  222.         $this->queuedInserts[spl_object_id($entity)] = $entity;
  223.     }
  224.     /**
  225.      * {@inheritDoc}
  226.      */
  227.     public function getInserts()
  228.     {
  229.         return $this->queuedInserts;
  230.     }
  231.     /**
  232.      * {@inheritDoc}
  233.      */
  234.     public function executeInserts()
  235.     {
  236.         if (! $this->queuedInserts) {
  237.             return;
  238.         }
  239.         $uow            $this->em->getUnitOfWork();
  240.         $idGenerator    $this->class->idGenerator;
  241.         $isPostInsertId $idGenerator->isPostInsertGenerator();
  242.         $stmt      $this->conn->prepare($this->getInsertSQL());
  243.         $tableName $this->class->getTableName();
  244.         foreach ($this->queuedInserts as $key => $entity) {
  245.             $insertData $this->prepareInsertData($entity);
  246.             if (isset($insertData[$tableName])) {
  247.                 $paramIndex 1;
  248.                 foreach ($insertData[$tableName] as $column => $value) {
  249.                     $stmt->bindValue($paramIndex++, $value$this->columnTypes[$column]);
  250.                 }
  251.             }
  252.             $stmt->executeStatement();
  253.             if ($isPostInsertId) {
  254.                 $generatedId $idGenerator->generateId($this->em$entity);
  255.                 $id          = [$this->class->identifier[0] => $generatedId];
  256.                 $uow->assignPostInsertId($entity$generatedId);
  257.             } else {
  258.                 $id $this->class->getIdentifierValues($entity);
  259.             }
  260.             if ($this->class->requiresFetchAfterChange) {
  261.                 $this->assignDefaultVersionAndUpsertableValues($entity$id);
  262.             }
  263.             // Unset this queued insert, so that the prepareUpdateData() method knows right away
  264.             // (for the next entity already) that the current entity has been written to the database
  265.             // and no extra updates need to be scheduled to refer to it.
  266.             //
  267.             // In \Doctrine\ORM\UnitOfWork::executeInserts(), the UoW already removed entities
  268.             // from its own list (\Doctrine\ORM\UnitOfWork::$entityInsertions) right after they
  269.             // were given to our addInsert() method.
  270.             unset($this->queuedInserts[$key]);
  271.         }
  272.     }
  273.     /**
  274.      * Retrieves the default version value which was created
  275.      * by the preceding INSERT statement and assigns it back in to the
  276.      * entities version field if the given entity is versioned.
  277.      * Also retrieves values of columns marked as 'non insertable' and / or
  278.      * 'not updatable' and assigns them back to the entities corresponding fields.
  279.      *
  280.      * @param object  $entity
  281.      * @param mixed[] $id
  282.      *
  283.      * @return void
  284.      */
  285.     protected function assignDefaultVersionAndUpsertableValues($entity, array $id)
  286.     {
  287.         $values $this->fetchVersionAndNotUpsertableValues($this->class$id);
  288.         foreach ($values as $field => $value) {
  289.             $value Type::getType($this->class->fieldMappings[$field]['type'])->convertToPHPValue($value$this->platform);
  290.             $this->class->setFieldValue($entity$field$value);
  291.         }
  292.     }
  293.     /**
  294.      * Fetches the current version value of a versioned entity and / or the values of fields
  295.      * marked as 'not insertable' and / or 'not updatable'.
  296.      *
  297.      * @param ClassMetadata $versionedClass
  298.      * @param mixed[]       $id
  299.      *
  300.      * @return mixed
  301.      */
  302.     protected function fetchVersionAndNotUpsertableValues($versionedClass, array $id)
  303.     {
  304.         $columnNames = [];
  305.         foreach ($this->class->fieldMappings as $key => $column) {
  306.             if (isset($column['generated']) || ($this->class->isVersioned && $key === $versionedClass->versionField)) {
  307.                 $columnNames[$key] = $this->quoteStrategy->getColumnName($key$versionedClass$this->platform);
  308.             }
  309.         }
  310.         $tableName  $this->quoteStrategy->getTableName($versionedClass$this->platform);
  311.         $identifier $this->quoteStrategy->getIdentifierColumnNames($versionedClass$this->platform);
  312.         // FIXME: Order with composite keys might not be correct
  313.         $sql 'SELECT ' implode(', '$columnNames)
  314.             . ' FROM ' $tableName
  315.             ' WHERE ' implode(' = ? AND '$identifier) . ' = ?';
  316.         $flatId $this->identifierFlattener->flattenIdentifier($versionedClass$id);
  317.         $values $this->conn->fetchNumeric(
  318.             $sql,
  319.             array_values($flatId),
  320.             $this->extractIdentifierTypes($id$versionedClass)
  321.         );
  322.         if ($values === false) {
  323.             throw new LengthException('Unexpected empty result for database query.');
  324.         }
  325.         $values array_combine(array_keys($columnNames), $values);
  326.         if (! $values) {
  327.             throw new LengthException('Unexpected number of database columns.');
  328.         }
  329.         return $values;
  330.     }
  331.     /**
  332.      * @param mixed[] $id
  333.      *
  334.      * @return int[]|null[]|string[]
  335.      * @psalm-return list<int|string|null>
  336.      */
  337.     final protected function extractIdentifierTypes(array $idClassMetadata $versionedClass): array
  338.     {
  339.         $types = [];
  340.         foreach ($id as $field => $value) {
  341.             $types array_merge($types$this->getTypes($field$value$versionedClass));
  342.         }
  343.         return $types;
  344.     }
  345.     /**
  346.      * {@inheritDoc}
  347.      */
  348.     public function update($entity)
  349.     {
  350.         $tableName  $this->class->getTableName();
  351.         $updateData $this->prepareUpdateData($entity);
  352.         if (! isset($updateData[$tableName])) {
  353.             return;
  354.         }
  355.         $data $updateData[$tableName];
  356.         if (! $data) {
  357.             return;
  358.         }
  359.         $isVersioned     $this->class->isVersioned;
  360.         $quotedTableName $this->quoteStrategy->getTableName($this->class$this->platform);
  361.         $this->updateTable($entity$quotedTableName$data$isVersioned);
  362.         if ($this->class->requiresFetchAfterChange) {
  363.             $id $this->class->getIdentifierValues($entity);
  364.             $this->assignDefaultVersionAndUpsertableValues($entity$id);
  365.         }
  366.     }
  367.     /**
  368.      * Performs an UPDATE statement for an entity on a specific table.
  369.      * The UPDATE can optionally be versioned, which requires the entity to have a version field.
  370.      *
  371.      * @param object  $entity          The entity object being updated.
  372.      * @param string  $quotedTableName The quoted name of the table to apply the UPDATE on.
  373.      * @param mixed[] $updateData      The map of columns to update (column => value).
  374.      * @param bool    $versioned       Whether the UPDATE should be versioned.
  375.      *
  376.      * @throws UnrecognizedField
  377.      * @throws OptimisticLockException
  378.      */
  379.     final protected function updateTable(
  380.         $entity,
  381.         $quotedTableName,
  382.         array $updateData,
  383.         $versioned false
  384.     ): void {
  385.         $set    = [];
  386.         $types  = [];
  387.         $params = [];
  388.         foreach ($updateData as $columnName => $value) {
  389.             $placeholder '?';
  390.             $column      $columnName;
  391.             switch (true) {
  392.                 case isset($this->class->fieldNames[$columnName]):
  393.                     $fieldName $this->class->fieldNames[$columnName];
  394.                     $column    $this->quoteStrategy->getColumnName($fieldName$this->class$this->platform);
  395.                     if (isset($this->class->fieldMappings[$fieldName]['requireSQLConversion'])) {
  396.                         $type        Type::getType($this->columnTypes[$columnName]);
  397.                         $placeholder $type->convertToDatabaseValueSQL('?'$this->platform);
  398.                     }
  399.                     break;
  400.                 case isset($this->quotedColumns[$columnName]):
  401.                     $column $this->quotedColumns[$columnName];
  402.                     break;
  403.             }
  404.             $params[] = $value;
  405.             $set[]    = $column ' = ' $placeholder;
  406.             $types[]  = $this->columnTypes[$columnName];
  407.         }
  408.         $where      = [];
  409.         $identifier $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  410.         foreach ($this->class->identifier as $idField) {
  411.             if (! isset($this->class->associationMappings[$idField])) {
  412.                 $params[] = $identifier[$idField];
  413.                 $types[]  = $this->class->fieldMappings[$idField]['type'];
  414.                 $where[]  = $this->quoteStrategy->getColumnName($idField$this->class$this->platform);
  415.                 continue;
  416.             }
  417.             $params[] = $identifier[$idField];
  418.             $where[]  = $this->quoteStrategy->getJoinColumnName(
  419.                 $this->class->associationMappings[$idField]['joinColumns'][0],
  420.                 $this->class,
  421.                 $this->platform
  422.             );
  423.             $targetMapping $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']);
  424.             $targetType    PersisterHelper::getTypeOfField($targetMapping->identifier[0], $targetMapping$this->em);
  425.             if ($targetType === []) {
  426.                 throw UnrecognizedField::byFullyQualifiedName($this->class->name$targetMapping->identifier[0]);
  427.             }
  428.             $types[] = reset($targetType);
  429.         }
  430.         if ($versioned) {
  431.             $versionField $this->class->versionField;
  432.             assert($versionField !== null);
  433.             $versionFieldType $this->class->fieldMappings[$versionField]['type'];
  434.             $versionColumn    $this->quoteStrategy->getColumnName($versionField$this->class$this->platform);
  435.             $where[]  = $versionColumn;
  436.             $types[]  = $this->class->fieldMappings[$versionField]['type'];
  437.             $params[] = $this->class->reflFields[$versionField]->getValue($entity);
  438.             switch ($versionFieldType) {
  439.                 case Types::SMALLINT:
  440.                 case Types::INTEGER:
  441.                 case Types::BIGINT:
  442.                     $set[] = $versionColumn ' = ' $versionColumn ' + 1';
  443.                     break;
  444.                 case Types::DATETIME_MUTABLE:
  445.                     $set[] = $versionColumn ' = CURRENT_TIMESTAMP';
  446.                     break;
  447.             }
  448.         }
  449.         $sql 'UPDATE ' $quotedTableName
  450.              ' SET ' implode(', '$set)
  451.              . ' WHERE ' implode(' = ? AND '$where) . ' = ?';
  452.         $result $this->conn->executeStatement($sql$params$types);
  453.         if ($versioned && ! $result) {
  454.             throw OptimisticLockException::lockFailed($entity);
  455.         }
  456.     }
  457.     /**
  458.      * @param array<mixed> $identifier
  459.      * @param string[]     $types
  460.      *
  461.      * @todo Add check for platform if it supports foreign keys/cascading.
  462.      */
  463.     protected function deleteJoinTableRecords(array $identifier, array $types): void
  464.     {
  465.         foreach ($this->class->associationMappings as $mapping) {
  466.             if ($mapping['type'] !== ClassMetadata::MANY_TO_MANY || isset($mapping['isOnDeleteCascade'])) {
  467.                 continue;
  468.             }
  469.             // @Todo this only covers scenarios with no inheritance or of the same level. Is there something
  470.             // like self-referential relationship between different levels of an inheritance hierarchy? I hope not!
  471.             $selfReferential = ($mapping['targetEntity'] === $mapping['sourceEntity']);
  472.             $class           $this->class;
  473.             $association     $mapping;
  474.             $otherColumns    = [];
  475.             $otherKeys       = [];
  476.             $keys            = [];
  477.             if (! $mapping['isOwningSide']) {
  478.                 $class       $this->em->getClassMetadata($mapping['targetEntity']);
  479.                 $association $class->associationMappings[$mapping['mappedBy']];
  480.             }
  481.             $joinColumns $mapping['isOwningSide']
  482.                 ? $association['joinTable']['joinColumns']
  483.                 : $association['joinTable']['inverseJoinColumns'];
  484.             if ($selfReferential) {
  485.                 $otherColumns = ! $mapping['isOwningSide']
  486.                     ? $association['joinTable']['joinColumns']
  487.                     : $association['joinTable']['inverseJoinColumns'];
  488.             }
  489.             foreach ($joinColumns as $joinColumn) {
  490.                 $keys[] = $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  491.             }
  492.             foreach ($otherColumns as $joinColumn) {
  493.                 $otherKeys[] = $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  494.             }
  495.             $joinTableName $this->quoteStrategy->getJoinTableName($association$this->class$this->platform);
  496.             $this->conn->delete($joinTableNamearray_combine($keys$identifier), $types);
  497.             if ($selfReferential) {
  498.                 $this->conn->delete($joinTableNamearray_combine($otherKeys$identifier), $types);
  499.             }
  500.         }
  501.     }
  502.     /**
  503.      * {@inheritDoc}
  504.      */
  505.     public function delete($entity)
  506.     {
  507.         $class      $this->class;
  508.         $identifier $this->em->getUnitOfWork()->getEntityIdentifier($entity);
  509.         $tableName  $this->quoteStrategy->getTableName($class$this->platform);
  510.         $idColumns  $this->quoteStrategy->getIdentifierColumnNames($class$this->platform);
  511.         $id         array_combine($idColumns$identifier);
  512.         $types      $this->getClassIdentifiersTypes($class);
  513.         $this->deleteJoinTableRecords($identifier$types);
  514.         return (bool) $this->conn->delete($tableName$id$types);
  515.     }
  516.     /**
  517.      * Prepares the changeset of an entity for database insertion (UPDATE).
  518.      *
  519.      * The changeset is obtained from the currently running UnitOfWork.
  520.      *
  521.      * During this preparation the array that is passed as the second parameter is filled with
  522.      * <columnName> => <value> pairs, grouped by table name.
  523.      *
  524.      * Example:
  525.      * <code>
  526.      * array(
  527.      *    'foo_table' => array('column1' => 'value1', 'column2' => 'value2', ...),
  528.      *    'bar_table' => array('columnX' => 'valueX', 'columnY' => 'valueY', ...),
  529.      *    ...
  530.      * )
  531.      * </code>
  532.      *
  533.      * @param object $entity   The entity for which to prepare the data.
  534.      * @param bool   $isInsert Whether the data to be prepared refers to an insert statement.
  535.      *
  536.      * @return mixed[][] The prepared data.
  537.      * @psalm-return array<string, array<array-key, mixed|null>>
  538.      */
  539.     protected function prepareUpdateData($entitybool $isInsert false)
  540.     {
  541.         $versionField null;
  542.         $result       = [];
  543.         $uow          $this->em->getUnitOfWork();
  544.         $versioned $this->class->isVersioned;
  545.         if ($versioned !== false) {
  546.             $versionField $this->class->versionField;
  547.         }
  548.         foreach ($uow->getEntityChangeSet($entity) as $field => $change) {
  549.             if (isset($versionField) && $versionField === $field) {
  550.                 continue;
  551.             }
  552.             if (isset($this->class->embeddedClasses[$field])) {
  553.                 continue;
  554.             }
  555.             $newVal $change[1];
  556.             if (! isset($this->class->associationMappings[$field])) {
  557.                 $fieldMapping $this->class->fieldMappings[$field];
  558.                 $columnName   $fieldMapping['columnName'];
  559.                 if (! $isInsert && isset($fieldMapping['notUpdatable'])) {
  560.                     continue;
  561.                 }
  562.                 if ($isInsert && isset($fieldMapping['notInsertable'])) {
  563.                     continue;
  564.                 }
  565.                 $this->columnTypes[$columnName] = $fieldMapping['type'];
  566.                 $result[$this->getOwningTable($field)][$columnName] = $newVal;
  567.                 continue;
  568.             }
  569.             $assoc $this->class->associationMappings[$field];
  570.             // Only owning side of x-1 associations can have a FK column.
  571.             if (! $assoc['isOwningSide'] || ! ($assoc['type'] & ClassMetadata::TO_ONE)) {
  572.                 continue;
  573.             }
  574.             if ($newVal !== null) {
  575.                 $oid spl_object_id($newVal);
  576.                 // If the associated entity $newVal is not yet persisted and/or does not yet have
  577.                 // an ID assigned, we must set $newVal = null. This will insert a null value and
  578.                 // schedule an extra update on the UnitOfWork.
  579.                 //
  580.                 // This gives us extra time to a) possibly obtain a database-generated identifier
  581.                 // value for $newVal, and b) insert $newVal into the database before the foreign
  582.                 // key reference is being made.
  583.                 //
  584.                 // When looking at $this->queuedInserts and $uow->isScheduledForInsert, be aware
  585.                 // of the implementation details that our own executeInserts() method will remove
  586.                 // entities from the former as soon as the insert statement has been executed and
  587.                 // a post-insert ID has been assigned (if necessary), and that the UnitOfWork has
  588.                 // already removed entities from its own list at the time they were passed to our
  589.                 // addInsert() method.
  590.                 //
  591.                 // Then, there is one extra exception we can make: An entity that references back to itself
  592.                 // _and_ uses an application-provided ID (the "NONE" generator strategy) also does not
  593.                 // need the extra update, although it is still in the list of insertions itself.
  594.                 // This looks like a minor optimization at first, but is the capstone for being able to
  595.                 // use non-NULLable, self-referencing associations in applications that provide IDs (like UUIDs).
  596.                 if (
  597.                     (isset($this->queuedInserts[$oid]) || $uow->isScheduledForInsert($newVal))
  598.                     && ! ($newVal === $entity && $this->class->isIdentifierNatural())
  599.                 ) {
  600.                     $uow->scheduleExtraUpdate($entity, [$field => [null$newVal]]);
  601.                     $newVal null;
  602.                 }
  603.             }
  604.             $newValId null;
  605.             if ($newVal !== null) {
  606.                 $newValId $uow->getEntityIdentifier($newVal);
  607.             }
  608.             $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  609.             $owningTable $this->getOwningTable($field);
  610.             foreach ($assoc['joinColumns'] as $joinColumn) {
  611.                 $sourceColumn $joinColumn['name'];
  612.                 $targetColumn $joinColumn['referencedColumnName'];
  613.                 $quotedColumn $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  614.                 $this->quotedColumns[$sourceColumn]  = $quotedColumn;
  615.                 $this->columnTypes[$sourceColumn]    = PersisterHelper::getTypeOfColumn($targetColumn$targetClass$this->em);
  616.                 $result[$owningTable][$sourceColumn] = $newValId
  617.                     $newValId[$targetClass->getFieldForColumn($targetColumn)]
  618.                     : null;
  619.             }
  620.         }
  621.         return $result;
  622.     }
  623.     /**
  624.      * Prepares the data changeset of a managed entity for database insertion (initial INSERT).
  625.      * The changeset of the entity is obtained from the currently running UnitOfWork.
  626.      *
  627.      * The default insert data preparation is the same as for updates.
  628.      *
  629.      * @see prepareUpdateData
  630.      *
  631.      * @param object $entity The entity for which to prepare the data.
  632.      *
  633.      * @return mixed[][] The prepared data for the tables to update.
  634.      * @psalm-return array<string, mixed[]>
  635.      */
  636.     protected function prepareInsertData($entity)
  637.     {
  638.         return $this->prepareUpdateData($entitytrue);
  639.     }
  640.     /**
  641.      * {@inheritDoc}
  642.      */
  643.     public function getOwningTable($fieldName)
  644.     {
  645.         return $this->class->getTableName();
  646.     }
  647.     /**
  648.      * {@inheritDoc}
  649.      */
  650.     public function load(array $criteria$entity null$assoc null, array $hints = [], $lockMode null$limit null, ?array $orderBy null)
  651.     {
  652.         $this->switchPersisterContext(null$limit);
  653.         $sql              $this->getSelectSQL($criteria$assoc$lockMode$limitnull$orderBy);
  654.         [$params$types] = $this->expandParameters($criteria);
  655.         $stmt             $this->conn->executeQuery($sql$params$types);
  656.         if ($entity !== null) {
  657.             $hints[Query::HINT_REFRESH]        = true;
  658.             $hints[Query::HINT_REFRESH_ENTITY] = $entity;
  659.         }
  660.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  661.         $entities $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm$hints);
  662.         return $entities $entities[0] : null;
  663.     }
  664.     /**
  665.      * {@inheritDoc}
  666.      */
  667.     public function loadById(array $identifier$entity null)
  668.     {
  669.         return $this->load($identifier$entity);
  670.     }
  671.     /**
  672.      * {@inheritDoc}
  673.      */
  674.     public function loadOneToOneEntity(array $assoc$sourceEntity, array $identifier = [])
  675.     {
  676.         $foundEntity $this->em->getUnitOfWork()->tryGetById($identifier$assoc['targetEntity']);
  677.         if ($foundEntity !== false) {
  678.             return $foundEntity;
  679.         }
  680.         $targetClass $this->em->getClassMetadata($assoc['targetEntity']);
  681.         if ($assoc['isOwningSide']) {
  682.             $isInverseSingleValued $assoc['inversedBy'] && ! $targetClass->isCollectionValuedAssociation($assoc['inversedBy']);
  683.             // Mark inverse side as fetched in the hints, otherwise the UoW would
  684.             // try to load it in a separate query (remember: to-one inverse sides can not be lazy).
  685.             $hints = [];
  686.             if ($isInverseSingleValued) {
  687.                 $hints['fetched']['r'][$assoc['inversedBy']] = true;
  688.             }
  689.             $targetEntity $this->load($identifiernull$assoc$hints);
  690.             // Complete bidirectional association, if necessary
  691.             if ($targetEntity !== null && $isInverseSingleValued) {
  692.                 $targetClass->reflFields[$assoc['inversedBy']]->setValue($targetEntity$sourceEntity);
  693.             }
  694.             return $targetEntity;
  695.         }
  696.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  697.         $owningAssoc $targetClass->getAssociationMapping($assoc['mappedBy']);
  698.         $computedIdentifier = [];
  699.         // TRICKY: since the association is specular source and target are flipped
  700.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  701.             if (! isset($sourceClass->fieldNames[$sourceKeyColumn])) {
  702.                 throw MappingException::joinColumnMustPointToMappedField(
  703.                     $sourceClass->name,
  704.                     $sourceKeyColumn
  705.                 );
  706.             }
  707.             $computedIdentifier[$targetClass->getFieldForColumn($targetKeyColumn)] =
  708.                 $sourceClass->reflFields[$sourceClass->fieldNames[$sourceKeyColumn]]->getValue($sourceEntity);
  709.         }
  710.         $targetEntity $this->load($computedIdentifiernull$assoc);
  711.         if ($targetEntity !== null) {
  712.             $targetClass->setFieldValue($targetEntity$assoc['mappedBy'], $sourceEntity);
  713.         }
  714.         return $targetEntity;
  715.     }
  716.     /**
  717.      * {@inheritDoc}
  718.      */
  719.     public function refresh(array $id$entity$lockMode null)
  720.     {
  721.         $sql              $this->getSelectSQL($idnull$lockMode);
  722.         [$params$types] = $this->expandParameters($id);
  723.         $stmt             $this->conn->executeQuery($sql$params$types);
  724.         $hydrator $this->em->newHydrator(Query::HYDRATE_OBJECT);
  725.         $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [Query::HINT_REFRESH => true]);
  726.     }
  727.     /**
  728.      * {@inheritDoc}
  729.      */
  730.     public function count($criteria = [])
  731.     {
  732.         $sql $this->getCountSQL($criteria);
  733.         [$params$types] = $criteria instanceof Criteria
  734.             $this->expandCriteriaParameters($criteria)
  735.             : $this->expandParameters($criteria);
  736.         return (int) $this->conn->executeQuery($sql$params$types)->fetchOne();
  737.     }
  738.     /**
  739.      * {@inheritDoc}
  740.      */
  741.     public function loadCriteria(Criteria $criteria)
  742.     {
  743.         $orderBy $criteria->getOrderings();
  744.         $limit   $criteria->getMaxResults();
  745.         $offset  $criteria->getFirstResult();
  746.         $query   $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  747.         [$params$types] = $this->expandCriteriaParameters($criteria);
  748.         $stmt     $this->conn->executeQuery($query$params$types);
  749.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  750.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  751.     }
  752.     /**
  753.      * {@inheritDoc}
  754.      */
  755.     public function expandCriteriaParameters(Criteria $criteria)
  756.     {
  757.         $expression $criteria->getWhereExpression();
  758.         $sqlParams  = [];
  759.         $sqlTypes   = [];
  760.         if ($expression === null) {
  761.             return [$sqlParams$sqlTypes];
  762.         }
  763.         $valueVisitor = new SqlValueVisitor();
  764.         $valueVisitor->dispatch($expression);
  765.         [, $types] = $valueVisitor->getParamsAndTypes();
  766.         foreach ($types as $type) {
  767.             [$field$value$operator] = $type;
  768.             if ($value === null && ($operator === Comparison::EQ || $operator === Comparison::NEQ)) {
  769.                 continue;
  770.             }
  771.             $sqlParams array_merge($sqlParams$this->getValues($value));
  772.             $sqlTypes  array_merge($sqlTypes$this->getTypes($field$value$this->class));
  773.         }
  774.         return [$sqlParams$sqlTypes];
  775.     }
  776.     /**
  777.      * {@inheritDoc}
  778.      */
  779.     public function loadAll(array $criteria = [], ?array $orderBy null$limit null$offset null)
  780.     {
  781.         $this->switchPersisterContext($offset$limit);
  782.         $sql              $this->getSelectSQL($criterianullnull$limit$offset$orderBy);
  783.         [$params$types] = $this->expandParameters($criteria);
  784.         $stmt             $this->conn->executeQuery($sql$params$types);
  785.         $hydrator $this->em->newHydrator($this->currentPersisterContext->selectJoinSql Query::HYDRATE_OBJECT Query::HYDRATE_SIMPLEOBJECT);
  786.         return $hydrator->hydrateAll($stmt$this->currentPersisterContext->rsm, [UnitOfWork::HINT_DEFEREAGERLOAD => true]);
  787.     }
  788.     /**
  789.      * {@inheritDoc}
  790.      */
  791.     public function getManyToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  792.     {
  793.         $this->switchPersisterContext($offset$limit);
  794.         $stmt $this->getManyToManyStatement($assoc$sourceEntity$offset$limit);
  795.         return $this->loadArrayFromResult($assoc$stmt);
  796.     }
  797.     /**
  798.      * Loads an array of entities from a given DBAL statement.
  799.      *
  800.      * @param mixed[] $assoc
  801.      *
  802.      * @return mixed[]
  803.      */
  804.     private function loadArrayFromResult(array $assocResult $stmt): array
  805.     {
  806.         $rsm   $this->currentPersisterContext->rsm;
  807.         $hints = [UnitOfWork::HINT_DEFEREAGERLOAD => true];
  808.         if (isset($assoc['indexBy'])) {
  809.             $rsm = clone $this->currentPersisterContext->rsm// this is necessary because the "default rsm" should be changed.
  810.             $rsm->addIndexBy('r'$assoc['indexBy']);
  811.         }
  812.         return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt$rsm$hints);
  813.     }
  814.     /**
  815.      * Hydrates a collection from a given DBAL statement.
  816.      *
  817.      * @param mixed[] $assoc
  818.      *
  819.      * @return mixed[]
  820.      */
  821.     private function loadCollectionFromStatement(
  822.         array $assoc,
  823.         Result $stmt,
  824.         PersistentCollection $coll
  825.     ): array {
  826.         $rsm   $this->currentPersisterContext->rsm;
  827.         $hints = [
  828.             UnitOfWork::HINT_DEFEREAGERLOAD => true,
  829.             'collection' => $coll,
  830.         ];
  831.         if (isset($assoc['indexBy'])) {
  832.             $rsm = clone $this->currentPersisterContext->rsm// this is necessary because the "default rsm" should be changed.
  833.             $rsm->addIndexBy('r'$assoc['indexBy']);
  834.         }
  835.         return $this->em->newHydrator(Query::HYDRATE_OBJECT)->hydrateAll($stmt$rsm$hints);
  836.     }
  837.     /**
  838.      * {@inheritDoc}
  839.      */
  840.     public function loadManyToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  841.     {
  842.         $stmt $this->getManyToManyStatement($assoc$sourceEntity);
  843.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  844.     }
  845.     /**
  846.      * @param object $sourceEntity
  847.      * @psalm-param array<string, mixed> $assoc
  848.      *
  849.      * @return Result
  850.      *
  851.      * @throws MappingException
  852.      */
  853.     private function getManyToManyStatement(
  854.         array $assoc,
  855.         $sourceEntity,
  856.         ?int $offset null,
  857.         ?int $limit null
  858.     ) {
  859.         $this->switchPersisterContext($offset$limit);
  860.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  861.         $class       $sourceClass;
  862.         $association $assoc;
  863.         $criteria    = [];
  864.         $parameters  = [];
  865.         if (! $assoc['isOwningSide']) {
  866.             $class       $this->em->getClassMetadata($assoc['targetEntity']);
  867.             $association $class->associationMappings[$assoc['mappedBy']];
  868.         }
  869.         $joinColumns $assoc['isOwningSide']
  870.             ? $association['joinTable']['joinColumns']
  871.             : $association['joinTable']['inverseJoinColumns'];
  872.         $quotedJoinTable $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  873.         foreach ($joinColumns as $joinColumn) {
  874.             $sourceKeyColumn $joinColumn['referencedColumnName'];
  875.             $quotedKeyColumn $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  876.             switch (true) {
  877.                 case $sourceClass->containsForeignIdentifier:
  878.                     $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  879.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  880.                     if (isset($sourceClass->associationMappings[$field])) {
  881.                         $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  882.                         $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  883.                     }
  884.                     break;
  885.                 case isset($sourceClass->fieldNames[$sourceKeyColumn]):
  886.                     $field $sourceClass->fieldNames[$sourceKeyColumn];
  887.                     $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  888.                     break;
  889.                 default:
  890.                     throw MappingException::joinColumnMustPointToMappedField(
  891.                         $sourceClass->name,
  892.                         $sourceKeyColumn
  893.                     );
  894.             }
  895.             $criteria[$quotedJoinTable '.' $quotedKeyColumn] = $value;
  896.             $parameters[]                                        = [
  897.                 'value' => $value,
  898.                 'field' => $field,
  899.                 'class' => $sourceClass,
  900.             ];
  901.         }
  902.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  903.         [$params$types] = $this->expandToManyParameters($parameters);
  904.         return $this->conn->executeQuery($sql$params$types);
  905.     }
  906.     /**
  907.      * {@inheritDoc}
  908.      */
  909.     public function getSelectSQL($criteria$assoc null$lockMode null$limit null$offset null, ?array $orderBy null)
  910.     {
  911.         $this->switchPersisterContext($offset$limit);
  912.         $lockSql    '';
  913.         $joinSql    '';
  914.         $orderBySql '';
  915.         if ($assoc !== null && $assoc['type'] === ClassMetadata::MANY_TO_MANY) {
  916.             $joinSql $this->getSelectManyToManyJoinSQL($assoc);
  917.         }
  918.         if (isset($assoc['orderBy'])) {
  919.             $orderBy $assoc['orderBy'];
  920.         }
  921.         if ($orderBy) {
  922.             $orderBySql $this->getOrderBySQL($orderBy$this->getSQLTableAlias($this->class->name));
  923.         }
  924.         $conditionSql $criteria instanceof Criteria
  925.             $this->getSelectConditionCriteriaSQL($criteria)
  926.             : $this->getSelectConditionSQL($criteria$assoc);
  927.         switch ($lockMode) {
  928.             case LockMode::PESSIMISTIC_READ:
  929.                 $lockSql ' ' $this->getReadLockSQL($this->platform);
  930.                 break;
  931.             case LockMode::PESSIMISTIC_WRITE:
  932.                 $lockSql ' ' $this->getWriteLockSQL($this->platform);
  933.                 break;
  934.         }
  935.         $columnList $this->getSelectColumnsSQL();
  936.         $tableAlias $this->getSQLTableAlias($this->class->name);
  937.         $filterSql  $this->generateFilterConditionSQL($this->class$tableAlias);
  938.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  939.         if ($filterSql !== '') {
  940.             $conditionSql $conditionSql
  941.                 $conditionSql ' AND ' $filterSql
  942.                 $filterSql;
  943.         }
  944.         $select 'SELECT ' $columnList;
  945.         $from   ' FROM ' $tableName ' ' $tableAlias;
  946.         $join   $this->currentPersisterContext->selectJoinSql $joinSql;
  947.         $where  = ($conditionSql ' WHERE ' $conditionSql '');
  948.         $lock   $this->platform->appendLockHint($from$lockMode ?? LockMode::NONE);
  949.         $query  $select
  950.             $lock
  951.             $join
  952.             $where
  953.             $orderBySql;
  954.         return $this->platform->modifyLimitQuery($query$limit$offset ?? 0) . $lockSql;
  955.     }
  956.     /**
  957.      * {@inheritDoc}
  958.      */
  959.     public function getCountSQL($criteria = [])
  960.     {
  961.         $tableName  $this->quoteStrategy->getTableName($this->class$this->platform);
  962.         $tableAlias $this->getSQLTableAlias($this->class->name);
  963.         $conditionSql $criteria instanceof Criteria
  964.             $this->getSelectConditionCriteriaSQL($criteria)
  965.             : $this->getSelectConditionSQL($criteria);
  966.         $filterSql $this->generateFilterConditionSQL($this->class$tableAlias);
  967.         if ($filterSql !== '') {
  968.             $conditionSql $conditionSql
  969.                 $conditionSql ' AND ' $filterSql
  970.                 $filterSql;
  971.         }
  972.         return 'SELECT COUNT(*) '
  973.             'FROM ' $tableName ' ' $tableAlias
  974.             . (empty($conditionSql) ? '' ' WHERE ' $conditionSql);
  975.     }
  976.     /**
  977.      * Gets the ORDER BY SQL snippet for ordered collections.
  978.      *
  979.      * @psalm-param array<string, string> $orderBy
  980.      *
  981.      * @throws InvalidOrientation
  982.      * @throws InvalidFindByCall
  983.      * @throws UnrecognizedField
  984.      */
  985.     final protected function getOrderBySQL(array $orderBystring $baseTableAlias): string
  986.     {
  987.         $orderByList = [];
  988.         foreach ($orderBy as $fieldName => $orientation) {
  989.             $orientation strtoupper(trim($orientation));
  990.             if ($orientation !== 'ASC' && $orientation !== 'DESC') {
  991.                 throw InvalidOrientation::fromClassNameAndField($this->class->name$fieldName);
  992.             }
  993.             if (isset($this->class->fieldMappings[$fieldName])) {
  994.                 $tableAlias = isset($this->class->fieldMappings[$fieldName]['inherited'])
  995.                     ? $this->getSQLTableAlias($this->class->fieldMappings[$fieldName]['inherited'])
  996.                     : $baseTableAlias;
  997.                 $columnName    $this->quoteStrategy->getColumnName($fieldName$this->class$this->platform);
  998.                 $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  999.                 continue;
  1000.             }
  1001.             if (isset($this->class->associationMappings[$fieldName])) {
  1002.                 if (! $this->class->associationMappings[$fieldName]['isOwningSide']) {
  1003.                     throw InvalidFindByCall::fromInverseSideUsage($this->class->name$fieldName);
  1004.                 }
  1005.                 $tableAlias = isset($this->class->associationMappings[$fieldName]['inherited'])
  1006.                     ? $this->getSQLTableAlias($this->class->associationMappings[$fieldName]['inherited'])
  1007.                     : $baseTableAlias;
  1008.                 foreach ($this->class->associationMappings[$fieldName]['joinColumns'] as $joinColumn) {
  1009.                     $columnName    $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1010.                     $orderByList[] = $tableAlias '.' $columnName ' ' $orientation;
  1011.                 }
  1012.                 continue;
  1013.             }
  1014.             throw UnrecognizedField::byFullyQualifiedName($this->class->name$fieldName);
  1015.         }
  1016.         return ' ORDER BY ' implode(', '$orderByList);
  1017.     }
  1018.     /**
  1019.      * Gets the SQL fragment with the list of columns to select when querying for
  1020.      * an entity in this persister.
  1021.      *
  1022.      * Subclasses should override this method to alter or change the select column
  1023.      * list SQL fragment. Note that in the implementation of BasicEntityPersister
  1024.      * the resulting SQL fragment is generated only once and cached in {@link selectColumnListSql}.
  1025.      * Subclasses may or may not do the same.
  1026.      *
  1027.      * @return string The SQL fragment.
  1028.      */
  1029.     protected function getSelectColumnsSQL()
  1030.     {
  1031.         if ($this->currentPersisterContext->selectColumnListSql !== null) {
  1032.             return $this->currentPersisterContext->selectColumnListSql;
  1033.         }
  1034.         $columnList = [];
  1035.         $this->currentPersisterContext->rsm->addEntityResult($this->class->name'r'); // r for root
  1036.         // Add regular columns to select list
  1037.         foreach ($this->class->fieldNames as $field) {
  1038.             $columnList[] = $this->getSelectColumnSQL($field$this->class);
  1039.         }
  1040.         $this->currentPersisterContext->selectJoinSql '';
  1041.         $eagerAliasCounter                            0;
  1042.         foreach ($this->class->associationMappings as $assocField => $assoc) {
  1043.             $assocColumnSQL $this->getSelectColumnAssociationSQL($assocField$assoc$this->class);
  1044.             if ($assocColumnSQL) {
  1045.                 $columnList[] = $assocColumnSQL;
  1046.             }
  1047.             $isAssocToOneInverseSide $assoc['type'] & ClassMetadata::TO_ONE && ! $assoc['isOwningSide'];
  1048.             $isAssocFromOneEager     $assoc['type'] & ClassMetadata::TO_ONE && $assoc['fetch'] === ClassMetadata::FETCH_EAGER;
  1049.             if (! ($isAssocFromOneEager || $isAssocToOneInverseSide)) {
  1050.                 continue;
  1051.             }
  1052.             if ((($assoc['type'] & ClassMetadata::TO_MANY) > 0) && $this->currentPersisterContext->handlesLimits) {
  1053.                 continue;
  1054.             }
  1055.             $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1056.             if ($eagerEntity->inheritanceType !== ClassMetadata::INHERITANCE_TYPE_NONE) {
  1057.                 continue; // now this is why you shouldn't use inheritance
  1058.             }
  1059.             $assocAlias 'e' . ($eagerAliasCounter++);
  1060.             $this->currentPersisterContext->rsm->addJoinedEntityResult($assoc['targetEntity'], $assocAlias'r'$assocField);
  1061.             foreach ($eagerEntity->fieldNames as $field) {
  1062.                 $columnList[] = $this->getSelectColumnSQL($field$eagerEntity$assocAlias);
  1063.             }
  1064.             foreach ($eagerEntity->associationMappings as $eagerAssocField => $eagerAssoc) {
  1065.                 $eagerAssocColumnSQL $this->getSelectColumnAssociationSQL(
  1066.                     $eagerAssocField,
  1067.                     $eagerAssoc,
  1068.                     $eagerEntity,
  1069.                     $assocAlias
  1070.                 );
  1071.                 if ($eagerAssocColumnSQL) {
  1072.                     $columnList[] = $eagerAssocColumnSQL;
  1073.                 }
  1074.             }
  1075.             $association   $assoc;
  1076.             $joinCondition = [];
  1077.             if (isset($assoc['indexBy'])) {
  1078.                 $this->currentPersisterContext->rsm->addIndexBy($assocAlias$assoc['indexBy']);
  1079.             }
  1080.             if (! $assoc['isOwningSide']) {
  1081.                 $eagerEntity $this->em->getClassMetadata($assoc['targetEntity']);
  1082.                 $association $eagerEntity->getAssociationMapping($assoc['mappedBy']);
  1083.             }
  1084.             $joinTableAlias $this->getSQLTableAlias($eagerEntity->name$assocAlias);
  1085.             $joinTableName  $this->quoteStrategy->getTableName($eagerEntity$this->platform);
  1086.             if ($assoc['isOwningSide']) {
  1087.                 $tableAlias                                    $this->getSQLTableAlias($association['targetEntity'], $assocAlias);
  1088.                 $this->currentPersisterContext->selectJoinSql .= ' ' $this->getJoinSQLForJoinColumns($association['joinColumns']);
  1089.                 foreach ($association['joinColumns'] as $joinColumn) {
  1090.                     $sourceCol       $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1091.                     $targetCol       $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1092.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'])
  1093.                                         . '.' $sourceCol ' = ' $tableAlias '.' $targetCol;
  1094.                 }
  1095.                 // Add filter SQL
  1096.                 $filterSql $this->generateFilterConditionSQL($eagerEntity$tableAlias);
  1097.                 if ($filterSql) {
  1098.                     $joinCondition[] = $filterSql;
  1099.                 }
  1100.             } else {
  1101.                 $this->currentPersisterContext->selectJoinSql .= ' LEFT JOIN';
  1102.                 foreach ($association['joinColumns'] as $joinColumn) {
  1103.                     $sourceCol $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1104.                     $targetCol $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1105.                     $joinCondition[] = $this->getSQLTableAlias($association['sourceEntity'], $assocAlias) . '.' $sourceCol ' = '
  1106.                         $this->getSQLTableAlias($association['targetEntity']) . '.' $targetCol;
  1107.                 }
  1108.             }
  1109.             $this->currentPersisterContext->selectJoinSql .= ' ' $joinTableName ' ' $joinTableAlias ' ON ';
  1110.             $this->currentPersisterContext->selectJoinSql .= implode(' AND '$joinCondition);
  1111.         }
  1112.         $this->currentPersisterContext->selectColumnListSql implode(', '$columnList);
  1113.         return $this->currentPersisterContext->selectColumnListSql;
  1114.     }
  1115.     /**
  1116.      * Gets the SQL join fragment used when selecting entities from an association.
  1117.      *
  1118.      * @param string             $field
  1119.      * @param AssociationMapping $assoc
  1120.      * @param string             $alias
  1121.      *
  1122.      * @return string
  1123.      */
  1124.     protected function getSelectColumnAssociationSQL($field$assocClassMetadata $class$alias 'r')
  1125.     {
  1126.         if (! ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE)) {
  1127.             return '';
  1128.         }
  1129.         $columnList    = [];
  1130.         $targetClass   $this->em->getClassMetadata($assoc['targetEntity']);
  1131.         $isIdentifier  = isset($assoc['id']) && $assoc['id'] === true;
  1132.         $sqlTableAlias $this->getSQLTableAlias($class->name, ($alias === 'r' '' $alias));
  1133.         foreach ($assoc['joinColumns'] as $joinColumn) {
  1134.             $quotedColumn     $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1135.             $resultColumnName $this->getSQLColumnAlias($joinColumn['name']);
  1136.             $type             PersisterHelper::getTypeOfColumn($joinColumn['referencedColumnName'], $targetClass$this->em);
  1137.             $this->currentPersisterContext->rsm->addMetaResult($alias$resultColumnName$joinColumn['name'], $isIdentifier$type);
  1138.             $columnList[] = sprintf('%s.%s AS %s'$sqlTableAlias$quotedColumn$resultColumnName);
  1139.         }
  1140.         return implode(', '$columnList);
  1141.     }
  1142.     /**
  1143.      * Gets the SQL join fragment used when selecting entities from a
  1144.      * many-to-many association.
  1145.      *
  1146.      * @psalm-param AssociationMapping $manyToMany
  1147.      *
  1148.      * @return string
  1149.      */
  1150.     protected function getSelectManyToManyJoinSQL(array $manyToMany)
  1151.     {
  1152.         $conditions       = [];
  1153.         $association      $manyToMany;
  1154.         $sourceTableAlias $this->getSQLTableAlias($this->class->name);
  1155.         if (! $manyToMany['isOwningSide']) {
  1156.             $targetEntity $this->em->getClassMetadata($manyToMany['targetEntity']);
  1157.             $association  $targetEntity->associationMappings[$manyToMany['mappedBy']];
  1158.         }
  1159.         $joinTableName $this->quoteStrategy->getJoinTableName($association$this->class$this->platform);
  1160.         $joinColumns   $manyToMany['isOwningSide']
  1161.             ? $association['joinTable']['inverseJoinColumns']
  1162.             : $association['joinTable']['joinColumns'];
  1163.         foreach ($joinColumns as $joinColumn) {
  1164.             $quotedSourceColumn $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1165.             $quotedTargetColumn $this->quoteStrategy->getReferencedJoinColumnName($joinColumn$this->class$this->platform);
  1166.             $conditions[]       = $sourceTableAlias '.' $quotedTargetColumn ' = ' $joinTableName '.' $quotedSourceColumn;
  1167.         }
  1168.         return ' INNER JOIN ' $joinTableName ' ON ' implode(' AND '$conditions);
  1169.     }
  1170.     /**
  1171.      * {@inheritDoc}
  1172.      */
  1173.     public function getInsertSQL()
  1174.     {
  1175.         if ($this->insertSql !== null) {
  1176.             return $this->insertSql;
  1177.         }
  1178.         $columns   $this->getInsertColumnList();
  1179.         $tableName $this->quoteStrategy->getTableName($this->class$this->platform);
  1180.         if (empty($columns)) {
  1181.             $identityColumn  $this->quoteStrategy->getColumnName($this->class->identifier[0], $this->class$this->platform);
  1182.             $this->insertSql $this->platform->getEmptyIdentityInsertSQL($tableName$identityColumn);
  1183.             return $this->insertSql;
  1184.         }
  1185.         $values  = [];
  1186.         $columns array_unique($columns);
  1187.         foreach ($columns as $column) {
  1188.             $placeholder '?';
  1189.             if (
  1190.                 isset($this->class->fieldNames[$column])
  1191.                 && isset($this->columnTypes[$this->class->fieldNames[$column]])
  1192.                 && isset($this->class->fieldMappings[$this->class->fieldNames[$column]]['requireSQLConversion'])
  1193.             ) {
  1194.                 $type        Type::getType($this->columnTypes[$this->class->fieldNames[$column]]);
  1195.                 $placeholder $type->convertToDatabaseValueSQL('?'$this->platform);
  1196.             }
  1197.             $values[] = $placeholder;
  1198.         }
  1199.         $columns implode(', '$columns);
  1200.         $values  implode(', '$values);
  1201.         $this->insertSql sprintf('INSERT INTO %s (%s) VALUES (%s)'$tableName$columns$values);
  1202.         return $this->insertSql;
  1203.     }
  1204.     /**
  1205.      * Gets the list of columns to put in the INSERT SQL statement.
  1206.      *
  1207.      * Subclasses should override this method to alter or change the list of
  1208.      * columns placed in the INSERT statements used by the persister.
  1209.      *
  1210.      * @return string[] The list of columns.
  1211.      * @psalm-return list<string>
  1212.      */
  1213.     protected function getInsertColumnList()
  1214.     {
  1215.         $columns = [];
  1216.         foreach ($this->class->reflFields as $name => $field) {
  1217.             if ($this->class->isVersioned && $this->class->versionField === $name) {
  1218.                 continue;
  1219.             }
  1220.             if (isset($this->class->embeddedClasses[$name])) {
  1221.                 continue;
  1222.             }
  1223.             if (isset($this->class->associationMappings[$name])) {
  1224.                 $assoc $this->class->associationMappings[$name];
  1225.                 if ($assoc['isOwningSide'] && $assoc['type'] & ClassMetadata::TO_ONE) {
  1226.                     foreach ($assoc['joinColumns'] as $joinColumn) {
  1227.                         $columns[] = $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1228.                     }
  1229.                 }
  1230.                 continue;
  1231.             }
  1232.             if (! $this->class->isIdGeneratorIdentity() || $this->class->identifier[0] !== $name) {
  1233.                 if (isset($this->class->fieldMappings[$name]['notInsertable'])) {
  1234.                     continue;
  1235.                 }
  1236.                 $columns[]                = $this->quoteStrategy->getColumnName($name$this->class$this->platform);
  1237.                 $this->columnTypes[$name] = $this->class->fieldMappings[$name]['type'];
  1238.             }
  1239.         }
  1240.         return $columns;
  1241.     }
  1242.     /**
  1243.      * Gets the SQL snippet of a qualified column name for the given field name.
  1244.      *
  1245.      * @param string        $field The field name.
  1246.      * @param ClassMetadata $class The class that declares this field. The table this class is
  1247.      *                             mapped to must own the column for the given field.
  1248.      * @param string        $alias
  1249.      *
  1250.      * @return string
  1251.      */
  1252.     protected function getSelectColumnSQL($fieldClassMetadata $class$alias 'r')
  1253.     {
  1254.         $root         $alias === 'r' '' $alias;
  1255.         $tableAlias   $this->getSQLTableAlias($class->name$root);
  1256.         $fieldMapping $class->fieldMappings[$field];
  1257.         $sql          sprintf('%s.%s'$tableAlias$this->quoteStrategy->getColumnName($field$class$this->platform));
  1258.         $columnAlias  $this->getSQLColumnAlias($fieldMapping['columnName']);
  1259.         $this->currentPersisterContext->rsm->addFieldResult($alias$columnAlias$field);
  1260.         if (! empty($fieldMapping['enumType'])) {
  1261.             $this->currentPersisterContext->rsm->addEnumResult($columnAlias$fieldMapping['enumType']);
  1262.         }
  1263.         if (isset($fieldMapping['requireSQLConversion'])) {
  1264.             $type Type::getType($fieldMapping['type']);
  1265.             $sql  $type->convertToPHPValueSQL($sql$this->platform);
  1266.         }
  1267.         return $sql ' AS ' $columnAlias;
  1268.     }
  1269.     /**
  1270.      * Gets the SQL table alias for the given class name.
  1271.      *
  1272.      * @param string $className
  1273.      * @param string $assocName
  1274.      *
  1275.      * @return string The SQL table alias.
  1276.      *
  1277.      * @todo Reconsider. Binding table aliases to class names is not such a good idea.
  1278.      */
  1279.     protected function getSQLTableAlias($className$assocName '')
  1280.     {
  1281.         if ($assocName) {
  1282.             $className .= '#' $assocName;
  1283.         }
  1284.         if (isset($this->currentPersisterContext->sqlTableAliases[$className])) {
  1285.             return $this->currentPersisterContext->sqlTableAliases[$className];
  1286.         }
  1287.         $tableAlias 't' $this->currentPersisterContext->sqlAliasCounter++;
  1288.         $this->currentPersisterContext->sqlTableAliases[$className] = $tableAlias;
  1289.         return $tableAlias;
  1290.     }
  1291.     /**
  1292.      * {@inheritDoc}
  1293.      */
  1294.     public function lock(array $criteria$lockMode)
  1295.     {
  1296.         $lockSql      '';
  1297.         $conditionSql $this->getSelectConditionSQL($criteria);
  1298.         switch ($lockMode) {
  1299.             case LockMode::PESSIMISTIC_READ:
  1300.                 $lockSql $this->getReadLockSQL($this->platform);
  1301.                 break;
  1302.             case LockMode::PESSIMISTIC_WRITE:
  1303.                 $lockSql $this->getWriteLockSQL($this->platform);
  1304.                 break;
  1305.         }
  1306.         $lock  $this->getLockTablesSql($lockMode);
  1307.         $where = ($conditionSql ' WHERE ' $conditionSql '') . ' ';
  1308.         $sql   'SELECT 1 '
  1309.              $lock
  1310.              $where
  1311.              $lockSql;
  1312.         [$params$types] = $this->expandParameters($criteria);
  1313.         $this->conn->executeQuery($sql$params$types);
  1314.     }
  1315.     /**
  1316.      * Gets the FROM and optionally JOIN conditions to lock the entity managed by this persister.
  1317.      *
  1318.      * @param int|null $lockMode One of the Doctrine\DBAL\LockMode::* constants.
  1319.      * @psalm-param LockMode::*|null $lockMode
  1320.      *
  1321.      * @return string
  1322.      */
  1323.     protected function getLockTablesSql($lockMode)
  1324.     {
  1325.         if ($lockMode === null) {
  1326.             Deprecation::trigger(
  1327.                 'doctrine/orm',
  1328.                 'https://github.com/doctrine/orm/pull/9466',
  1329.                 'Passing null as argument to %s is deprecated, pass LockMode::NONE instead.',
  1330.                 __METHOD__
  1331.             );
  1332.             $lockMode LockMode::NONE;
  1333.         }
  1334.         return $this->platform->appendLockHint(
  1335.             'FROM '
  1336.             $this->quoteStrategy->getTableName($this->class$this->platform) . ' '
  1337.             $this->getSQLTableAlias($this->class->name),
  1338.             $lockMode
  1339.         );
  1340.     }
  1341.     /**
  1342.      * Gets the Select Where Condition from a Criteria object.
  1343.      *
  1344.      * @return string
  1345.      */
  1346.     protected function getSelectConditionCriteriaSQL(Criteria $criteria)
  1347.     {
  1348.         $expression $criteria->getWhereExpression();
  1349.         if ($expression === null) {
  1350.             return '';
  1351.         }
  1352.         $visitor = new SqlExpressionVisitor($this$this->class);
  1353.         return $visitor->dispatch($expression);
  1354.     }
  1355.     /**
  1356.      * {@inheritDoc}
  1357.      */
  1358.     public function getSelectConditionStatementSQL($field$value$assoc null$comparison null)
  1359.     {
  1360.         $selectedColumns = [];
  1361.         $columns         $this->getSelectConditionStatementColumnSQL($field$assoc);
  1362.         if (count($columns) > && $comparison === Comparison::IN) {
  1363.             /*
  1364.              *  @todo try to support multi-column IN expressions.
  1365.              *  Example: (col1, col2) IN (('val1A', 'val2A'), ('val1B', 'val2B'))
  1366.              */
  1367.             throw CantUseInOperatorOnCompositeKeys::create();
  1368.         }
  1369.         foreach ($columns as $column) {
  1370.             $placeholder '?';
  1371.             if (isset($this->class->fieldMappings[$field]['requireSQLConversion'])) {
  1372.                 $type        Type::getType($this->class->fieldMappings[$field]['type']);
  1373.                 $placeholder $type->convertToDatabaseValueSQL($placeholder$this->platform);
  1374.             }
  1375.             if ($comparison !== null) {
  1376.                 // special case null value handling
  1377.                 if (($comparison === Comparison::EQ || $comparison === Comparison::IS) && $value === null) {
  1378.                     $selectedColumns[] = $column ' IS NULL';
  1379.                     continue;
  1380.                 }
  1381.                 if ($comparison === Comparison::NEQ && $value === null) {
  1382.                     $selectedColumns[] = $column ' IS NOT NULL';
  1383.                     continue;
  1384.                 }
  1385.                 $selectedColumns[] = $column ' ' sprintf(self::$comparisonMap[$comparison], $placeholder);
  1386.                 continue;
  1387.             }
  1388.             if (is_array($value)) {
  1389.                 $in sprintf('%s IN (%s)'$column$placeholder);
  1390.                 if (array_search(null$valuetrue) !== false) {
  1391.                     $selectedColumns[] = sprintf('(%s OR %s IS NULL)'$in$column);
  1392.                     continue;
  1393.                 }
  1394.                 $selectedColumns[] = $in;
  1395.                 continue;
  1396.             }
  1397.             if ($value === null) {
  1398.                 $selectedColumns[] = sprintf('%s IS NULL'$column);
  1399.                 continue;
  1400.             }
  1401.             $selectedColumns[] = sprintf('%s = %s'$column$placeholder);
  1402.         }
  1403.         return implode(' AND '$selectedColumns);
  1404.     }
  1405.     /**
  1406.      * Builds the left-hand-side of a where condition statement.
  1407.      *
  1408.      * @psalm-param AssociationMapping|null $assoc
  1409.      *
  1410.      * @return string[]
  1411.      * @psalm-return list<string>
  1412.      *
  1413.      * @throws InvalidFindByCall
  1414.      * @throws UnrecognizedField
  1415.      */
  1416.     private function getSelectConditionStatementColumnSQL(
  1417.         string $field,
  1418.         ?array $assoc null
  1419.     ): array {
  1420.         if (isset($this->class->fieldMappings[$field])) {
  1421.             $className $this->class->fieldMappings[$field]['inherited'] ?? $this->class->name;
  1422.             return [$this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getColumnName($field$this->class$this->platform)];
  1423.         }
  1424.         if (isset($this->class->associationMappings[$field])) {
  1425.             $association $this->class->associationMappings[$field];
  1426.             // Many-To-Many requires join table check for joinColumn
  1427.             $columns = [];
  1428.             $class   $this->class;
  1429.             if ($association['type'] === ClassMetadata::MANY_TO_MANY) {
  1430.                 if (! $association['isOwningSide']) {
  1431.                     $association $assoc;
  1432.                 }
  1433.                 $joinTableName $this->quoteStrategy->getJoinTableName($association$class$this->platform);
  1434.                 $joinColumns   $assoc['isOwningSide']
  1435.                     ? $association['joinTable']['joinColumns']
  1436.                     : $association['joinTable']['inverseJoinColumns'];
  1437.                 foreach ($joinColumns as $joinColumn) {
  1438.                     $columns[] = $joinTableName '.' $this->quoteStrategy->getJoinColumnName($joinColumn$class$this->platform);
  1439.                 }
  1440.             } else {
  1441.                 if (! $association['isOwningSide']) {
  1442.                     throw InvalidFindByCall::fromInverseSideUsage(
  1443.                         $this->class->name,
  1444.                         $field
  1445.                     );
  1446.                 }
  1447.                 $className $association['inherited'] ?? $this->class->name;
  1448.                 foreach ($association['joinColumns'] as $joinColumn) {
  1449.                     $columns[] = $this->getSQLTableAlias($className) . '.' $this->quoteStrategy->getJoinColumnName($joinColumn$this->class$this->platform);
  1450.                 }
  1451.             }
  1452.             return $columns;
  1453.         }
  1454.         if ($assoc !== null && ! str_contains($field' ') && ! str_contains($field'(')) {
  1455.             // very careless developers could potentially open up this normally hidden api for userland attacks,
  1456.             // therefore checking for spaces and function calls which are not allowed.
  1457.             // found a join column condition, not really a "field"
  1458.             return [$field];
  1459.         }
  1460.         throw UnrecognizedField::byFullyQualifiedName($this->class->name$field);
  1461.     }
  1462.     /**
  1463.      * Gets the conditional SQL fragment used in the WHERE clause when selecting
  1464.      * entities in this persister.
  1465.      *
  1466.      * Subclasses are supposed to override this method if they intend to change
  1467.      * or alter the criteria by which entities are selected.
  1468.      *
  1469.      * @param AssociationMapping|null $assoc
  1470.      * @psalm-param array<string, mixed> $criteria
  1471.      * @psalm-param array<string, mixed>|null $assoc
  1472.      *
  1473.      * @return string
  1474.      */
  1475.     protected function getSelectConditionSQL(array $criteria$assoc null)
  1476.     {
  1477.         $conditions = [];
  1478.         foreach ($criteria as $field => $value) {
  1479.             $conditions[] = $this->getSelectConditionStatementSQL($field$value$assoc);
  1480.         }
  1481.         return implode(' AND '$conditions);
  1482.     }
  1483.     /**
  1484.      * {@inheritDoc}
  1485.      */
  1486.     public function getOneToManyCollection(array $assoc$sourceEntity$offset null$limit null)
  1487.     {
  1488.         $this->switchPersisterContext($offset$limit);
  1489.         $stmt $this->getOneToManyStatement($assoc$sourceEntity$offset$limit);
  1490.         return $this->loadArrayFromResult($assoc$stmt);
  1491.     }
  1492.     /**
  1493.      * {@inheritDoc}
  1494.      */
  1495.     public function loadOneToManyCollection(array $assoc$sourceEntityPersistentCollection $collection)
  1496.     {
  1497.         $stmt $this->getOneToManyStatement($assoc$sourceEntity);
  1498.         return $this->loadCollectionFromStatement($assoc$stmt$collection);
  1499.     }
  1500.     /**
  1501.      * Builds criteria and execute SQL statement to fetch the one to many entities from.
  1502.      *
  1503.      * @param object $sourceEntity
  1504.      * @psalm-param AssociationMapping $assoc
  1505.      */
  1506.     private function getOneToManyStatement(
  1507.         array $assoc,
  1508.         $sourceEntity,
  1509.         ?int $offset null,
  1510.         ?int $limit null
  1511.     ): Result {
  1512.         $this->switchPersisterContext($offset$limit);
  1513.         $criteria    = [];
  1514.         $parameters  = [];
  1515.         $owningAssoc $this->class->associationMappings[$assoc['mappedBy']];
  1516.         $sourceClass $this->em->getClassMetadata($assoc['sourceEntity']);
  1517.         $tableAlias  $this->getSQLTableAlias($owningAssoc['inherited'] ?? $this->class->name);
  1518.         foreach ($owningAssoc['targetToSourceKeyColumns'] as $sourceKeyColumn => $targetKeyColumn) {
  1519.             if ($sourceClass->containsForeignIdentifier) {
  1520.                 $field $sourceClass->getFieldForColumn($sourceKeyColumn);
  1521.                 $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1522.                 if (isset($sourceClass->associationMappings[$field])) {
  1523.                     $value $this->em->getUnitOfWork()->getEntityIdentifier($value);
  1524.                     $value $value[$this->em->getClassMetadata($sourceClass->associationMappings[$field]['targetEntity'])->identifier[0]];
  1525.                 }
  1526.                 $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1527.                 $parameters[]                                   = [
  1528.                     'value' => $value,
  1529.                     'field' => $field,
  1530.                     'class' => $sourceClass,
  1531.                 ];
  1532.                 continue;
  1533.             }
  1534.             $field $sourceClass->fieldNames[$sourceKeyColumn];
  1535.             $value $sourceClass->reflFields[$field]->getValue($sourceEntity);
  1536.             $criteria[$tableAlias '.' $targetKeyColumn] = $value;
  1537.             $parameters[]                                   = [
  1538.                 'value' => $value,
  1539.                 'field' => $field,
  1540.                 'class' => $sourceClass,
  1541.             ];
  1542.         }
  1543.         $sql              $this->getSelectSQL($criteria$assocnull$limit$offset);
  1544.         [$params$types] = $this->expandToManyParameters($parameters);
  1545.         return $this->conn->executeQuery($sql$params$types);
  1546.     }
  1547.     /**
  1548.      * {@inheritDoc}
  1549.      */
  1550.     public function expandParameters($criteria)
  1551.     {
  1552.         $params = [];
  1553.         $types  = [];
  1554.         foreach ($criteria as $field => $value) {
  1555.             if ($value === null) {
  1556.                 continue; // skip null values.
  1557.             }
  1558.             $types  array_merge($types$this->getTypes($field$value$this->class));
  1559.             $params array_merge($params$this->getValues($value));
  1560.         }
  1561.         return [$params$types];
  1562.     }
  1563.     /**
  1564.      * Expands the parameters from the given criteria and use the correct binding types if found,
  1565.      * specialized for OneToMany or ManyToMany associations.
  1566.      *
  1567.      * @param mixed[][] $criteria an array of arrays containing following:
  1568.      *                             - field to which each criterion will be bound
  1569.      *                             - value to be bound
  1570.      *                             - class to which the field belongs to
  1571.      *
  1572.      * @return mixed[][]
  1573.      * @psalm-return array{0: array, 1: list<int|string|null>}
  1574.      */
  1575.     private function expandToManyParameters(array $criteria): array
  1576.     {
  1577.         $params = [];
  1578.         $types  = [];
  1579.         foreach ($criteria as $criterion) {
  1580.             if ($criterion['value'] === null) {
  1581.                 continue; // skip null values.
  1582.             }
  1583.             $types  array_merge($types$this->getTypes($criterion['field'], $criterion['value'], $criterion['class']));
  1584.             $params array_merge($params$this->getValues($criterion['value']));
  1585.         }
  1586.         return [$params$types];
  1587.     }
  1588.     /**
  1589.      * Infers field types to be used by parameter type casting.
  1590.      *
  1591.      * @param mixed $value
  1592.      *
  1593.      * @return int[]|null[]|string[]
  1594.      * @psalm-return list<int|string|null>
  1595.      *
  1596.      * @throws QueryException
  1597.      */
  1598.     private function getTypes(string $field$valueClassMetadata $class): array
  1599.     {
  1600.         $types = [];
  1601.         switch (true) {
  1602.             case isset($class->fieldMappings[$field]):
  1603.                 $types array_merge($types, [$class->fieldMappings[$field]['type']]);
  1604.                 break;
  1605.             case isset($class->associationMappings[$field]):
  1606.                 $assoc $class->associationMappings[$field];
  1607.                 $class $this->em->getClassMetadata($assoc['targetEntity']);
  1608.                 if (! $assoc['isOwningSide']) {
  1609.                     $assoc $class->associationMappings[$assoc['mappedBy']];
  1610.                     $class $this->em->getClassMetadata($assoc['targetEntity']);
  1611.                 }
  1612.                 $columns $assoc['type'] === ClassMetadata::MANY_TO_MANY
  1613.                     $assoc['relationToTargetKeyColumns']
  1614.                     : $assoc['sourceToTargetKeyColumns'];
  1615.                 foreach ($columns as $column) {
  1616.                     $types[] = PersisterHelper::getTypeOfColumn($column$class$this->em);
  1617.                 }
  1618.                 break;
  1619.             default:
  1620.                 $types[] = null;
  1621.                 break;
  1622.         }
  1623.         if (is_array($value)) {
  1624.             return array_map(static function ($type) {
  1625.                 $type Type::getType($type);
  1626.                 return $type->getBindingType() + Connection::ARRAY_PARAM_OFFSET;
  1627.             }, $types);
  1628.         }
  1629.         return $types;
  1630.     }
  1631.     /**
  1632.      * Retrieves the parameters that identifies a value.
  1633.      *
  1634.      * @param mixed $value
  1635.      *
  1636.      * @return mixed[]
  1637.      */
  1638.     private function getValues($value): array
  1639.     {
  1640.         if (is_array($value)) {
  1641.             $newValue = [];
  1642.             foreach ($value as $itemValue) {
  1643.                 $newValue array_merge($newValue$this->getValues($itemValue));
  1644.             }
  1645.             return [$newValue];
  1646.         }
  1647.         return $this->getIndividualValue($value);
  1648.     }
  1649.     /**
  1650.      * Retrieves an individual parameter value.
  1651.      *
  1652.      * @param mixed $value
  1653.      *
  1654.      * @psalm-return list<mixed>
  1655.      */
  1656.     private function getIndividualValue($value): array
  1657.     {
  1658.         if (! is_object($value)) {
  1659.             return [$value];
  1660.         }
  1661.         if ($value instanceof BackedEnum) {
  1662.             return [$value->value];
  1663.         }
  1664.         $valueClass DefaultProxyClassNameResolver::getClass($value);
  1665.         if ($this->em->getMetadataFactory()->isTransient($valueClass)) {
  1666.             return [$value];
  1667.         }
  1668.         $class $this->em->getClassMetadata($valueClass);
  1669.         if ($class->isIdentifierComposite) {
  1670.             $newValue = [];
  1671.             foreach ($class->getIdentifierValues($value) as $innerValue) {
  1672.                 $newValue array_merge($newValue$this->getValues($innerValue));
  1673.             }
  1674.             return $newValue;
  1675.         }
  1676.         return [$this->em->getUnitOfWork()->getSingleIdentifierValue($value)];
  1677.     }
  1678.     /**
  1679.      * {@inheritDoc}
  1680.      */
  1681.     public function exists($entity, ?Criteria $extraConditions null)
  1682.     {
  1683.         $criteria $this->class->getIdentifierValues($entity);
  1684.         if (! $criteria) {
  1685.             return false;
  1686.         }
  1687.         $alias $this->getSQLTableAlias($this->class->name);
  1688.         $sql 'SELECT 1 '
  1689.              $this->getLockTablesSql(LockMode::NONE)
  1690.              . ' WHERE ' $this->getSelectConditionSQL($criteria);
  1691.         [$params$types] = $this->expandParameters($criteria);
  1692.         if ($extraConditions !== null) {
  1693.             $sql                             .= ' AND ' $this->getSelectConditionCriteriaSQL($extraConditions);
  1694.             [$criteriaParams$criteriaTypes] = $this->expandCriteriaParameters($extraConditions);
  1695.             $params array_merge($params$criteriaParams);
  1696.             $types  array_merge($types$criteriaTypes);
  1697.         }
  1698.         $filterSql $this->generateFilterConditionSQL($this->class$alias);
  1699.         if ($filterSql) {
  1700.             $sql .= ' AND ' $filterSql;
  1701.         }
  1702.         return (bool) $this->conn->fetchOne($sql$params$types);
  1703.     }
  1704.     /**
  1705.      * Generates the appropriate join SQL for the given join column.
  1706.      *
  1707.      * @param array[] $joinColumns The join columns definition of an association.
  1708.      * @psalm-param array<array<string, mixed>> $joinColumns
  1709.      *
  1710.      * @return string LEFT JOIN if one of the columns is nullable, INNER JOIN otherwise.
  1711.      */
  1712.     protected function getJoinSQLForJoinColumns($joinColumns)
  1713.     {
  1714.         // if one of the join columns is nullable, return left join
  1715.         foreach ($joinColumns as $joinColumn) {
  1716.             if (! isset($joinColumn['nullable']) || $joinColumn['nullable']) {
  1717.                 return 'LEFT JOIN';
  1718.             }
  1719.         }
  1720.         return 'INNER JOIN';
  1721.     }
  1722.     /**
  1723.      * @param string $columnName
  1724.      *
  1725.      * @return string
  1726.      */
  1727.     public function getSQLColumnAlias($columnName)
  1728.     {
  1729.         return $this->quoteStrategy->getColumnAlias($columnName$this->currentPersisterContext->sqlAliasCounter++, $this->platform);
  1730.     }
  1731.     /**
  1732.      * Generates the filter SQL for a given entity and table alias.
  1733.      *
  1734.      * @param ClassMetadata $targetEntity     Metadata of the target entity.
  1735.      * @param string        $targetTableAlias The table alias of the joined/selected table.
  1736.      *
  1737.      * @return string The SQL query part to add to a query.
  1738.      */
  1739.     protected function generateFilterConditionSQL(ClassMetadata $targetEntity$targetTableAlias)
  1740.     {
  1741.         $filterClauses = [];
  1742.         foreach ($this->em->getFilters()->getEnabledFilters() as $filter) {
  1743.             $filterExpr $filter->addFilterConstraint($targetEntity$targetTableAlias);
  1744.             if ($filterExpr !== '') {
  1745.                 $filterClauses[] = '(' $filterExpr ')';
  1746.             }
  1747.         }
  1748.         $sql implode(' AND '$filterClauses);
  1749.         return $sql '(' $sql ')' ''// Wrap again to avoid "X or Y and FilterConditionSQL"
  1750.     }
  1751.     /**
  1752.      * Switches persister context according to current query offset/limits
  1753.      *
  1754.      * This is due to the fact that to-many associations cannot be fetch-joined when a limit is involved
  1755.      *
  1756.      * @param int|null $offset
  1757.      * @param int|null $limit
  1758.      *
  1759.      * @return void
  1760.      */
  1761.     protected function switchPersisterContext($offset$limit)
  1762.     {
  1763.         if ($offset === null && $limit === null) {
  1764.             $this->currentPersisterContext $this->noLimitsContext;
  1765.             return;
  1766.         }
  1767.         $this->currentPersisterContext $this->limitsHandlingContext;
  1768.     }
  1769.     /**
  1770.      * @return string[]
  1771.      * @psalm-return list<string>
  1772.      */
  1773.     protected function getClassIdentifiersTypes(ClassMetadata $class): array
  1774.     {
  1775.         $entityManager $this->em;
  1776.         return array_map(
  1777.             static function ($fieldName) use ($class$entityManager): string {
  1778.                 $types PersisterHelper::getTypeOfField($fieldName$class$entityManager);
  1779.                 assert(isset($types[0]));
  1780.                 return $types[0];
  1781.             },
  1782.             $class->identifier
  1783.         );
  1784.     }
  1785. }