vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php line 1218

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