Connection.php 41.4 KB
Newer Older
1
<?php
romanb's avatar
romanb committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
Benjamin Eberlei's avatar
Benjamin Eberlei committed
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
romanb's avatar
romanb committed
18 19
 */

20
namespace Doctrine\DBAL;
romanb's avatar
romanb committed
21

Benjamin Morel's avatar
Benjamin Morel committed
22 23 24 25 26 27 28 29 30 31 32
use PDO;
use Closure;
use Exception;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Driver\Connection as DriverConnection;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Cache\ResultCacheStatement;
use Doctrine\DBAL\Cache\QueryCacheProfile;
use Doctrine\DBAL\Cache\ArrayStatement;
use Doctrine\DBAL\Cache\CacheException;
33 34

/**
35
 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
36 37
 * events, transaction isolation levels, configuration, emulated transaction nesting,
 * lazy connecting and more.
38
 *
Benjamin Morel's avatar
Benjamin Morel committed
39 40 41 42 43 44 45 46
 * @link   www.doctrine-project.org
 * @since  2.0
 * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author Jonathan Wage <jonwage@gmail.com>
 * @author Roman Borschel <roman@code-factory.org>
 * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @author Lukas Smith <smith@pooteeweet.org> (MDB2 library)
 * @author Benjamin Eberlei <kontakt@beberlei.de>
47
 */
48
class Connection implements DriverConnection
49
{
50 51 52 53
    /**
     * Constant for transaction isolation level READ UNCOMMITTED.
     */
    const TRANSACTION_READ_UNCOMMITTED = 1;
54

55 56 57 58
    /**
     * Constant for transaction isolation level READ COMMITTED.
     */
    const TRANSACTION_READ_COMMITTED = 2;
59

60 61 62 63
    /**
     * Constant for transaction isolation level REPEATABLE READ.
     */
    const TRANSACTION_REPEATABLE_READ = 3;
64

65 66 67 68
    /**
     * Constant for transaction isolation level SERIALIZABLE.
     */
    const TRANSACTION_SERIALIZABLE = 4;
69

70 71
    /**
     * Represents an array of ints to be expanded by Doctrine SQL parsing.
72
     *
Benjamin Morel's avatar
Benjamin Morel committed
73
     * @var integer
74 75
     */
    const PARAM_INT_ARRAY = 101;
76

77 78
    /**
     * Represents an array of strings to be expanded by Doctrine SQL parsing.
79
     *
Benjamin Morel's avatar
Benjamin Morel committed
80
     * @var integer
81 82
     */
    const PARAM_STR_ARRAY = 102;
83

84 85
    /**
     * Offset by which PARAM_* constants are detected as arrays of the param type.
86
     *
Benjamin Morel's avatar
Benjamin Morel committed
87
     * @var integer
88 89
     */
    const ARRAY_PARAM_OFFSET = 100;
90

romanb's avatar
romanb committed
91 92 93
    /**
     * The wrapped driver connection.
     *
94
     * @var \Doctrine\DBAL\Driver\Connection
romanb's avatar
romanb committed
95 96
     */
    protected $_conn;
97

romanb's avatar
romanb committed
98
    /**
99
     * @var \Doctrine\DBAL\Configuration
romanb's avatar
romanb committed
100 101
     */
    protected $_config;
102

romanb's avatar
romanb committed
103
    /**
104
     * @var \Doctrine\Common\EventManager
romanb's avatar
romanb committed
105 106
     */
    protected $_eventManager;
107

108
    /**
109
     * @var \Doctrine\DBAL\Query\Expression\ExpressionBuilder
110 111
     */
    protected $_expr;
112

romanb's avatar
romanb committed
113 114 115 116 117
    /**
     * Whether or not a connection has been established.
     *
     * @var boolean
     */
118
    private $_isConnected = false;
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133
    /**
     * The transaction nesting level.
     *
     * @var integer
     */
    private $_transactionNestingLevel = 0;

    /**
     * The currently active transaction isolation level.
     *
     * @var integer
     */
    private $_transactionIsolationLevel;

134
    /**
Benjamin Morel's avatar
Benjamin Morel committed
135
     * If nested transactions should use savepoints.
136 137 138 139
     *
     * @var integer
     */
    private $_nestTransactionsWithSavepoints;
Lukas Kahwe Smith's avatar
Lukas Kahwe Smith committed
140

romanb's avatar
romanb committed
141 142 143 144 145
    /**
     * The parameters used during creation of the Connection instance.
     *
     * @var array
     */
146
    private $_params = array();
147

romanb's avatar
romanb committed
148 149 150 151
    /**
     * The DatabasePlatform object that provides information about the
     * database platform used by the connection.
     *
152
     * @var \Doctrine\DBAL\Platforms\AbstractPlatform
romanb's avatar
romanb committed
153 154
     */
    protected $_platform;
155

romanb's avatar
romanb committed
156 157 158
    /**
     * The schema manager.
     *
159
     * @var \Doctrine\DBAL\Schema\AbstractSchemaManager
romanb's avatar
romanb committed
160 161
     */
    protected $_schemaManager;
162

romanb's avatar
romanb committed
163
    /**
romanb's avatar
romanb committed
164 165
     * The used DBAL driver.
     *
166
     * @var \Doctrine\DBAL\Driver
romanb's avatar
romanb committed
167 168
     */
    protected $_driver;
169

170
    /**
171
     * Flag that indicates whether the current transaction is marked for rollback only.
172
     *
173
     * @var boolean
174
     */
175 176
    private $_isRollbackOnly = false;

Benjamin Morel's avatar
Benjamin Morel committed
177 178 179
    /**
     * @var integer
     */
180
    protected $defaultFetchMode = PDO::FETCH_ASSOC;
181

romanb's avatar
romanb committed
182 183 184
    /**
     * Initializes a new instance of the Connection class.
     *
Benjamin Morel's avatar
Benjamin Morel committed
185 186 187 188 189 190
     * @param array                              $params       The connection parameters.
     * @param \Doctrine\DBAL\Driver              $driver       The driver to use.
     * @param \Doctrine\DBAL\Configuration|null  $config       The configuration, optional.
     * @param \Doctrine\Common\EventManager|null $eventManager The event manager, optional.
     *
     * @throws \Doctrine\DBAL\DBALException
romanb's avatar
romanb committed
191 192 193 194 195 196
     */
    public function __construct(array $params, Driver $driver, Configuration $config = null,
            EventManager $eventManager = null)
    {
        $this->_driver = $driver;
        $this->_params = $params;
197

romanb's avatar
romanb committed
198 199 200 201
        if (isset($params['pdo'])) {
            $this->_conn = $params['pdo'];
            $this->_isConnected = true;
        }
202

romanb's avatar
romanb committed
203 204 205
        // Create default config and event manager if none given
        if ( ! $config) {
            $config = new Configuration();
romanb's avatar
romanb committed
206
        }
207

romanb's avatar
romanb committed
208
        if ( ! $eventManager) {
romanb's avatar
romanb committed
209
            $eventManager = new EventManager();
romanb's avatar
romanb committed
210
        }
211

romanb's avatar
romanb committed
212
        $this->_config = $config;
romanb's avatar
romanb committed
213
        $this->_eventManager = $eventManager;
214

215
        $this->_expr = new Query\Expression\ExpressionBuilder($this);
216

217
        if ( ! isset($params['platform'])) {
218
            $this->_platform = $driver->getDatabasePlatform();
219
        } else if ($params['platform'] instanceof Platforms\AbstractPlatform) {
220 221 222 223
            $this->_platform = $params['platform'];
        } else {
            throw DBALException::invalidPlatformSpecified();
        }
224

225 226
        $this->_platform->setEventManager($eventManager);

227
        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
romanb's avatar
romanb committed
228
    }
romanb's avatar
romanb committed
229

230
    /**
romanb's avatar
romanb committed
231
     * Gets the parameters used during instantiation.
232
     *
Benjamin Morel's avatar
Benjamin Morel committed
233
     * @return array
234 235 236 237 238 239
     */
    public function getParams()
    {
        return $this->_params;
    }

romanb's avatar
romanb committed
240
    /**
romanb's avatar
romanb committed
241
     * Gets the name of the database this Connection is connected to.
romanb's avatar
romanb committed
242
     *
Benjamin Morel's avatar
Benjamin Morel committed
243
     * @return string
romanb's avatar
romanb committed
244 245 246 247 248
     */
    public function getDatabase()
    {
        return $this->_driver->getDatabase($this);
    }
249

250 251
    /**
     * Gets the hostname of the currently connected database.
252
     *
Benjamin Morel's avatar
Benjamin Morel committed
253
     * @return string|null
254 255 256
     */
    public function getHost()
    {
jwage's avatar
jwage committed
257
        return isset($this->_params['host']) ? $this->_params['host'] : null;
258
    }
259

260 261
    /**
     * Gets the port of the currently connected database.
262
     *
263 264 265 266
     * @return mixed
     */
    public function getPort()
    {
jwage's avatar
jwage committed
267
        return isset($this->_params['port']) ? $this->_params['port'] : null;
268
    }
269

270 271
    /**
     * Gets the username used by this connection.
272
     *
Benjamin Morel's avatar
Benjamin Morel committed
273
     * @return string|null
274 275 276
     */
    public function getUsername()
    {
jwage's avatar
jwage committed
277
        return isset($this->_params['user']) ? $this->_params['user'] : null;
278
    }
279

280 281
    /**
     * Gets the password used by this connection.
282
     *
Benjamin Morel's avatar
Benjamin Morel committed
283
     * @return string|null
284 285 286
     */
    public function getPassword()
    {
jwage's avatar
jwage committed
287
        return isset($this->_params['password']) ? $this->_params['password'] : null;
288
    }
romanb's avatar
romanb committed
289 290 291 292

    /**
     * Gets the DBAL driver instance.
     *
293
     * @return \Doctrine\DBAL\Driver
romanb's avatar
romanb committed
294 295 296 297 298 299 300 301 302
     */
    public function getDriver()
    {
        return $this->_driver;
    }

    /**
     * Gets the Configuration used by the Connection.
     *
303
     * @return \Doctrine\DBAL\Configuration
romanb's avatar
romanb committed
304 305 306 307 308 309 310 311 312
     */
    public function getConfiguration()
    {
        return $this->_config;
    }

    /**
     * Gets the EventManager used by the Connection.
     *
313
     * @return \Doctrine\Common\EventManager
romanb's avatar
romanb committed
314 315 316 317 318 319 320 321 322
     */
    public function getEventManager()
    {
        return $this->_eventManager;
    }

    /**
     * Gets the DatabasePlatform for the connection.
     *
323
     * @return \Doctrine\DBAL\Platforms\AbstractPlatform
romanb's avatar
romanb committed
324 325 326 327 328
     */
    public function getDatabasePlatform()
    {
        return $this->_platform;
    }
329

330 331 332
    /**
     * Gets the ExpressionBuilder for the connection.
     *
333
     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
334 335 336 337 338
     */
    public function getExpressionBuilder()
    {
        return $this->_expr;
    }
339

romanb's avatar
romanb committed
340 341 342
    /**
     * Establishes the connection with the database.
     *
343 344
     * @return boolean TRUE if the connection was successfully established, FALSE if
     *                 the connection is already open.
romanb's avatar
romanb committed
345 346 347 348 349 350
     */
    public function connect()
    {
        if ($this->_isConnected) return false;

        $driverOptions = isset($this->_params['driverOptions']) ?
romanb's avatar
romanb committed
351 352
                $this->_params['driverOptions'] : array();
        $user = isset($this->_params['user']) ? $this->_params['user'] : null;
romanb's avatar
romanb committed
353
        $password = isset($this->_params['password']) ?
romanb's avatar
romanb committed
354 355 356
                $this->_params['password'] : null;

        $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
romanb's avatar
romanb committed
357 358
        $this->_isConnected = true;

359
        if ($this->_eventManager->hasListeners(Events::postConnect)) {
360
            $eventArgs = new Event\ConnectionEventArgs($this);
361 362 363
            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
        }

romanb's avatar
romanb committed
364 365 366
        return true;
    }

367
    /**
Benjamin Morel's avatar
Benjamin Morel committed
368
     * Sets the fetch mode.
369
     *
370
     * @param integer $fetchMode
Benjamin Morel's avatar
Benjamin Morel committed
371 372
     *
     * @return void
373
     */
374
    public function setFetchMode($fetchMode)
375
    {
376
        $this->defaultFetchMode = $fetchMode;
377 378
    }

romanb's avatar
romanb committed
379
    /**
380 381
     * Prepares and executes an SQL query and returns the first row of the result
     * as an associative array.
382
     *
romanb's avatar
romanb committed
383
     * @param string $statement The SQL query.
Benjamin Morel's avatar
Benjamin Morel committed
384 385
     * @param array  $params    The query parameters.
     *
romanb's avatar
romanb committed
386 387
     * @return array
     */
388
    public function fetchAssoc($statement, array $params = array())
romanb's avatar
romanb committed
389
    {
390
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_ASSOC);
romanb's avatar
romanb committed
391 392 393
    }

    /**
394 395
     * Prepares and executes an SQL query and returns the first row of the result
     * as a numerically indexed array.
romanb's avatar
romanb committed
396
     *
Benjamin Morel's avatar
Benjamin Morel committed
397 398 399
     * @param string $statement The SQL query to be executed.
     * @param array  $params    The prepared statement params.
     *
romanb's avatar
romanb committed
400 401 402 403
     * @return array
     */
    public function fetchArray($statement, array $params = array())
    {
404
        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_NUM);
romanb's avatar
romanb committed
405 406 407
    }

    /**
408 409
     * Prepares and executes an SQL query and returns the value of a single column
     * of the first row of the result.
410
     *
Benjamin Morel's avatar
Benjamin Morel committed
411 412 413 414
     * @param string  $statement The SQL query to be executed.
     * @param array   $params    The prepared statement params.
     * @param integer $colnum    The 0-indexed column number to retrieve.
     *
415
     * @return mixed
romanb's avatar
romanb committed
416 417 418
     */
    public function fetchColumn($statement, array $params = array(), $colnum = 0)
    {
419
        return $this->executeQuery($statement, $params)->fetchColumn($colnum);
romanb's avatar
romanb committed
420 421 422 423 424 425 426 427 428 429 430 431
    }

    /**
     * Whether an actual connection to the database is established.
     *
     * @return boolean
     */
    public function isConnected()
    {
        return $this->_isConnected;
    }

432 433
    /**
     * Checks whether a transaction is currently active.
434
     *
435 436 437 438 439 440 441
     * @return boolean TRUE if a transaction is currently active, FALSE otherwise.
     */
    public function isTransactionActive()
    {
        return $this->_transactionNestingLevel > 0;
    }

442 443
    /**
     * Executes an SQL DELETE statement on a table.
romanb's avatar
romanb committed
444
     *
Benjamin Morel's avatar
Benjamin Morel committed
445 446 447 448
     * @param string $tableName  The name of the table on which to delete.
     * @param array  $identifier The deletion criteria. An associative array containing column-value pairs.
     * @param array  $types      The types of identifiers.
     *
449
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
450
     */
451
    public function delete($tableName, array $identifier, array $types = array())
romanb's avatar
romanb committed
452 453
    {
        $this->connect();
454

romanb's avatar
romanb committed
455
        $criteria = array();
456 457 458

        foreach (array_keys($identifier) as $columnName) {
            $criteria[] = $columnName . ' = ?';
romanb's avatar
romanb committed
459 460
        }

461 462 463 464
        if ( ! is_int(key($types))) {
            $types = $this->extractTypeValues($identifier, $types);
        }

465
        $query = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' AND ', $criteria);
romanb's avatar
romanb committed
466

467
        return $this->executeUpdate($query, array_values($identifier), $types);
romanb's avatar
romanb committed
468 469 470 471 472 473 474 475 476 477
    }

    /**
     * Closes the connection.
     *
     * @return void
     */
    public function close()
    {
        unset($this->_conn);
478

romanb's avatar
romanb committed
479 480 481
        $this->_isConnected = false;
    }

482 483 484
    /**
     * Sets the transaction isolation level.
     *
485
     * @param integer $level The level to set.
Benjamin Morel's avatar
Benjamin Morel committed
486
     *
487
     * @return integer
488 489 490 491
     */
    public function setTransactionIsolation($level)
    {
        $this->_transactionIsolationLevel = $level;
492

493 494 495 496 497 498
        return $this->executeUpdate($this->_platform->getSetTransactionIsolationSQL($level));
    }

    /**
     * Gets the currently active transaction isolation level.
     *
499
     * @return integer The current transaction isolation level.
500 501 502 503 504 505
     */
    public function getTransactionIsolation()
    {
        return $this->_transactionIsolationLevel;
    }

romanb's avatar
romanb committed
506
    /**
507
     * Executes an SQL UPDATE statement on a table.
romanb's avatar
romanb committed
508
     *
Benjamin Morel's avatar
Benjamin Morel committed
509 510 511 512 513
     * @param string $tableName  The name of the table to update.
     * @param array  $data       An associative array containing column-value pairs.
     * @param array  $identifier The update criteria. An associative array containing column-value pairs.
     * @param array  $types      Types of the merged $data and $identifier arrays in that order.
     *
514
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
515
     */
516
    public function update($tableName, array $data, array $identifier, array $types = array())
romanb's avatar
romanb committed
517 518 519
    {
        $this->connect();
        $set = array();
520

romanb's avatar
romanb committed
521
        foreach ($data as $columnName => $value) {
522
            $set[] = $columnName . ' = ?';
romanb's avatar
romanb committed
523 524
        }

525 526 527 528
        if ( ! is_int(key($types))) {
            $types = $this->extractTypeValues(array_merge($data, $identifier), $types);
        }

romanb's avatar
romanb committed
529 530
        $params = array_merge(array_values($data), array_values($identifier));

531 532 533
        $sql  = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $set)
                . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
                . ' = ?';
romanb's avatar
romanb committed
534

535
        return $this->executeUpdate($sql, $params, $types);
romanb's avatar
romanb committed
536 537 538 539 540
    }

    /**
     * Inserts a table row with specified data.
     *
541
     * @param string $tableName The name of the table to insert data into.
Benjamin Morel's avatar
Benjamin Morel committed
542 543 544
     * @param array  $data      An associative array containing column-value pairs.
     * @param array  $types     Types of the inserted data.
     *
545
     * @return integer The number of affected rows.
romanb's avatar
romanb committed
546
     */
547
    public function insert($tableName, array $data, array $types = array())
romanb's avatar
romanb committed
548 549 550
    {
        $this->connect();

551 552
        if (empty($data)) {
            return $this->executeUpdate('INSERT INTO ' . $tableName . ' ()' . ' VALUES ()');
553 554
        }

555 556 557 558 559 560
        return $this->executeUpdate(
            'INSERT INTO ' . $tableName . ' (' . implode(', ', array_keys($data)) . ')' .
            ' VALUES (' . implode(', ', array_fill(0, count($data), '?')) . ')',
            array_values($data),
            is_int(key($types)) ? $types : $this->extractTypeValues($data, $types)
        );
romanb's avatar
romanb committed
561 562
    }

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
    /**
     * Extract ordered type list from two associate key lists of data and types.
     *
     * @param array $data
     * @param array $types
     *
     * @return array
     */
    private function extractTypeValues(array $data, array $types)
    {
        $typeValues = array();

        foreach ($data as $k => $_) {
            $typeValues[] = isset($types[$k])
                ? $types[$k]
                : \PDO::PARAM_STR;
        }

        return $typeValues;
    }

romanb's avatar
romanb committed
584
    /**
Benjamin Morel's avatar
Benjamin Morel committed
585
     * Quotes a string so it can be safely used as a table or column name, even if
romanb's avatar
romanb committed
586 587 588 589
     * it is a reserved name.
     *
     * Delimiting style depends on the underlying database platform that is being used.
     *
590 591
     * NOTE: Just because you CAN use quoted identifiers does not mean
     * you SHOULD use them. In general, they end up causing way more
romanb's avatar
romanb committed
592 593
     * problems than they solve.
     *
594
     * @param string $str The name to be quoted.
Benjamin Morel's avatar
Benjamin Morel committed
595
     *
596
     * @return string The quoted name.
romanb's avatar
romanb committed
597 598 599
     */
    public function quoteIdentifier($str)
    {
600
        return $this->_platform->quoteIdentifier($str);
romanb's avatar
romanb committed
601 602 603 604 605
    }

    /**
     * Quotes a given input parameter.
     *
Benjamin Morel's avatar
Benjamin Morel committed
606 607 608
     * @param mixed       $input The parameter to be quoted.
     * @param string|null $type  The type of the parameter.
     *
609
     * @return string The quoted parameter.
romanb's avatar
romanb committed
610 611 612
     */
    public function quote($input, $type = null)
    {
613
        $this->connect();
614 615

        list($value, $bindingType) = $this->getBindingInfo($input, $type);
616
        return $this->_conn->quote($value, $bindingType);
romanb's avatar
romanb committed
617 618 619
    }

    /**
620
     * Prepares and executes an SQL query and returns the result as an associative array.
romanb's avatar
romanb committed
621
     *
Benjamin Morel's avatar
Benjamin Morel committed
622 623 624 625
     * @param string $sql    The SQL query.
     * @param array  $params The query parameters.
     * @param array  $types  The query parameter types.
     *
romanb's avatar
romanb committed
626 627
     * @return array
     */
root's avatar
root committed
628
    public function fetchAll($sql, array $params = array(), $types = array())
romanb's avatar
romanb committed
629
    {
root's avatar
root committed
630
        return $this->executeQuery($sql, $params, $types)->fetchAll();
romanb's avatar
romanb committed
631 632 633 634 635
    }

    /**
     * Prepares an SQL statement.
     *
636
     * @param string $statement The SQL statement to prepare.
Benjamin Morel's avatar
Benjamin Morel committed
637
     *
638
     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
Benjamin Morel's avatar
Benjamin Morel committed
639 640
     *
     * @throws \Doctrine\DBAL\DBALException
romanb's avatar
romanb committed
641 642 643 644
     */
    public function prepare($statement)
    {
        $this->connect();
645

646 647 648 649 650 651
        try {
            $stmt = new Statement($statement, $this);
        } catch (\Exception $ex) {
            throw DBALException::driverExceptionDuringQuery($ex, $statement);
        }

652
        $stmt->setFetchMode($this->defaultFetchMode);
653 654

        return $stmt;
romanb's avatar
romanb committed
655 656 657
    }

    /**
Pascal Borreli's avatar
Pascal Borreli committed
658
     * Executes an, optionally parametrized, SQL query.
romanb's avatar
romanb committed
659
     *
Pascal Borreli's avatar
Pascal Borreli committed
660
     * If the query is parametrized, a prepared statement is used.
661 662
     * If an SQLLogger is configured, the execution is logged.
     *
Benjamin Morel's avatar
Benjamin Morel committed
663 664 665 666 667
     * @param string                                      $query  The SQL query to execute.
     * @param array                                       $params The parameters to bind to the query, if any.
     * @param array                                       $types  The types the previous parameters are in.
     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
     *
668
     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
Benjamin Morel's avatar
Benjamin Morel committed
669 670 671
     *
     * @throws \Doctrine\DBAL\DBALException
     *
672
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
romanb's avatar
romanb committed
673
     */
674
    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
romanb's avatar
romanb committed
675
    {
676
        if ($qcp !== null) {
677
            return $this->executeCacheQuery($query, $params, $types, $qcp);
678 679
        }

romanb's avatar
romanb committed
680 681
        $this->connect();

682 683 684
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
685
        }
686

687 688 689
        try {
            if ($params) {
                list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
690

691 692 693 694 695 696 697
                $stmt = $this->_conn->prepare($query);
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
698
            } else {
699
                $stmt = $this->_conn->query($query);
700
            }
701 702
        } catch (\Exception $ex) {
            throw DBALException::driverExceptionDuringQuery($ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
703
        }
704

705
        $stmt->setFetchMode($this->defaultFetchMode);
706

707 708
        if ($logger) {
            $logger->stopQuery();
709 710
        }

romanb's avatar
romanb committed
711
        return $stmt;
romanb's avatar
romanb committed
712
    }
713

714
    /**
Benjamin Morel's avatar
Benjamin Morel committed
715 716 717 718 719 720
     * Executes a caching query.
     *
     * @param string                                 $query  The SQL query to execute.
     * @param array                                  $params The parameters to bind to the query, if any.
     * @param array                                  $types  The types the previous parameters are in.
     * @param \Doctrine\DBAL\Cache\QueryCacheProfile $qcp    The query cache profile.
721 722
     *
     * @return \Doctrine\DBAL\Driver\ResultStatement
Benjamin Morel's avatar
Benjamin Morel committed
723 724
     *
     * @throws \Doctrine\DBAL\Cache\CacheException
725 726 727 728
     */
    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
    {
        $resultCache = $qcp->getResultCacheDriver() ?: $this->_config->getResultCacheImpl();
729
        if ( ! $resultCache) {
730 731 732 733 734 735 736 737 738
            throw CacheException::noResultDriverConfigured();
        }

        list($cacheKey, $realKey) = $qcp->generateCacheKeys($query, $params, $types);

        // fetch the row pointers entry
        if ($data = $resultCache->fetch($cacheKey)) {
            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
            if (isset($data[$realKey])) {
739
                $stmt = new ArrayStatement($data[$realKey]);
740
            } else if (array_key_exists($realKey, $data)) {
741
                $stmt = new ArrayStatement(array());
742 743
            }
        }
744 745 746 747 748

        if (!isset($stmt)) {
            $stmt = new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
        }

749
        $stmt->setFetchMode($this->defaultFetchMode);
750 751

        return $stmt;
752 753
    }

754
    /**
Pascal Borreli's avatar
Pascal Borreli committed
755
     * Executes an, optionally parametrized, SQL query and returns the result,
756
     * applying a given projection/transformation function on each row of the result.
757
     *
Benjamin Morel's avatar
Benjamin Morel committed
758 759 760 761 762 763
     * @param string   $query    The SQL query to execute.
     * @param array    $params   The parameters, if any.
     * @param \Closure $function The transformation function that is applied on each row.
     *                           The function receives a single parameter, an array, that
     *                           represents a row of the result set.
     *
764
     * @return mixed The projected result of the query.
765
     */
766
    public function project($query, array $params, Closure $function)
767 768
    {
        $result = array();
769
        $stmt = $this->executeQuery($query, $params ?: array());
770

771
        while ($row = $stmt->fetch()) {
772
            $result[] = $function($row);
773
        }
774

775
        $stmt->closeCursor();
776

777 778
        return $result;
    }
romanb's avatar
romanb committed
779 780

    /**
781
     * Executes an SQL statement, returning a result set as a Statement object.
782
     *
783
     * @return \Doctrine\DBAL\Driver\Statement
Benjamin Morel's avatar
Benjamin Morel committed
784 785
     *
     * @throws \Doctrine\DBAL\DBALException
786 787 788
     */
    public function query()
    {
789 790
        $this->connect();

791 792
        $args = func_get_args();

793
        $logger = $this->_config->getSQLLogger();
794 795 796 797
        if ($logger) {
            $logger->startQuery($args[0]);
        }

798
        try {
799 800 801 802 803 804 805 806 807 808 809
            switch (func_num_args()) {
                case 1:
                    $statement = $this->_conn->query($args[0]);
                    break;
                case 2:
                    $statement = $this->_conn->query($args[0], $args[1]);
                    break;
                default:
                    $statement = call_user_func_array(array($this->_conn, 'query'), $args);
                    break;
            }
810
        } catch (\Exception $ex) {
811
            throw DBALException::driverExceptionDuringQuery($ex, $args[0]);
812 813
        }

814
        $statement->setFetchMode($this->defaultFetchMode);
815 816 817 818 819 820

        if ($logger) {
            $logger->stopQuery();
        }

        return $statement;
821 822 823 824 825
    }

    /**
     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
     * and returns the number of affected rows.
826
     *
827
     * This method supports PDO binding types as well as DBAL mapping types.
romanb's avatar
romanb committed
828
     *
Benjamin Morel's avatar
Benjamin Morel committed
829 830 831 832
     * @param string $query  The SQL query.
     * @param array  $params The query parameters.
     * @param array  $types  The parameter types.
     *
833
     * @return integer The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
834 835 836
     *
     * @throws \Doctrine\DBAL\DBALException
     *
837
     * @internal PERF: Directly prepares a driver statement, not a wrapper.
romanb's avatar
romanb committed
838
     */
839
    public function executeUpdate($query, array $params = array(), array $types = array())
romanb's avatar
romanb committed
840 841 842
    {
        $this->connect();

843 844 845
        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($query, $params, $types);
romanb's avatar
romanb committed
846 847
        }

848 849 850
        try {
            if ($params) {
                list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
851

852 853 854 855 856 857 858 859
                $stmt = $this->_conn->prepare($query);
                if ($types) {
                    $this->_bindTypedValues($stmt, $params, $types);
                    $stmt->execute();
                } else {
                    $stmt->execute($params);
                }
                $result = $stmt->rowCount();
860
            } else {
861
                $result = $this->_conn->exec($query);
862
            }
863 864
        } catch (\Exception $ex) {
            throw DBALException::driverExceptionDuringQuery($ex, $query, $this->resolveParams($params, $types));
romanb's avatar
romanb committed
865
        }
866

867 868
        if ($logger) {
            $logger->stopQuery();
869 870
        }

romanb's avatar
romanb committed
871
        return $result;
romanb's avatar
romanb committed
872 873
    }

874
    /**
Benjamin Morel's avatar
Benjamin Morel committed
875
     * Executes an SQL statement and return the number of affected rows.
876
     *
877
     * @param string $statement
Benjamin Morel's avatar
Benjamin Morel committed
878
     *
879
     * @return integer The number of affected rows.
Benjamin Morel's avatar
Benjamin Morel committed
880 881
     *
     * @throws \Doctrine\DBAL\DBALException
882 883 884 885
     */
    public function exec($statement)
    {
        $this->connect();
886 887 888 889 890 891

        $logger = $this->_config->getSQLLogger();
        if ($logger) {
            $logger->startQuery($statement);
        }

892 893 894 895 896
        try {
            $result = $this->_conn->exec($statement);
        } catch (\Exception $ex) {
            throw DBALException::driverExceptionDuringQuery($ex, $statement);
        }
897 898 899 900 901 902

        if ($logger) {
            $logger->stopQuery();
        }

        return $result;
903 904
    }

905 906 907 908 909 910 911 912 913 914
    /**
     * Returns the current transaction nesting level.
     *
     * @return integer The nesting level. A value of 0 means there's no active transaction.
     */
    public function getTransactionNestingLevel()
    {
        return $this->_transactionNestingLevel;
    }

romanb's avatar
romanb committed
915
    /**
Benjamin Morel's avatar
Benjamin Morel committed
916
     * Fetches the SQLSTATE associated with the last database operation.
romanb's avatar
romanb committed
917
     *
918
     * @return integer The last error code.
romanb's avatar
romanb committed
919 920 921 922
     */
    public function errorCode()
    {
        $this->connect();
Benjamin Morel's avatar
Benjamin Morel committed
923

romanb's avatar
romanb committed
924 925 926 927
        return $this->_conn->errorCode();
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
928
     * Fetches extended error information associated with the last database operation.
romanb's avatar
romanb committed
929
     *
930
     * @return array The last error information.
romanb's avatar
romanb committed
931 932 933 934
     */
    public function errorInfo()
    {
        $this->connect();
Benjamin Morel's avatar
Benjamin Morel committed
935

romanb's avatar
romanb committed
936 937 938 939 940 941 942 943
        return $this->_conn->errorInfo();
    }

    /**
     * Returns the ID of the last inserted row, or the last value from a sequence object,
     * depending on the underlying driver.
     *
     * Note: This method may not return a meaningful or consistent result across different drivers,
944 945
     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
     * columns or sequences.
romanb's avatar
romanb committed
946
     *
Benjamin Morel's avatar
Benjamin Morel committed
947 948
     * @param string|null $seqName Name of the sequence object from which the ID should be returned.
     *
949
     * @return string A string representation of the last inserted ID.
romanb's avatar
romanb committed
950
     */
romanb's avatar
romanb committed
951 952 953
    public function lastInsertId($seqName = null)
    {
        $this->connect();
Benjamin Morel's avatar
Benjamin Morel committed
954

romanb's avatar
romanb committed
955 956
        return $this->_conn->lastInsertId($seqName);
    }
957

958 959 960 961 962 963 964 965
    /**
     * Executes a function in a transaction.
     *
     * The function gets passed this Connection instance as an (optional) parameter.
     *
     * If an exception occurs during execution of the function or transaction commit,
     * the transaction is rolled back and the exception re-thrown.
     *
Benjamin Morel's avatar
Benjamin Morel committed
966 967 968 969 970
     * @param \Closure $func The function to execute transactionally.
     *
     * @return void
     *
     * @throws \Exception
971 972 973 974 975 976 977 978 979 980 981 982 983
     */
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
            $func($this);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }
    }

984
    /**
Benjamin Morel's avatar
Benjamin Morel committed
985
     * Sets if nested transactions should use savepoints.
986
     *
987
     * @param boolean $nestTransactionsWithSavepoints
Benjamin Morel's avatar
Benjamin Morel committed
988
     *
989
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
990 991
     *
     * @throws \Doctrine\DBAL\ConnectionException
992 993 994
     */
    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
    {
995 996 997 998
        if ($this->_transactionNestingLevel > 0) {
            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
        }

999
        if ( ! $this->_platform->supportsSavepoints()) {
1000
            throw ConnectionException::savepointsNotSupported();
1001 1002 1003 1004 1005 1006
        }

        $this->_nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1007
     * Gets if nested transactions should use savepoints.
1008 1009 1010 1011 1012 1013 1014 1015
     *
     * @return boolean
     */
    public function getNestTransactionsWithSavepoints()
    {
        return $this->_nestTransactionsWithSavepoints;
    }

1016 1017 1018 1019
    /**
     * Returns the savepoint name to use for nested transactions are false if they are not supported
     * "savepointFormat" parameter is not set
     *
Benjamin Morel's avatar
Benjamin Morel committed
1020
     * @return mixed A string with the savepoint name or false.
1021
     */
1022 1023 1024
    protected function _getNestedTransactionSavePointName()
    {
        return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel;
1025 1026
    }

1027 1028 1029 1030 1031 1032 1033 1034 1035
    /**
     * Starts a transaction by suspending auto-commit mode.
     *
     * @return void
     */
    public function beginTransaction()
    {
        $this->connect();

1036 1037
        ++$this->_transactionNestingLevel;

1038 1039
        $logger = $this->_config->getSQLLogger();

1040
        if ($this->_transactionNestingLevel == 1) {
1041 1042 1043
            if ($logger) {
                $logger->startQuery('"START TRANSACTION"');
            }
1044
            $this->_conn->beginTransaction();
1045 1046 1047
            if ($logger) {
                $logger->stopQuery();
            }
1048
        } else if ($this->_nestTransactionsWithSavepoints) {
1049 1050 1051
            if ($logger) {
                $logger->startQuery('"SAVEPOINT"');
            }
1052
            $this->createSavepoint($this->_getNestedTransactionSavePointName());
1053 1054 1055
            if ($logger) {
                $logger->stopQuery();
            }
1056 1057 1058 1059 1060 1061 1062
        }
    }

    /**
     * Commits the current transaction.
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1063 1064 1065
     *
     * @throws \Doctrine\DBAL\ConnectionException If the commit failed due to no active transaction or
     *                                            because the transaction was marked for rollback only.
1066 1067 1068 1069
     */
    public function commit()
    {
        if ($this->_transactionNestingLevel == 0) {
1070
            throw ConnectionException::noActiveTransaction();
1071 1072 1073 1074 1075 1076 1077
        }
        if ($this->_isRollbackOnly) {
            throw ConnectionException::commitFailedRollbackOnly();
        }

        $this->connect();

1078 1079
        $logger = $this->_config->getSQLLogger();

1080
        if ($this->_transactionNestingLevel == 1) {
1081 1082 1083
            if ($logger) {
                $logger->startQuery('"COMMIT"');
            }
1084
            $this->_conn->commit();
1085 1086 1087
            if ($logger) {
                $logger->stopQuery();
            }
1088
        } else if ($this->_nestTransactionsWithSavepoints) {
1089 1090 1091
            if ($logger) {
                $logger->startQuery('"RELEASE SAVEPOINT"');
            }
1092
            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
1093 1094 1095
            if ($logger) {
                $logger->stopQuery();
            }
1096 1097 1098 1099 1100 1101
        }

        --$this->_transactionNestingLevel;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1102
     * Cancels any database changes done during the current transaction.
1103
     *
Benjamin Morel's avatar
Benjamin Morel committed
1104 1105
     * This method can be listened with onPreTransactionRollback and onTransactionRollback
     * eventlistener methods.
1106
     *
Benjamin Morel's avatar
Benjamin Morel committed
1107
     * @throws \Doctrine\DBAL\ConnectionException If the rollback operation failed.
1108
     */
1109
    public function rollBack()
1110 1111
    {
        if ($this->_transactionNestingLevel == 0) {
1112
            throw ConnectionException::noActiveTransaction();
1113 1114 1115 1116
        }

        $this->connect();

1117 1118
        $logger = $this->_config->getSQLLogger();

1119
        if ($this->_transactionNestingLevel == 1) {
1120 1121 1122
            if ($logger) {
                $logger->startQuery('"ROLLBACK"');
            }
1123 1124 1125
            $this->_transactionNestingLevel = 0;
            $this->_conn->rollback();
            $this->_isRollbackOnly = false;
1126 1127 1128
            if ($logger) {
                $logger->stopQuery();
            }
1129
        } else if ($this->_nestTransactionsWithSavepoints) {
1130 1131 1132
            if ($logger) {
                $logger->startQuery('"ROLLBACK TO SAVEPOINT"');
            }
1133 1134
            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
            --$this->_transactionNestingLevel;
1135 1136 1137
            if ($logger) {
                $logger->stopQuery();
            }
1138
        } else {
1139
            $this->_isRollbackOnly = true;
1140 1141 1142 1143
            --$this->_transactionNestingLevel;
        }
    }

1144
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1145 1146 1147
     * Creates a new savepoint.
     *
     * @param string $savepoint The name of the savepoint to create.
1148 1149
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1150 1151
     *
     * @throws \Doctrine\DBAL\ConnectionException
1152
     */
1153
    public function createSavepoint($savepoint)
1154
    {
1155
        if ( ! $this->_platform->supportsSavepoints()) {
1156
            throw ConnectionException::savepointsNotSupported();
1157 1158
        }

1159
        $this->_conn->exec($this->_platform->createSavePoint($savepoint));
1160 1161 1162
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1163 1164 1165
     * Releases the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to release.
1166 1167
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1168 1169
     *
     * @throws \Doctrine\DBAL\ConnectionException
1170
     */
1171
    public function releaseSavepoint($savepoint)
1172
    {
1173
        if ( ! $this->_platform->supportsSavepoints()) {
1174
            throw ConnectionException::savepointsNotSupported();
1175 1176
        }

1177 1178
        if ($this->_platform->supportsReleaseSavepoints()) {
            $this->_conn->exec($this->_platform->releaseSavePoint($savepoint));
1179
        }
1180 1181 1182
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1183 1184 1185
     * Rolls back to the given savepoint.
     *
     * @param string $savepoint The name of the savepoint to rollback to.
1186 1187
     *
     * @return void
Benjamin Morel's avatar
Benjamin Morel committed
1188 1189
     *
     * @throws \Doctrine\DBAL\ConnectionException
1190
     */
1191
    public function rollbackSavepoint($savepoint)
1192
    {
1193
        if ( ! $this->_platform->supportsSavepoints()) {
1194
            throw ConnectionException::savepointsNotSupported();
1195 1196
        }

1197
        $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
1198 1199
    }

romanb's avatar
romanb committed
1200 1201 1202
    /**
     * Gets the wrapped driver connection.
     *
1203
     * @return \Doctrine\DBAL\Driver\Connection
romanb's avatar
romanb committed
1204 1205 1206 1207
     */
    public function getWrappedConnection()
    {
        $this->connect();
1208

romanb's avatar
romanb committed
1209 1210
        return $this->_conn;
    }
1211

romanb's avatar
romanb committed
1212 1213 1214 1215
    /**
     * Gets the SchemaManager that can be used to inspect or change the
     * database schema through the connection.
     *
1216
     * @return \Doctrine\DBAL\Schema\AbstractSchemaManager
romanb's avatar
romanb committed
1217 1218 1219 1220 1221 1222
     */
    public function getSchemaManager()
    {
        if ( ! $this->_schemaManager) {
            $this->_schemaManager = $this->_driver->getSchemaManager($this);
        }
1223

romanb's avatar
romanb committed
1224 1225
        return $this->_schemaManager;
    }
1226

1227 1228 1229
    /**
     * Marks the current transaction so that the only possible
     * outcome for the transaction to be rolled back.
1230
     *
Benjamin Morel's avatar
Benjamin Morel committed
1231 1232 1233
     * @return void
     *
     * @throws \Doctrine\DBAL\ConnectionException If no transaction is active.
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
     */
    public function setRollbackOnly()
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
        $this->_isRollbackOnly = true;
    }

    /**
Benjamin Morel's avatar
Benjamin Morel committed
1244
     * Checks whether the current transaction is marked for rollback only.
1245
     *
1246
     * @return boolean
Benjamin Morel's avatar
Benjamin Morel committed
1247 1248
     *
     * @throws \Doctrine\DBAL\ConnectionException If no transaction is active.
1249
     */
1250
    public function isRollbackOnly()
1251 1252 1253 1254
    {
        if ($this->_transactionNestingLevel == 0) {
            throw ConnectionException::noActiveTransaction();
        }
Benjamin Morel's avatar
Benjamin Morel committed
1255

1256 1257 1258
        return $this->_isRollbackOnly;
    }

1259 1260 1261
    /**
     * Converts a given value to its database representation according to the conversion
     * rules of a specific DBAL mapping type.
1262
     *
Benjamin Morel's avatar
Benjamin Morel committed
1263 1264 1265
     * @param mixed  $value The value to convert.
     * @param string $type  The name of the DBAL mapping type.
     *
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
     * @return mixed The converted value.
     */
    public function convertToDatabaseValue($value, $type)
    {
        return Type::getType($type)->convertToDatabaseValue($value, $this->_platform);
    }

    /**
     * Converts a given value to its PHP representation according to the conversion
     * rules of a specific DBAL mapping type.
1276
     *
Benjamin Morel's avatar
Benjamin Morel committed
1277 1278 1279
     * @param mixed  $value The value to convert.
     * @param string $type  The name of the DBAL mapping type.
     *
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
     * @return mixed The converted type.
     */
    public function convertToPHPValue($value, $type)
    {
        return Type::getType($type)->convertToPHPValue($value, $this->_platform);
    }

    /**
     * Binds a set of parameters, some or all of which are typed with a PDO binding type
     * or DBAL mapping type, to a given statement.
1290
     *
Benjamin Morel's avatar
Benjamin Morel committed
1291 1292 1293 1294 1295 1296
     * @param \Doctrine\DBAL\Driver\Statement $stmt   The statement to bind the values to.
     * @param array                           $params The map/list of named/positional parameters.
     * @param array                           $types  The parameter types (PDO binding types or DBAL mapping types).
     *
     * @return void
     *
1297 1298
     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
     *           raw PDOStatement instances.
1299
     */
1300
    private function _bindTypedValues($stmt, array $params, array $types)
1301 1302 1303 1304
    {
        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
1305
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1306
            $bindIndex = 1;
1307
            foreach ($params as $value) {
1308 1309 1310
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
                    $type = $types[$typeIndex];
1311
                    list($value, $bindingType) = $this->getBindingInfo($value, $type);
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
                    $stmt->bindValue($bindIndex, $value, $bindingType);
                } else {
                    $stmt->bindValue($bindIndex, $value);
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
                    $type = $types[$name];
1323
                    list($value, $bindingType) = $this->getBindingInfo($value, $type);
1324 1325 1326 1327 1328 1329 1330
                    $stmt->bindValue($name, $value, $bindingType);
                } else {
                    $stmt->bindValue($name, $value);
                }
            }
        }
    }
1331 1332 1333 1334

    /**
     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
     *
Benjamin Morel's avatar
Benjamin Morel committed
1335 1336 1337 1338
     * @param mixed $value The value to bind.
     * @param mixed $type  The type to bind (PDO or DBAL).
     *
     * @return array [0] => the (escaped) value, [1] => the binding type.
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
     */
    private function getBindingInfo($value, $type)
    {
        if (is_string($type)) {
            $type = Type::getType($type);
        }
        if ($type instanceof Type) {
            $value = $type->convertToDatabaseValue($value, $this->_platform);
            $bindingType = $type->getBindingType();
        } else {
            $bindingType = $type; // PDO::PARAM_* constants
        }
Benjamin Morel's avatar
Benjamin Morel committed
1351

1352 1353 1354
        return array($value, $bindingType);
    }

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    /**
     * Resolves the parameters to a format which can be displayed.
     *
     * @internal This is a purely internal method. If you rely on this method, you are advised to
     *           copy/paste the code as this method may change, or be removed without prior notice.
     *
     * @param array $params
     * @param array $types
     *
     * @return array
     */
    public function resolveParams(array $params, array $types)
    {
        $resolvedParams = array();

        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
        if (is_int(key($params))) {
            // Positional parameters
            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
            $bindIndex = 1;
            foreach ($params as $value) {
                $typeIndex = $bindIndex + $typeOffset;
                if (isset($types[$typeIndex])) {
                    $type = $types[$typeIndex];
                    list($value,) = $this->getBindingInfo($value, $type);
                    $resolvedParams[$bindIndex] = $value;
                } else {
                    $resolvedParams[$bindIndex] = $value;
                }
                ++$bindIndex;
            }
        } else {
            // Named parameters
            foreach ($params as $name => $value) {
                if (isset($types[$name])) {
                    $type = $types[$name];
                    list($value,) = $this->getBindingInfo($value, $type);
                    $resolvedParams[$name] = $value;
                } else {
                    $resolvedParams[$name] = $value;
                }
            }
        }

        return $resolvedParams;
    }

1402
    /**
Benjamin Morel's avatar
Benjamin Morel committed
1403
     * Creates a new instance of a SQL query builder.
1404
     *
1405
     * @return \Doctrine\DBAL\Query\QueryBuilder
1406 1407 1408 1409 1410
     */
    public function createQueryBuilder()
    {
        return new Query\QueryBuilder($this);
    }
1411
}