vendor/doctrine/dbal/src/Connection.php line 1648

Open in your IDE?
  1. <?php
  2. namespace Doctrine\DBAL;
  3. use Closure;
  4. use Doctrine\Common\EventManager;
  5. use Doctrine\DBAL\Cache\ArrayResult;
  6. use Doctrine\DBAL\Cache\CacheException;
  7. use Doctrine\DBAL\Cache\QueryCacheProfile;
  8. use Doctrine\DBAL\Driver\API\ExceptionConverter;
  9. use Doctrine\DBAL\Driver\Connection as DriverConnection;
  10. use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
  11. use Doctrine\DBAL\Driver\Statement as DriverStatement;
  12. use Doctrine\DBAL\Event\TransactionBeginEventArgs;
  13. use Doctrine\DBAL\Event\TransactionCommitEventArgs;
  14. use Doctrine\DBAL\Event\TransactionRollBackEventArgs;
  15. use Doctrine\DBAL\Exception\ConnectionLost;
  16. use Doctrine\DBAL\Exception\DriverException;
  17. use Doctrine\DBAL\Exception\InvalidArgumentException;
  18. use Doctrine\DBAL\Platforms\AbstractPlatform;
  19. use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
  20. use Doctrine\DBAL\Query\QueryBuilder;
  21. use Doctrine\DBAL\Schema\AbstractSchemaManager;
  22. use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory;
  23. use Doctrine\DBAL\Schema\LegacySchemaManagerFactory;
  24. use Doctrine\DBAL\Schema\SchemaManagerFactory;
  25. use Doctrine\DBAL\SQL\Parser;
  26. use Doctrine\DBAL\Types\Type;
  27. use Doctrine\Deprecations\Deprecation;
  28. use LogicException;
  29. use SensitiveParameter;
  30. use Throwable;
  31. use Traversable;
  32. use function array_key_exists;
  33. use function assert;
  34. use function count;
  35. use function get_class;
  36. use function implode;
  37. use function is_int;
  38. use function is_string;
  39. use function key;
  40. use function method_exists;
  41. use function sprintf;
  42. /**
  43.  * A database abstraction-level connection that implements features like events, transaction isolation levels,
  44.  * configuration, emulated transaction nesting, lazy connecting and more.
  45.  *
  46.  * @psalm-import-type Params from DriverManager
  47.  * @psalm-consistent-constructor
  48.  */
  49. class Connection
  50. {
  51.     /**
  52.      * Represents an array of ints to be expanded by Doctrine SQL parsing.
  53.      *
  54.      * @deprecated Use {@see ArrayParameterType::INTEGER} instead.
  55.      */
  56.     public const PARAM_INT_ARRAY ArrayParameterType::INTEGER;
  57.     /**
  58.      * Represents an array of strings to be expanded by Doctrine SQL parsing.
  59.      *
  60.      * @deprecated Use {@see ArrayParameterType::STRING} instead.
  61.      */
  62.     public const PARAM_STR_ARRAY ArrayParameterType::STRING;
  63.     /**
  64.      * Represents an array of ascii strings to be expanded by Doctrine SQL parsing.
  65.      *
  66.      * @deprecated Use {@see ArrayParameterType::ASCII} instead.
  67.      */
  68.     public const PARAM_ASCII_STR_ARRAY ArrayParameterType::ASCII;
  69.     /**
  70.      * Offset by which PARAM_* constants are detected as arrays of the param type.
  71.      *
  72.      * @internal Should be used only within the wrapper layer.
  73.      */
  74.     public const ARRAY_PARAM_OFFSET 100;
  75.     /**
  76.      * The wrapped driver connection.
  77.      *
  78.      * @var DriverConnection|null
  79.      */
  80.     protected $_conn;
  81.     /** @var Configuration */
  82.     protected $_config;
  83.     /**
  84.      * @deprecated
  85.      *
  86.      * @var EventManager
  87.      */
  88.     protected $_eventManager;
  89.     /**
  90.      * @deprecated Use {@see createExpressionBuilder()} instead.
  91.      *
  92.      * @var ExpressionBuilder
  93.      */
  94.     protected $_expr;
  95.     /**
  96.      * The current auto-commit mode of this connection.
  97.      */
  98.     private bool $autoCommit true;
  99.     /**
  100.      * The transaction nesting level.
  101.      */
  102.     private int $transactionNestingLevel 0;
  103.     /**
  104.      * The currently active transaction isolation level or NULL before it has been determined.
  105.      *
  106.      * @var TransactionIsolationLevel::*|null
  107.      */
  108.     private $transactionIsolationLevel;
  109.     /**
  110.      * If nested transactions should use savepoints.
  111.      */
  112.     private bool $nestTransactionsWithSavepoints false;
  113.     /**
  114.      * The parameters used during creation of the Connection instance.
  115.      *
  116.      * @var array<string,mixed>
  117.      * @psalm-var Params
  118.      */
  119.     private array $params;
  120.     /**
  121.      * The database platform object used by the connection or NULL before it's initialized.
  122.      */
  123.     private ?AbstractPlatform $platform null;
  124.     private ?ExceptionConverter $exceptionConverter null;
  125.     private ?Parser $parser                         null;
  126.     /**
  127.      * The schema manager.
  128.      *
  129.      * @deprecated Use {@see createSchemaManager()} instead.
  130.      *
  131.      * @var AbstractSchemaManager|null
  132.      */
  133.     protected $_schemaManager;
  134.     /**
  135.      * The used DBAL driver.
  136.      *
  137.      * @var Driver
  138.      */
  139.     protected $_driver;
  140.     /**
  141.      * Flag that indicates whether the current transaction is marked for rollback only.
  142.      */
  143.     private bool $isRollbackOnly false;
  144.     private SchemaManagerFactory $schemaManagerFactory;
  145.     /**
  146.      * Initializes a new instance of the Connection class.
  147.      *
  148.      * @internal The connection can be only instantiated by the driver manager.
  149.      *
  150.      * @param array<string,mixed> $params       The connection parameters.
  151.      * @param Driver              $driver       The driver to use.
  152.      * @param Configuration|null  $config       The configuration, optional.
  153.      * @param EventManager|null   $eventManager The event manager, optional.
  154.      * @psalm-param Params $params
  155.      *
  156.      * @throws Exception
  157.      */
  158.     public function __construct(
  159.         #[SensitiveParameter]
  160.         array $params,
  161.         Driver $driver,
  162.         ?Configuration $config null,
  163.         ?EventManager $eventManager null
  164.     ) {
  165.         $this->_driver $driver;
  166.         $this->params  $params;
  167.         // Create default config and event manager if none given
  168.         $config       ??= new Configuration();
  169.         $eventManager ??= new EventManager();
  170.         $this->_config       $config;
  171.         $this->_eventManager $eventManager;
  172.         if (isset($params['platform'])) {
  173.             if (! $params['platform'] instanceof Platforms\AbstractPlatform) {
  174.                 throw Exception::invalidPlatformType($params['platform']);
  175.             }
  176.             Deprecation::trigger(
  177.                 'doctrine/dbal',
  178.                 'https://github.com/doctrine/dbal/pull/5699',
  179.                 'The "platform" connection parameter is deprecated.'
  180.                     ' Use a driver middleware that would instantiate the platform instead.',
  181.             );
  182.             $this->platform $params['platform'];
  183.             $this->platform->setEventManager($this->_eventManager);
  184.         }
  185.         $this->_expr $this->createExpressionBuilder();
  186.         $this->autoCommit $config->getAutoCommit();
  187.         $schemaManagerFactory $config->getSchemaManagerFactory();
  188.         if ($schemaManagerFactory === null) {
  189.             Deprecation::trigger(
  190.                 'doctrine/dbal',
  191.                 'https://github.com/doctrine/dbal/issues/5812',
  192.                 'Not configuring a schema manager factory is deprecated.'
  193.                     ' Use %s which is going to be the default in DBAL 4.',
  194.                 DefaultSchemaManagerFactory::class,
  195.             );
  196.             $schemaManagerFactory = new LegacySchemaManagerFactory();
  197.         }
  198.         $this->schemaManagerFactory $schemaManagerFactory;
  199.     }
  200.     /**
  201.      * Gets the parameters used during instantiation.
  202.      *
  203.      * @internal
  204.      *
  205.      * @return array<string,mixed>
  206.      * @psalm-return Params
  207.      */
  208.     public function getParams()
  209.     {
  210.         return $this->params;
  211.     }
  212.     /**
  213.      * Gets the name of the currently selected database.
  214.      *
  215.      * @return string|null The name of the database or NULL if a database is not selected.
  216.      *                     The platforms which don't support the concept of a database (e.g. embedded databases)
  217.      *                     must always return a string as an indicator of an implicitly selected database.
  218.      *
  219.      * @throws Exception
  220.      */
  221.     public function getDatabase()
  222.     {
  223.         $platform $this->getDatabasePlatform();
  224.         $query    $platform->getDummySelectSQL($platform->getCurrentDatabaseExpression());
  225.         $database $this->fetchOne($query);
  226.         assert(is_string($database) || $database === null);
  227.         return $database;
  228.     }
  229.     /**
  230.      * Gets the DBAL driver instance.
  231.      *
  232.      * @return Driver
  233.      */
  234.     public function getDriver()
  235.     {
  236.         return $this->_driver;
  237.     }
  238.     /**
  239.      * Gets the Configuration used by the Connection.
  240.      *
  241.      * @return Configuration
  242.      */
  243.     public function getConfiguration()
  244.     {
  245.         return $this->_config;
  246.     }
  247.     /**
  248.      * Gets the EventManager used by the Connection.
  249.      *
  250.      * @deprecated
  251.      *
  252.      * @return EventManager
  253.      */
  254.     public function getEventManager()
  255.     {
  256.         Deprecation::triggerIfCalledFromOutside(
  257.             'doctrine/dbal',
  258.             'https://github.com/doctrine/dbal/issues/5784',
  259.             '%s is deprecated.',
  260.             __METHOD__,
  261.         );
  262.         return $this->_eventManager;
  263.     }
  264.     /**
  265.      * Gets the DatabasePlatform for the connection.
  266.      *
  267.      * @return AbstractPlatform
  268.      *
  269.      * @throws Exception
  270.      */
  271.     public function getDatabasePlatform()
  272.     {
  273.         if ($this->platform === null) {
  274.             $this->platform $this->detectDatabasePlatform();
  275.             $this->platform->setEventManager($this->_eventManager);
  276.         }
  277.         return $this->platform;
  278.     }
  279.     /**
  280.      * Creates an expression builder for the connection.
  281.      */
  282.     public function createExpressionBuilder(): ExpressionBuilder
  283.     {
  284.         return new ExpressionBuilder($this);
  285.     }
  286.     /**
  287.      * Gets the ExpressionBuilder for the connection.
  288.      *
  289.      * @deprecated Use {@see createExpressionBuilder()} instead.
  290.      *
  291.      * @return ExpressionBuilder
  292.      */
  293.     public function getExpressionBuilder()
  294.     {
  295.         Deprecation::triggerIfCalledFromOutside(
  296.             'doctrine/dbal',
  297.             'https://github.com/doctrine/dbal/issues/4515',
  298.             'Connection::getExpressionBuilder() is deprecated,'
  299.                 ' use Connection::createExpressionBuilder() instead.',
  300.         );
  301.         return $this->_expr;
  302.     }
  303.     /**
  304.      * Establishes the connection with the database.
  305.      *
  306.      * @internal This method will be made protected in DBAL 4.0.
  307.      *
  308.      * @return bool TRUE if the connection was successfully established, FALSE if
  309.      *              the connection is already open.
  310.      *
  311.      * @throws Exception
  312.      *
  313.      * @psalm-assert !null $this->_conn
  314.      */
  315.     public function connect()
  316.     {
  317.         Deprecation::triggerIfCalledFromOutside(
  318.             'doctrine/dbal',
  319.             'https://github.com/doctrine/dbal/issues/4966',
  320.             'Public access to Connection::connect() is deprecated.',
  321.         );
  322.         if ($this->_conn !== null) {
  323.             return false;
  324.         }
  325.         try {
  326.             $this->_conn $this->_driver->connect($this->params);
  327.         } catch (Driver\Exception $e) {
  328.             throw $this->convertException($e);
  329.         }
  330.         if ($this->autoCommit === false) {
  331.             $this->beginTransaction();
  332.         }
  333.         if ($this->_eventManager->hasListeners(Events::postConnect)) {
  334.             Deprecation::trigger(
  335.                 'doctrine/dbal',
  336.                 'https://github.com/doctrine/dbal/issues/5784',
  337.                 'Subscribing to %s events is deprecated. Implement a middleware instead.',
  338.                 Events::postConnect,
  339.             );
  340.             $eventArgs = new Event\ConnectionEventArgs($this);
  341.             $this->_eventManager->dispatchEvent(Events::postConnect$eventArgs);
  342.         }
  343.         return true;
  344.     }
  345.     /**
  346.      * Detects and sets the database platform.
  347.      *
  348.      * Evaluates custom platform class and version in order to set the correct platform.
  349.      *
  350.      * @throws Exception If an invalid platform was specified for this connection.
  351.      */
  352.     private function detectDatabasePlatform(): AbstractPlatform
  353.     {
  354.         $version $this->getDatabasePlatformVersion();
  355.         if ($version !== null) {
  356.             assert($this->_driver instanceof VersionAwarePlatformDriver);
  357.             return $this->_driver->createDatabasePlatformForVersion($version);
  358.         }
  359.         return $this->_driver->getDatabasePlatform();
  360.     }
  361.     /**
  362.      * Returns the version of the related platform if applicable.
  363.      *
  364.      * Returns null if either the driver is not capable to create version
  365.      * specific platform instances, no explicit server version was specified
  366.      * or the underlying driver connection cannot determine the platform
  367.      * version without having to query it (performance reasons).
  368.      *
  369.      * @return string|null
  370.      *
  371.      * @throws Throwable
  372.      */
  373.     private function getDatabasePlatformVersion()
  374.     {
  375.         // Driver does not support version specific platforms.
  376.         if (! $this->_driver instanceof VersionAwarePlatformDriver) {
  377.             return null;
  378.         }
  379.         // Explicit platform version requested (supersedes auto-detection).
  380.         if (isset($this->params['serverVersion'])) {
  381.             return $this->params['serverVersion'];
  382.         }
  383.         // If not connected, we need to connect now to determine the platform version.
  384.         if ($this->_conn === null) {
  385.             try {
  386.                 $this->connect();
  387.             } catch (Exception $originalException) {
  388.                 if (! isset($this->params['dbname'])) {
  389.                     throw $originalException;
  390.                 }
  391.                 Deprecation::trigger(
  392.                     'doctrine/dbal',
  393.                     'https://github.com/doctrine/dbal/pull/5707',
  394.                     'Relying on a fallback connection used to determine the database platform while connecting'
  395.                         ' to a non-existing database is deprecated. Either use an existing database name in'
  396.                         ' connection parameters or omit the database name if the platform'
  397.                         ' and the server configuration allow that.',
  398.                 );
  399.                 // The database to connect to might not yet exist.
  400.                 // Retry detection without database name connection parameter.
  401.                 $params $this->params;
  402.                 unset($this->params['dbname']);
  403.                 try {
  404.                     $this->connect();
  405.                 } catch (Exception $fallbackException) {
  406.                     // Either the platform does not support database-less connections
  407.                     // or something else went wrong.
  408.                     throw $originalException;
  409.                 } finally {
  410.                     $this->params $params;
  411.                 }
  412.                 $serverVersion $this->getServerVersion();
  413.                 // Close "temporary" connection to allow connecting to the real database again.
  414.                 $this->close();
  415.                 return $serverVersion;
  416.             }
  417.         }
  418.         return $this->getServerVersion();
  419.     }
  420.     /**
  421.      * Returns the database server version if the underlying driver supports it.
  422.      *
  423.      * @return string|null
  424.      *
  425.      * @throws Exception
  426.      */
  427.     private function getServerVersion()
  428.     {
  429.         $connection $this->getWrappedConnection();
  430.         // Automatic platform version detection.
  431.         if ($connection instanceof ServerInfoAwareConnection) {
  432.             try {
  433.                 return $connection->getServerVersion();
  434.             } catch (Driver\Exception $e) {
  435.                 throw $this->convertException($e);
  436.             }
  437.         }
  438.         Deprecation::trigger(
  439.             'doctrine/dbal',
  440.             'https://github.com/doctrine/dbal/pull/4750',
  441.             'Not implementing the ServerInfoAwareConnection interface in %s is deprecated',
  442.             get_class($connection),
  443.         );
  444.         // Unable to detect platform version.
  445.         return null;
  446.     }
  447.     /**
  448.      * Returns the current auto-commit mode for this connection.
  449.      *
  450.      * @see    setAutoCommit
  451.      *
  452.      * @return bool True if auto-commit mode is currently enabled for this connection, false otherwise.
  453.      */
  454.     public function isAutoCommit()
  455.     {
  456.         return $this->autoCommit === true;
  457.     }
  458.     /**
  459.      * Sets auto-commit mode for this connection.
  460.      *
  461.      * If a connection is in auto-commit mode, then all its SQL statements will be executed and committed as individual
  462.      * transactions. Otherwise, its SQL statements are grouped into transactions that are terminated by a call to either
  463.      * the method commit or the method rollback. By default, new connections are in auto-commit mode.
  464.      *
  465.      * NOTE: If this method is called during a transaction and the auto-commit mode is changed, the transaction is
  466.      * committed. If this method is called and the auto-commit mode is not changed, the call is a no-op.
  467.      *
  468.      * @see   isAutoCommit
  469.      *
  470.      * @param bool $autoCommit True to enable auto-commit mode; false to disable it.
  471.      *
  472.      * @return void
  473.      */
  474.     public function setAutoCommit($autoCommit)
  475.     {
  476.         $autoCommit = (bool) $autoCommit;
  477.         // Mode not changed, no-op.
  478.         if ($autoCommit === $this->autoCommit) {
  479.             return;
  480.         }
  481.         $this->autoCommit $autoCommit;
  482.         // Commit all currently active transactions if any when switching auto-commit mode.
  483.         if ($this->_conn === null || $this->transactionNestingLevel === 0) {
  484.             return;
  485.         }
  486.         $this->commitAll();
  487.     }
  488.     /**
  489.      * Prepares and executes an SQL query and returns the first row of the result
  490.      * as an associative array.
  491.      *
  492.      * @param string                                                               $query  SQL query
  493.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  494.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  495.      *
  496.      * @return array<string, mixed>|false False is returned if no rows are found.
  497.      *
  498.      * @throws Exception
  499.      */
  500.     public function fetchAssociative(string $query, array $params = [], array $types = [])
  501.     {
  502.         return $this->executeQuery($query$params$types)->fetchAssociative();
  503.     }
  504.     /**
  505.      * Prepares and executes an SQL query and returns the first row of the result
  506.      * as a numerically indexed array.
  507.      *
  508.      * @param string                                                               $query  SQL query
  509.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  510.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  511.      *
  512.      * @return list<mixed>|false False is returned if no rows are found.
  513.      *
  514.      * @throws Exception
  515.      */
  516.     public function fetchNumeric(string $query, array $params = [], array $types = [])
  517.     {
  518.         return $this->executeQuery($query$params$types)->fetchNumeric();
  519.     }
  520.     /**
  521.      * Prepares and executes an SQL query and returns the value of a single column
  522.      * of the first row of the result.
  523.      *
  524.      * @param string                                                               $query  SQL query
  525.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  526.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  527.      *
  528.      * @return mixed|false False is returned if no rows are found.
  529.      *
  530.      * @throws Exception
  531.      */
  532.     public function fetchOne(string $query, array $params = [], array $types = [])
  533.     {
  534.         return $this->executeQuery($query$params$types)->fetchOne();
  535.     }
  536.     /**
  537.      * Whether an actual connection to the database is established.
  538.      *
  539.      * @return bool
  540.      */
  541.     public function isConnected()
  542.     {
  543.         return $this->_conn !== null;
  544.     }
  545.     /**
  546.      * Checks whether a transaction is currently active.
  547.      *
  548.      * @return bool TRUE if a transaction is currently active, FALSE otherwise.
  549.      */
  550.     public function isTransactionActive()
  551.     {
  552.         return $this->transactionNestingLevel 0;
  553.     }
  554.     /**
  555.      * Adds condition based on the criteria to the query components
  556.      *
  557.      * @param array<string,mixed> $criteria   Map of key columns to their values
  558.      * @param string[]            $columns    Column names
  559.      * @param mixed[]             $values     Column values
  560.      * @param string[]            $conditions Key conditions
  561.      *
  562.      * @throws Exception
  563.      */
  564.     private function addCriteriaCondition(
  565.         array $criteria,
  566.         array &$columns,
  567.         array &$values,
  568.         array &$conditions
  569.     ): void {
  570.         $platform $this->getDatabasePlatform();
  571.         foreach ($criteria as $columnName => $value) {
  572.             if ($value === null) {
  573.                 $conditions[] = $platform->getIsNullExpression($columnName);
  574.                 continue;
  575.             }
  576.             $columns[]    = $columnName;
  577.             $values[]     = $value;
  578.             $conditions[] = $columnName ' = ?';
  579.         }
  580.     }
  581.     /**
  582.      * Executes an SQL DELETE statement on a table.
  583.      *
  584.      * Table expression and columns are not escaped and are not safe for user-input.
  585.      *
  586.      * @param string                                                               $table    Table name
  587.      * @param array<string, mixed>                                                 $criteria Deletion criteria
  588.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types    Parameter types
  589.      *
  590.      * @return int|string The number of affected rows.
  591.      *
  592.      * @throws Exception
  593.      */
  594.     public function delete($table, array $criteria, array $types = [])
  595.     {
  596.         if (count($criteria) === 0) {
  597.             throw InvalidArgumentException::fromEmptyCriteria();
  598.         }
  599.         $columns $values $conditions = [];
  600.         $this->addCriteriaCondition($criteria$columns$values$conditions);
  601.         return $this->executeStatement(
  602.             'DELETE FROM ' $table ' WHERE ' implode(' AND '$conditions),
  603.             $values,
  604.             is_string(key($types)) ? $this->extractTypeValues($columns$types) : $types,
  605.         );
  606.     }
  607.     /**
  608.      * Closes the connection.
  609.      *
  610.      * @return void
  611.      */
  612.     public function close()
  613.     {
  614.         $this->_conn                   null;
  615.         $this->transactionNestingLevel 0;
  616.     }
  617.     /**
  618.      * Sets the transaction isolation level.
  619.      *
  620.      * @param TransactionIsolationLevel::* $level The level to set.
  621.      *
  622.      * @return int|string
  623.      *
  624.      * @throws Exception
  625.      */
  626.     public function setTransactionIsolation($level)
  627.     {
  628.         $this->transactionIsolationLevel $level;
  629.         return $this->executeStatement($this->getDatabasePlatform()->getSetTransactionIsolationSQL($level));
  630.     }
  631.     /**
  632.      * Gets the currently active transaction isolation level.
  633.      *
  634.      * @return TransactionIsolationLevel::* The current transaction isolation level.
  635.      *
  636.      * @throws Exception
  637.      */
  638.     public function getTransactionIsolation()
  639.     {
  640.         return $this->transactionIsolationLevel ??= $this->getDatabasePlatform()->getDefaultTransactionIsolationLevel();
  641.     }
  642.     /**
  643.      * Executes an SQL UPDATE statement on a table.
  644.      *
  645.      * Table expression and columns are not escaped and are not safe for user-input.
  646.      *
  647.      * @param string                                                               $table    Table name
  648.      * @param array<string, mixed>                                                 $data     Column-value pairs
  649.      * @param array<string, mixed>                                                 $criteria Update criteria
  650.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types    Parameter types
  651.      *
  652.      * @return int|string The number of affected rows.
  653.      *
  654.      * @throws Exception
  655.      */
  656.     public function update($table, array $data, array $criteria, array $types = [])
  657.     {
  658.         $columns $values $conditions $set = [];
  659.         foreach ($data as $columnName => $value) {
  660.             $columns[] = $columnName;
  661.             $values[]  = $value;
  662.             $set[]     = $columnName ' = ?';
  663.         }
  664.         $this->addCriteriaCondition($criteria$columns$values$conditions);
  665.         if (is_string(key($types))) {
  666.             $types $this->extractTypeValues($columns$types);
  667.         }
  668.         $sql 'UPDATE ' $table ' SET ' implode(', '$set)
  669.                 . ' WHERE ' implode(' AND '$conditions);
  670.         return $this->executeStatement($sql$values$types);
  671.     }
  672.     /**
  673.      * Inserts a table row with specified data.
  674.      *
  675.      * Table expression and columns are not escaped and are not safe for user-input.
  676.      *
  677.      * @param string                                                               $table Table name
  678.      * @param array<string, mixed>                                                 $data  Column-value pairs
  679.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types Parameter types
  680.      *
  681.      * @return int|string The number of affected rows.
  682.      *
  683.      * @throws Exception
  684.      */
  685.     public function insert($table, array $data, array $types = [])
  686.     {
  687.         if (count($data) === 0) {
  688.             return $this->executeStatement('INSERT INTO ' $table ' () VALUES ()');
  689.         }
  690.         $columns = [];
  691.         $values  = [];
  692.         $set     = [];
  693.         foreach ($data as $columnName => $value) {
  694.             $columns[] = $columnName;
  695.             $values[]  = $value;
  696.             $set[]     = '?';
  697.         }
  698.         return $this->executeStatement(
  699.             'INSERT INTO ' $table ' (' implode(', '$columns) . ')' .
  700.             ' VALUES (' implode(', '$set) . ')',
  701.             $values,
  702.             is_string(key($types)) ? $this->extractTypeValues($columns$types) : $types,
  703.         );
  704.     }
  705.     /**
  706.      * Extract ordered type list from an ordered column list and type map.
  707.      *
  708.      * @param array<int, string>                                                   $columnList
  709.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  710.      *
  711.      * @return array<int, int|string|Type|null>|array<string, int|string|Type|null>
  712.      */
  713.     private function extractTypeValues(array $columnList, array $types): array
  714.     {
  715.         $typeValues = [];
  716.         foreach ($columnList as $columnName) {
  717.             $typeValues[] = $types[$columnName] ?? ParameterType::STRING;
  718.         }
  719.         return $typeValues;
  720.     }
  721.     /**
  722.      * Quotes a string so it can be safely used as a table or column name, even if
  723.      * it is a reserved name.
  724.      *
  725.      * Delimiting style depends on the underlying database platform that is being used.
  726.      *
  727.      * NOTE: Just because you CAN use quoted identifiers does not mean
  728.      * you SHOULD use them. In general, they end up causing way more
  729.      * problems than they solve.
  730.      *
  731.      * @param string $str The name to be quoted.
  732.      *
  733.      * @return string The quoted name.
  734.      */
  735.     public function quoteIdentifier($str)
  736.     {
  737.         return $this->getDatabasePlatform()->quoteIdentifier($str);
  738.     }
  739.     /**
  740.      * The usage of this method is discouraged. Use prepared statements
  741.      * or {@see AbstractPlatform::quoteStringLiteral()} instead.
  742.      *
  743.      * @param mixed                $value
  744.      * @param int|string|Type|null $type
  745.      *
  746.      * @return mixed
  747.      */
  748.     public function quote($value$type ParameterType::STRING)
  749.     {
  750.         $connection $this->getWrappedConnection();
  751.         [$value$bindingType] = $this->getBindingInfo($value$type);
  752.         return $connection->quote($value$bindingType);
  753.     }
  754.     /**
  755.      * Prepares and executes an SQL query and returns the result as an array of numeric arrays.
  756.      *
  757.      * @param string                                                               $query  SQL query
  758.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  759.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  760.      *
  761.      * @return list<list<mixed>>
  762.      *
  763.      * @throws Exception
  764.      */
  765.     public function fetchAllNumeric(string $query, array $params = [], array $types = []): array
  766.     {
  767.         return $this->executeQuery($query$params$types)->fetchAllNumeric();
  768.     }
  769.     /**
  770.      * Prepares and executes an SQL query and returns the result as an array of associative arrays.
  771.      *
  772.      * @param string                                                               $query  SQL query
  773.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  774.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  775.      *
  776.      * @return list<array<string,mixed>>
  777.      *
  778.      * @throws Exception
  779.      */
  780.     public function fetchAllAssociative(string $query, array $params = [], array $types = []): array
  781.     {
  782.         return $this->executeQuery($query$params$types)->fetchAllAssociative();
  783.     }
  784.     /**
  785.      * Prepares and executes an SQL query and returns the result as an associative array with the keys
  786.      * mapped to the first column and the values mapped to the second column.
  787.      *
  788.      * @param string                                                               $query  SQL query
  789.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  790.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  791.      *
  792.      * @return array<mixed,mixed>
  793.      *
  794.      * @throws Exception
  795.      */
  796.     public function fetchAllKeyValue(string $query, array $params = [], array $types = []): array
  797.     {
  798.         return $this->executeQuery($query$params$types)->fetchAllKeyValue();
  799.     }
  800.     /**
  801.      * Prepares and executes an SQL query and returns the result as an associative array with the keys mapped
  802.      * to the first column and the values being an associative array representing the rest of the columns
  803.      * and their values.
  804.      *
  805.      * @param string                                                               $query  SQL query
  806.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  807.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  808.      *
  809.      * @return array<mixed,array<string,mixed>>
  810.      *
  811.      * @throws Exception
  812.      */
  813.     public function fetchAllAssociativeIndexed(string $query, array $params = [], array $types = []): array
  814.     {
  815.         return $this->executeQuery($query$params$types)->fetchAllAssociativeIndexed();
  816.     }
  817.     /**
  818.      * Prepares and executes an SQL query and returns the result as an array of the first column values.
  819.      *
  820.      * @param string                                                               $query  SQL query
  821.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  822.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  823.      *
  824.      * @return list<mixed>
  825.      *
  826.      * @throws Exception
  827.      */
  828.     public function fetchFirstColumn(string $query, array $params = [], array $types = []): array
  829.     {
  830.         return $this->executeQuery($query$params$types)->fetchFirstColumn();
  831.     }
  832.     /**
  833.      * Prepares and executes an SQL query and returns the result as an iterator over rows represented as numeric arrays.
  834.      *
  835.      * @param string                                                               $query  SQL query
  836.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  837.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  838.      *
  839.      * @return Traversable<int,list<mixed>>
  840.      *
  841.      * @throws Exception
  842.      */
  843.     public function iterateNumeric(string $query, array $params = [], array $types = []): Traversable
  844.     {
  845.         return $this->executeQuery($query$params$types)->iterateNumeric();
  846.     }
  847.     /**
  848.      * Prepares and executes an SQL query and returns the result as an iterator over rows represented
  849.      * as associative arrays.
  850.      *
  851.      * @param string                                                               $query  SQL query
  852.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  853.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  854.      *
  855.      * @return Traversable<int,array<string,mixed>>
  856.      *
  857.      * @throws Exception
  858.      */
  859.     public function iterateAssociative(string $query, array $params = [], array $types = []): Traversable
  860.     {
  861.         return $this->executeQuery($query$params$types)->iterateAssociative();
  862.     }
  863.     /**
  864.      * Prepares and executes an SQL query and returns the result as an iterator with the keys
  865.      * mapped to the first column and the values mapped to the second column.
  866.      *
  867.      * @param string                                                               $query  SQL query
  868.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  869.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  870.      *
  871.      * @return Traversable<mixed,mixed>
  872.      *
  873.      * @throws Exception
  874.      */
  875.     public function iterateKeyValue(string $query, array $params = [], array $types = []): Traversable
  876.     {
  877.         return $this->executeQuery($query$params$types)->iterateKeyValue();
  878.     }
  879.     /**
  880.      * Prepares and executes an SQL query and returns the result as an iterator with the keys mapped
  881.      * to the first column and the values being an associative array representing the rest of the columns
  882.      * and their values.
  883.      *
  884.      * @param string                                           $query  SQL query
  885.      * @param list<mixed>|array<string, mixed>                 $params Query parameters
  886.      * @param array<int, int|string>|array<string, int|string> $types  Parameter types
  887.      *
  888.      * @return Traversable<mixed,array<string,mixed>>
  889.      *
  890.      * @throws Exception
  891.      */
  892.     public function iterateAssociativeIndexed(string $query, array $params = [], array $types = []): Traversable
  893.     {
  894.         return $this->executeQuery($query$params$types)->iterateAssociativeIndexed();
  895.     }
  896.     /**
  897.      * Prepares and executes an SQL query and returns the result as an iterator over the first column values.
  898.      *
  899.      * @param string                                                               $query  SQL query
  900.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  901.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  902.      *
  903.      * @return Traversable<int,mixed>
  904.      *
  905.      * @throws Exception
  906.      */
  907.     public function iterateColumn(string $query, array $params = [], array $types = []): Traversable
  908.     {
  909.         return $this->executeQuery($query$params$types)->iterateColumn();
  910.     }
  911.     /**
  912.      * Prepares an SQL statement.
  913.      *
  914.      * @param string $sql The SQL statement to prepare.
  915.      *
  916.      * @throws Exception
  917.      */
  918.     public function prepare(string $sql): Statement
  919.     {
  920.         $connection $this->getWrappedConnection();
  921.         try {
  922.             $statement $connection->prepare($sql);
  923.         } catch (Driver\Exception $e) {
  924.             throw $this->convertExceptionDuringQuery($e$sql);
  925.         }
  926.         return new Statement($this$statement$sql);
  927.     }
  928.     /**
  929.      * Executes an, optionally parametrized, SQL query.
  930.      *
  931.      * If the query is parametrized, a prepared statement is used.
  932.      * If an SQLLogger is configured, the execution is logged.
  933.      *
  934.      * @param string                                                               $sql    SQL query
  935.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  936.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  937.      *
  938.      * @throws Exception
  939.      */
  940.     public function executeQuery(
  941.         string $sql,
  942.         array $params = [],
  943.         $types = [],
  944.         ?QueryCacheProfile $qcp null
  945.     ): Result {
  946.         if ($qcp !== null) {
  947.             return $this->executeCacheQuery($sql$params$types$qcp);
  948.         }
  949.         $connection $this->getWrappedConnection();
  950.         $logger $this->_config->getSQLLogger();
  951.         if ($logger !== null) {
  952.             $logger->startQuery($sql$params$types);
  953.         }
  954.         try {
  955.             if (count($params) > 0) {
  956.                 if ($this->needsArrayParameterConversion($params$types)) {
  957.                     [$sql$params$types] = $this->expandArrayParameters($sql$params$types);
  958.                 }
  959.                 $stmt $connection->prepare($sql);
  960.                 $this->bindParameters($stmt$params$types);
  961.                 $result $stmt->execute();
  962.             } else {
  963.                 $result $connection->query($sql);
  964.             }
  965.             return new Result($result$this);
  966.         } catch (Driver\Exception $e) {
  967.             throw $this->convertExceptionDuringQuery($e$sql$params$types);
  968.         } finally {
  969.             if ($logger !== null) {
  970.                 $logger->stopQuery();
  971.             }
  972.         }
  973.     }
  974.     /**
  975.      * Executes a caching query.
  976.      *
  977.      * @param string                                                               $sql    SQL query
  978.      * @param list<mixed>|array<string, mixed>                                     $params Query parameters
  979.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  980.      *
  981.      * @throws CacheException
  982.      * @throws Exception
  983.      */
  984.     public function executeCacheQuery($sql$params$typesQueryCacheProfile $qcp): Result
  985.     {
  986.         $resultCache $qcp->getResultCache() ?? $this->_config->getResultCache();
  987.         if ($resultCache === null) {
  988.             throw CacheException::noResultDriverConfigured();
  989.         }
  990.         $connectionParams $this->params;
  991.         unset($connectionParams['platform'], $connectionParams['password'], $connectionParams['url']);
  992.         [$cacheKey$realKey] = $qcp->generateCacheKeys($sql$params$types$connectionParams);
  993.         $item $resultCache->getItem($cacheKey);
  994.         if ($item->isHit()) {
  995.             $value $item->get();
  996.             if (isset($value[$realKey])) {
  997.                 return new Result(new ArrayResult($value[$realKey]), $this);
  998.             }
  999.         } else {
  1000.             $value = [];
  1001.         }
  1002.         $data $this->fetchAllAssociative($sql$params$types);
  1003.         $value[$realKey] = $data;
  1004.         $item->set($value);
  1005.         $lifetime $qcp->getLifetime();
  1006.         if ($lifetime 0) {
  1007.             $item->expiresAfter($lifetime);
  1008.         }
  1009.         $resultCache->save($item);
  1010.         return new Result(new ArrayResult($data), $this);
  1011.     }
  1012.     /**
  1013.      * Executes an SQL statement with the given parameters and returns the number of affected rows.
  1014.      *
  1015.      * Could be used for:
  1016.      *  - DML statements: INSERT, UPDATE, DELETE, etc.
  1017.      *  - DDL statements: CREATE, DROP, ALTER, etc.
  1018.      *  - DCL statements: GRANT, REVOKE, etc.
  1019.      *  - Session control statements: ALTER SESSION, SET, DECLARE, etc.
  1020.      *  - Other statements that don't yield a row set.
  1021.      *
  1022.      * This method supports PDO binding types as well as DBAL mapping types.
  1023.      *
  1024.      * @param string                                                               $sql    SQL statement
  1025.      * @param list<mixed>|array<string, mixed>                                     $params Statement parameters
  1026.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  1027.      *
  1028.      * @return int|string The number of affected rows.
  1029.      *
  1030.      * @throws Exception
  1031.      */
  1032.     public function executeStatement($sql, array $params = [], array $types = [])
  1033.     {
  1034.         $connection $this->getWrappedConnection();
  1035.         $logger $this->_config->getSQLLogger();
  1036.         if ($logger !== null) {
  1037.             $logger->startQuery($sql$params$types);
  1038.         }
  1039.         try {
  1040.             if (count($params) > 0) {
  1041.                 if ($this->needsArrayParameterConversion($params$types)) {
  1042.                     [$sql$params$types] = $this->expandArrayParameters($sql$params$types);
  1043.                 }
  1044.                 $stmt $connection->prepare($sql);
  1045.                 $this->bindParameters($stmt$params$types);
  1046.                 return $stmt->execute()
  1047.                     ->rowCount();
  1048.             }
  1049.             return $connection->exec($sql);
  1050.         } catch (Driver\Exception $e) {
  1051.             throw $this->convertExceptionDuringQuery($e$sql$params$types);
  1052.         } finally {
  1053.             if ($logger !== null) {
  1054.                 $logger->stopQuery();
  1055.             }
  1056.         }
  1057.     }
  1058.     /**
  1059.      * Returns the current transaction nesting level.
  1060.      *
  1061.      * @return int The nesting level. A value of 0 means there's no active transaction.
  1062.      */
  1063.     public function getTransactionNestingLevel()
  1064.     {
  1065.         return $this->transactionNestingLevel;
  1066.     }
  1067.     /**
  1068.      * Returns the ID of the last inserted row, or the last value from a sequence object,
  1069.      * depending on the underlying driver.
  1070.      *
  1071.      * Note: This method may not return a meaningful or consistent result across different drivers,
  1072.      * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
  1073.      * columns or sequences.
  1074.      *
  1075.      * @param string|null $name Name of the sequence object from which the ID should be returned.
  1076.      *
  1077.      * @return string|int|false A string representation of the last inserted ID.
  1078.      *
  1079.      * @throws Exception
  1080.      */
  1081.     public function lastInsertId($name null)
  1082.     {
  1083.         if ($name !== null) {
  1084.             Deprecation::trigger(
  1085.                 'doctrine/dbal',
  1086.                 'https://github.com/doctrine/dbal/issues/4687',
  1087.                 'The usage of Connection::lastInsertId() with a sequence name is deprecated.',
  1088.             );
  1089.         }
  1090.         try {
  1091.             return $this->getWrappedConnection()->lastInsertId($name);
  1092.         } catch (Driver\Exception $e) {
  1093.             throw $this->convertException($e);
  1094.         }
  1095.     }
  1096.     /**
  1097.      * Executes a function in a transaction.
  1098.      *
  1099.      * The function gets passed this Connection instance as an (optional) parameter.
  1100.      *
  1101.      * If an exception occurs during execution of the function or transaction commit,
  1102.      * the transaction is rolled back and the exception re-thrown.
  1103.      *
  1104.      * @param Closure(self):T $func The function to execute transactionally.
  1105.      *
  1106.      * @return T The value returned by $func
  1107.      *
  1108.      * @throws Throwable
  1109.      *
  1110.      * @template T
  1111.      */
  1112.     public function transactional(Closure $func)
  1113.     {
  1114.         $this->beginTransaction();
  1115.         try {
  1116.             $res $func($this);
  1117.             $this->commit();
  1118.             return $res;
  1119.         } catch (Throwable $e) {
  1120.             $this->rollBack();
  1121.             throw $e;
  1122.         }
  1123.     }
  1124.     /**
  1125.      * Sets if nested transactions should use savepoints.
  1126.      *
  1127.      * @param bool $nestTransactionsWithSavepoints
  1128.      *
  1129.      * @return void
  1130.      *
  1131.      * @throws Exception
  1132.      */
  1133.     public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
  1134.     {
  1135.         if (! $nestTransactionsWithSavepoints) {
  1136.             Deprecation::trigger(
  1137.                 'doctrine/dbal',
  1138.                 'https://github.com/doctrine/dbal/pull/5383',
  1139.                 <<<'DEPRECATION'
  1140.                 Nesting transactions without enabling savepoints is deprecated.
  1141.                 Call %s::setNestTransactionsWithSavepoints(true) to enable savepoints.
  1142.                 DEPRECATION,
  1143.                 self::class,
  1144.             );
  1145.         }
  1146.         if ($this->transactionNestingLevel 0) {
  1147.             throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
  1148.         }
  1149.         if (! $this->getDatabasePlatform()->supportsSavepoints()) {
  1150.             throw ConnectionException::savepointsNotSupported();
  1151.         }
  1152.         $this->nestTransactionsWithSavepoints = (bool) $nestTransactionsWithSavepoints;
  1153.     }
  1154.     /**
  1155.      * Gets if nested transactions should use savepoints.
  1156.      *
  1157.      * @return bool
  1158.      */
  1159.     public function getNestTransactionsWithSavepoints()
  1160.     {
  1161.         return $this->nestTransactionsWithSavepoints;
  1162.     }
  1163.     /**
  1164.      * Returns the savepoint name to use for nested transactions.
  1165.      *
  1166.      * @return string
  1167.      */
  1168.     protected function _getNestedTransactionSavePointName()
  1169.     {
  1170.         return 'DOCTRINE2_SAVEPOINT_' $this->transactionNestingLevel;
  1171.     }
  1172.     /**
  1173.      * @return bool
  1174.      *
  1175.      * @throws Exception
  1176.      */
  1177.     public function beginTransaction()
  1178.     {
  1179.         $connection $this->getWrappedConnection();
  1180.         ++$this->transactionNestingLevel;
  1181.         $logger $this->_config->getSQLLogger();
  1182.         if ($this->transactionNestingLevel === 1) {
  1183.             if ($logger !== null) {
  1184.                 $logger->startQuery('"START TRANSACTION"');
  1185.             }
  1186.             $connection->beginTransaction();
  1187.             if ($logger !== null) {
  1188.                 $logger->stopQuery();
  1189.             }
  1190.         } elseif ($this->nestTransactionsWithSavepoints) {
  1191.             if ($logger !== null) {
  1192.                 $logger->startQuery('"SAVEPOINT"');
  1193.             }
  1194.             $this->createSavepoint($this->_getNestedTransactionSavePointName());
  1195.             if ($logger !== null) {
  1196.                 $logger->stopQuery();
  1197.             }
  1198.         } else {
  1199.             Deprecation::trigger(
  1200.                 'doctrine/dbal',
  1201.                 'https://github.com/doctrine/dbal/pull/5383',
  1202.                 <<<'DEPRECATION'
  1203.                 Nesting transactions without enabling savepoints is deprecated.
  1204.                 Call %s::setNestTransactionsWithSavepoints(true) to enable savepoints.
  1205.                 DEPRECATION,
  1206.                 self::class,
  1207.             );
  1208.         }
  1209.         $eventManager $this->getEventManager();
  1210.         if ($eventManager->hasListeners(Events::onTransactionBegin)) {
  1211.             Deprecation::trigger(
  1212.                 'doctrine/dbal',
  1213.                 'https://github.com/doctrine/dbal/issues/5784',
  1214.                 'Subscribing to %s events is deprecated.',
  1215.                 Events::onTransactionBegin,
  1216.             );
  1217.             $eventManager->dispatchEvent(Events::onTransactionBegin, new TransactionBeginEventArgs($this));
  1218.         }
  1219.         return true;
  1220.     }
  1221.     /**
  1222.      * @return bool
  1223.      *
  1224.      * @throws Exception
  1225.      */
  1226.     public function commit()
  1227.     {
  1228.         if ($this->transactionNestingLevel === 0) {
  1229.             throw ConnectionException::noActiveTransaction();
  1230.         }
  1231.         if ($this->isRollbackOnly) {
  1232.             throw ConnectionException::commitFailedRollbackOnly();
  1233.         }
  1234.         $result true;
  1235.         $connection $this->getWrappedConnection();
  1236.         if ($this->transactionNestingLevel === 1) {
  1237.             $result $this->doCommit($connection);
  1238.         } elseif ($this->nestTransactionsWithSavepoints) {
  1239.             $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
  1240.         }
  1241.         --$this->transactionNestingLevel;
  1242.         $eventManager $this->getEventManager();
  1243.         if ($eventManager->hasListeners(Events::onTransactionCommit)) {
  1244.             Deprecation::trigger(
  1245.                 'doctrine/dbal',
  1246.                 'https://github.com/doctrine/dbal/issues/5784',
  1247.                 'Subscribing to %s events is deprecated.',
  1248.                 Events::onTransactionCommit,
  1249.             );
  1250.             $eventManager->dispatchEvent(Events::onTransactionCommit, new TransactionCommitEventArgs($this));
  1251.         }
  1252.         if ($this->autoCommit !== false || $this->transactionNestingLevel !== 0) {
  1253.             return $result;
  1254.         }
  1255.         $this->beginTransaction();
  1256.         return $result;
  1257.     }
  1258.     /**
  1259.      * @return bool
  1260.      *
  1261.      * @throws DriverException
  1262.      */
  1263.     private function doCommit(DriverConnection $connection)
  1264.     {
  1265.         $logger $this->_config->getSQLLogger();
  1266.         if ($logger !== null) {
  1267.             $logger->startQuery('"COMMIT"');
  1268.         }
  1269.         $result $connection->commit();
  1270.         if ($logger !== null) {
  1271.             $logger->stopQuery();
  1272.         }
  1273.         return $result;
  1274.     }
  1275.     /**
  1276.      * Commits all current nesting transactions.
  1277.      *
  1278.      * @throws Exception
  1279.      */
  1280.     private function commitAll(): void
  1281.     {
  1282.         while ($this->transactionNestingLevel !== 0) {
  1283.             if ($this->autoCommit === false && $this->transactionNestingLevel === 1) {
  1284.                 // When in no auto-commit mode, the last nesting commit immediately starts a new transaction.
  1285.                 // Therefore we need to do the final commit here and then leave to avoid an infinite loop.
  1286.                 $this->commit();
  1287.                 return;
  1288.             }
  1289.             $this->commit();
  1290.         }
  1291.     }
  1292.     /**
  1293.      * Cancels any database changes done during the current transaction.
  1294.      *
  1295.      * @return bool
  1296.      *
  1297.      * @throws Exception
  1298.      */
  1299.     public function rollBack()
  1300.     {
  1301.         if ($this->transactionNestingLevel === 0) {
  1302.             throw ConnectionException::noActiveTransaction();
  1303.         }
  1304.         $connection $this->getWrappedConnection();
  1305.         $logger $this->_config->getSQLLogger();
  1306.         if ($this->transactionNestingLevel === 1) {
  1307.             if ($logger !== null) {
  1308.                 $logger->startQuery('"ROLLBACK"');
  1309.             }
  1310.             $this->transactionNestingLevel 0;
  1311.             $connection->rollBack();
  1312.             $this->isRollbackOnly false;
  1313.             if ($logger !== null) {
  1314.                 $logger->stopQuery();
  1315.             }
  1316.             if ($this->autoCommit === false) {
  1317.                 $this->beginTransaction();
  1318.             }
  1319.         } elseif ($this->nestTransactionsWithSavepoints) {
  1320.             if ($logger !== null) {
  1321.                 $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
  1322.             }
  1323.             $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
  1324.             --$this->transactionNestingLevel;
  1325.             if ($logger !== null) {
  1326.                 $logger->stopQuery();
  1327.             }
  1328.         } else {
  1329.             $this->isRollbackOnly true;
  1330.             --$this->transactionNestingLevel;
  1331.         }
  1332.         $eventManager $this->getEventManager();
  1333.         if ($eventManager->hasListeners(Events::onTransactionRollBack)) {
  1334.             Deprecation::trigger(
  1335.                 'doctrine/dbal',
  1336.                 'https://github.com/doctrine/dbal/issues/5784',
  1337.                 'Subscribing to %s events is deprecated.',
  1338.                 Events::onTransactionRollBack,
  1339.             );
  1340.             $eventManager->dispatchEvent(Events::onTransactionRollBack, new TransactionRollBackEventArgs($this));
  1341.         }
  1342.         return true;
  1343.     }
  1344.     /**
  1345.      * Creates a new savepoint.
  1346.      *
  1347.      * @param string $savepoint The name of the savepoint to create.
  1348.      *
  1349.      * @return void
  1350.      *
  1351.      * @throws Exception
  1352.      */
  1353.     public function createSavepoint($savepoint)
  1354.     {
  1355.         $platform $this->getDatabasePlatform();
  1356.         if (! $platform->supportsSavepoints()) {
  1357.             throw ConnectionException::savepointsNotSupported();
  1358.         }
  1359.         $this->executeStatement($platform->createSavePoint($savepoint));
  1360.     }
  1361.     /**
  1362.      * Releases the given savepoint.
  1363.      *
  1364.      * @param string $savepoint The name of the savepoint to release.
  1365.      *
  1366.      * @return void
  1367.      *
  1368.      * @throws Exception
  1369.      */
  1370.     public function releaseSavepoint($savepoint)
  1371.     {
  1372.         $logger $this->_config->getSQLLogger();
  1373.         $platform $this->getDatabasePlatform();
  1374.         if (! $platform->supportsSavepoints()) {
  1375.             throw ConnectionException::savepointsNotSupported();
  1376.         }
  1377.         if (! $platform->supportsReleaseSavepoints()) {
  1378.             if ($logger !== null) {
  1379.                 $logger->stopQuery();
  1380.             }
  1381.             return;
  1382.         }
  1383.         if ($logger !== null) {
  1384.             $logger->startQuery('"RELEASE SAVEPOINT"');
  1385.         }
  1386.         $this->executeStatement($platform->releaseSavePoint($savepoint));
  1387.         if ($logger === null) {
  1388.             return;
  1389.         }
  1390.         $logger->stopQuery();
  1391.     }
  1392.     /**
  1393.      * Rolls back to the given savepoint.
  1394.      *
  1395.      * @param string $savepoint The name of the savepoint to rollback to.
  1396.      *
  1397.      * @return void
  1398.      *
  1399.      * @throws Exception
  1400.      */
  1401.     public function rollbackSavepoint($savepoint)
  1402.     {
  1403.         $platform $this->getDatabasePlatform();
  1404.         if (! $platform->supportsSavepoints()) {
  1405.             throw ConnectionException::savepointsNotSupported();
  1406.         }
  1407.         $this->executeStatement($platform->rollbackSavePoint($savepoint));
  1408.     }
  1409.     /**
  1410.      * Gets the wrapped driver connection.
  1411.      *
  1412.      * @deprecated Use {@link getNativeConnection()} to access the native connection.
  1413.      *
  1414.      * @return DriverConnection
  1415.      *
  1416.      * @throws Exception
  1417.      */
  1418.     public function getWrappedConnection()
  1419.     {
  1420.         Deprecation::triggerIfCalledFromOutside(
  1421.             'doctrine/dbal',
  1422.             'https://github.com/doctrine/dbal/issues/4966',
  1423.             'Connection::getWrappedConnection() is deprecated.'
  1424.                 ' Use Connection::getNativeConnection() to access the native connection.',
  1425.         );
  1426.         $this->connect();
  1427.         return $this->_conn;
  1428.     }
  1429.     /** @return resource|object */
  1430.     public function getNativeConnection()
  1431.     {
  1432.         $this->connect();
  1433.         if (! method_exists($this->_conn'getNativeConnection')) {
  1434.             throw new LogicException(sprintf(
  1435.                 'The driver connection %s does not support accessing the native connection.',
  1436.                 get_class($this->_conn),
  1437.             ));
  1438.         }
  1439.         return $this->_conn->getNativeConnection();
  1440.     }
  1441.     /**
  1442.      * Creates a SchemaManager that can be used to inspect or change the
  1443.      * database schema through the connection.
  1444.      *
  1445.      * @throws Exception
  1446.      */
  1447.     public function createSchemaManager(): AbstractSchemaManager
  1448.     {
  1449.         return $this->schemaManagerFactory->createSchemaManager($this);
  1450.     }
  1451.     /**
  1452.      * Gets the SchemaManager that can be used to inspect or change the
  1453.      * database schema through the connection.
  1454.      *
  1455.      * @deprecated Use {@see createSchemaManager()} instead.
  1456.      *
  1457.      * @return AbstractSchemaManager
  1458.      *
  1459.      * @throws Exception
  1460.      */
  1461.     public function getSchemaManager()
  1462.     {
  1463.         Deprecation::triggerIfCalledFromOutside(
  1464.             'doctrine/dbal',
  1465.             'https://github.com/doctrine/dbal/issues/4515',
  1466.             'Connection::getSchemaManager() is deprecated, use Connection::createSchemaManager() instead.',
  1467.         );
  1468.         return $this->_schemaManager ??= $this->createSchemaManager();
  1469.     }
  1470.     /**
  1471.      * Marks the current transaction so that the only possible
  1472.      * outcome for the transaction to be rolled back.
  1473.      *
  1474.      * @return void
  1475.      *
  1476.      * @throws ConnectionException If no transaction is active.
  1477.      */
  1478.     public function setRollbackOnly()
  1479.     {
  1480.         if ($this->transactionNestingLevel === 0) {
  1481.             throw ConnectionException::noActiveTransaction();
  1482.         }
  1483.         $this->isRollbackOnly true;
  1484.     }
  1485.     /**
  1486.      * Checks whether the current transaction is marked for rollback only.
  1487.      *
  1488.      * @return bool
  1489.      *
  1490.      * @throws ConnectionException If no transaction is active.
  1491.      */
  1492.     public function isRollbackOnly()
  1493.     {
  1494.         if ($this->transactionNestingLevel === 0) {
  1495.             throw ConnectionException::noActiveTransaction();
  1496.         }
  1497.         return $this->isRollbackOnly;
  1498.     }
  1499.     /**
  1500.      * Converts a given value to its database representation according to the conversion
  1501.      * rules of a specific DBAL mapping type.
  1502.      *
  1503.      * @param mixed  $value The value to convert.
  1504.      * @param string $type  The name of the DBAL mapping type.
  1505.      *
  1506.      * @return mixed The converted value.
  1507.      *
  1508.      * @throws Exception
  1509.      */
  1510.     public function convertToDatabaseValue($value$type)
  1511.     {
  1512.         return Type::getType($type)->convertToDatabaseValue($value$this->getDatabasePlatform());
  1513.     }
  1514.     /**
  1515.      * Converts a given value to its PHP representation according to the conversion
  1516.      * rules of a specific DBAL mapping type.
  1517.      *
  1518.      * @param mixed  $value The value to convert.
  1519.      * @param string $type  The name of the DBAL mapping type.
  1520.      *
  1521.      * @return mixed The converted type.
  1522.      *
  1523.      * @throws Exception
  1524.      */
  1525.     public function convertToPHPValue($value$type)
  1526.     {
  1527.         return Type::getType($type)->convertToPHPValue($value$this->getDatabasePlatform());
  1528.     }
  1529.     /**
  1530.      * Binds a set of parameters, some or all of which are typed with a PDO binding type
  1531.      * or DBAL mapping type, to a given statement.
  1532.      *
  1533.      * @param DriverStatement                                                      $stmt   Prepared statement
  1534.      * @param list<mixed>|array<string, mixed>                                     $params Statement parameters
  1535.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types  Parameter types
  1536.      *
  1537.      * @throws Exception
  1538.      */
  1539.     private function bindParameters(DriverStatement $stmt, array $params, array $types): void
  1540.     {
  1541.         // Check whether parameters are positional or named. Mixing is not allowed.
  1542.         if (is_int(key($params))) {
  1543.             $bindIndex 1;
  1544.             foreach ($params as $key => $value) {
  1545.                 if (isset($types[$key])) {
  1546.                     $type                  $types[$key];
  1547.                     [$value$bindingType] = $this->getBindingInfo($value$type);
  1548.                 } else {
  1549.                     if (array_key_exists($key$types)) {
  1550.                         Deprecation::trigger(
  1551.                             'doctrine/dbal',
  1552.                             'https://github.com/doctrine/dbal/pull/5550',
  1553.                             'Using NULL as prepared statement parameter type is deprecated.'
  1554.                                 'Omit or use Parameter::STRING instead',
  1555.                         );
  1556.                     }
  1557.                     $bindingType ParameterType::STRING;
  1558.                 }
  1559.                 $stmt->bindValue($bindIndex$value$bindingType);
  1560.                 ++$bindIndex;
  1561.             }
  1562.         } else {
  1563.             // Named parameters
  1564.             foreach ($params as $name => $value) {
  1565.                 if (isset($types[$name])) {
  1566.                     $type                  $types[$name];
  1567.                     [$value$bindingType] = $this->getBindingInfo($value$type);
  1568.                 } else {
  1569.                     if (array_key_exists($name$types)) {
  1570.                         Deprecation::trigger(
  1571.                             'doctrine/dbal',
  1572.                             'https://github.com/doctrine/dbal/pull/5550',
  1573.                             'Using NULL as prepared statement parameter type is deprecated.'
  1574.                                 'Omit or use Parameter::STRING instead',
  1575.                         );
  1576.                     }
  1577.                     $bindingType ParameterType::STRING;
  1578.                 }
  1579.                 $stmt->bindValue($name$value$bindingType);
  1580.             }
  1581.         }
  1582.     }
  1583.     /**
  1584.      * Gets the binding type of a given type.
  1585.      *
  1586.      * @param mixed                $value The value to bind.
  1587.      * @param int|string|Type|null $type  The type to bind (PDO or DBAL).
  1588.      *
  1589.      * @return array{mixed, int} [0] => the (escaped) value, [1] => the binding type.
  1590.      *
  1591.      * @throws Exception
  1592.      */
  1593.     private function getBindingInfo($value$type): array
  1594.     {
  1595.         if (is_string($type)) {
  1596.             $type Type::getType($type);
  1597.         }
  1598.         if ($type instanceof Type) {
  1599.             $value       $type->convertToDatabaseValue($value$this->getDatabasePlatform());
  1600.             $bindingType $type->getBindingType();
  1601.         } else {
  1602.             $bindingType $type ?? ParameterType::STRING;
  1603.         }
  1604.         return [$value$bindingType];
  1605.     }
  1606.     /**
  1607.      * Creates a new instance of a SQL query builder.
  1608.      *
  1609.      * @return QueryBuilder
  1610.      */
  1611.     public function createQueryBuilder()
  1612.     {
  1613.         return new Query\QueryBuilder($this);
  1614.     }
  1615.     /**
  1616.      * @internal
  1617.      *
  1618.      * @param list<mixed>|array<string, mixed>                                     $params
  1619.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1620.      */
  1621.     final public function convertExceptionDuringQuery(
  1622.         Driver\Exception $e,
  1623.         string $sql,
  1624.         array $params = [],
  1625.         array $types = []
  1626.     ): DriverException {
  1627.         return $this->handleDriverException($e, new Query($sql$params$types));
  1628.     }
  1629.     /** @internal */
  1630.     final public function convertException(Driver\Exception $e): DriverException
  1631.     {
  1632.         return $this->handleDriverException($enull);
  1633.     }
  1634.     /**
  1635.      * @param array<int, mixed>|array<string, mixed>                               $params
  1636.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1637.      *
  1638.      * @return array{string, list<mixed>, array<int,Type|int|string|null>}
  1639.      */
  1640.     private function expandArrayParameters(string $sql, array $params, array $types): array
  1641.     {
  1642.         $this->parser ??= $this->getDatabasePlatform()->createSQLParser();
  1643.         $visitor        = new ExpandArrayParameters($params$types);
  1644.         $this->parser->parse($sql$visitor);
  1645.         return [
  1646.             $visitor->getSQL(),
  1647.             $visitor->getParameters(),
  1648.             $visitor->getTypes(),
  1649.         ];
  1650.     }
  1651.     /**
  1652.      * @param array<int, mixed>|array<string, mixed>                               $params
  1653.      * @param array<int, int|string|Type|null>|array<string, int|string|Type|null> $types
  1654.      */
  1655.     private function needsArrayParameterConversion(array $params, array $types): bool
  1656.     {
  1657.         if (is_string(key($params))) {
  1658.             return true;
  1659.         }
  1660.         foreach ($types as $type) {
  1661.             if (
  1662.                 $type === ArrayParameterType::INTEGER
  1663.                 || $type === ArrayParameterType::STRING
  1664.                 || $type === ArrayParameterType::ASCII
  1665.             ) {
  1666.                 return true;
  1667.             }
  1668.         }
  1669.         return false;
  1670.     }
  1671.     private function handleDriverException(
  1672.         Driver\Exception $driverException,
  1673.         ?Query $query
  1674.     ): DriverException {
  1675.         $this->exceptionConverter ??= $this->_driver->getExceptionConverter();
  1676.         $exception                  $this->exceptionConverter->convert($driverException$query);
  1677.         if ($exception instanceof ConnectionLost) {
  1678.             $this->close();
  1679.         }
  1680.         return $exception;
  1681.     }
  1682.     /**
  1683.      * BC layer for a wide-spread use-case of old DBAL APIs
  1684.      *
  1685.      * @deprecated This API is deprecated and will be removed after 2022
  1686.      *
  1687.      * @param array<mixed>           $params The query parameters
  1688.      * @param array<int|string|null> $types  The parameter types
  1689.      */
  1690.     public function executeUpdate(string $sql, array $params = [], array $types = []): int
  1691.     {
  1692.         return $this->executeStatement($sql$params$types);
  1693.     }
  1694.     /**
  1695.      * BC layer for a wide-spread use-case of old DBAL APIs
  1696.      *
  1697.      * @deprecated This API is deprecated and will be removed after 2022
  1698.      */
  1699.     public function query(string $sql): Result
  1700.     {
  1701.         return $this->executeQuery($sql);
  1702.     }
  1703.     /**
  1704.      * BC layer for a wide-spread use-case of old DBAL APIs
  1705.      *
  1706.      * @deprecated This API is deprecated and will be removed after 2022
  1707.      */
  1708.     public function exec(string $sql): int
  1709.     {
  1710.         return $this->executeStatement($sql);
  1711.     }
  1712. }