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

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