source: pro-violet-viettel/sourcecode/application/libraries/Doctrine/DBAL/Connection.php @ 356

Last change on this file since 356 was 345, checked in by quyenla, 11 years ago

collaborator page

File size: 34.3 KB
Line 
1<?php
2/*
3 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14 *
15 * This software consists of voluntary contributions made by many individuals
16 * and is licensed under the LGPL. For more information, see
17 * <http://www.doctrine-project.org>.
18 */
19
20namespace Doctrine\DBAL;
21
22use PDO, Closure, Exception,
23    Doctrine\DBAL\Types\Type,
24    Doctrine\DBAL\Driver\Connection as DriverConnection,
25    Doctrine\Common\EventManager,
26    Doctrine\DBAL\DBALException,
27    Doctrine\DBAL\Cache\ResultCacheStatement,
28    Doctrine\DBAL\Cache\QueryCacheProfile,
29    Doctrine\DBAL\Cache\ArrayStatement,
30    Doctrine\DBAL\Cache\CacheException;
31
32/**
33 * A wrapper around a Doctrine\DBAL\Driver\Connection that adds features like
34 * events, transaction isolation levels, configuration, emulated transaction nesting,
35 * lazy connecting and more.
36 *
37 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
38 * @link    www.doctrine-project.org
39 * @since   2.0
40 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
41 * @author  Jonathan Wage <jonwage@gmail.com>
42 * @author  Roman Borschel <roman@code-factory.org>
43 * @author  Konsta Vesterinen <kvesteri@cc.hut.fi>
44 * @author  Lukas Smith <smith@pooteeweet.org> (MDB2 library)
45 * @author  Benjamin Eberlei <kontakt@beberlei.de>
46 */
47class Connection implements DriverConnection
48{
49    /**
50     * Constant for transaction isolation level READ UNCOMMITTED.
51     */
52    const TRANSACTION_READ_UNCOMMITTED = 1;
53
54    /**
55     * Constant for transaction isolation level READ COMMITTED.
56     */
57    const TRANSACTION_READ_COMMITTED = 2;
58
59    /**
60     * Constant for transaction isolation level REPEATABLE READ.
61     */
62    const TRANSACTION_REPEATABLE_READ = 3;
63
64    /**
65     * Constant for transaction isolation level SERIALIZABLE.
66     */
67    const TRANSACTION_SERIALIZABLE = 4;
68
69    /**
70     * Represents an array of ints to be expanded by Doctrine SQL parsing.
71     *
72     * @var int
73     */
74    const PARAM_INT_ARRAY = 101;
75
76    /**
77     * Represents an array of strings to be expanded by Doctrine SQL parsing.
78     *
79     * @var int
80     */
81    const PARAM_STR_ARRAY = 102;
82
83    /**
84     * Offset by which PARAM_* constants are detected as arrays of the param type.
85     *
86     * @var int
87     */
88    const ARRAY_PARAM_OFFSET = 100;
89
90    /**
91     * The wrapped driver connection.
92     *
93     * @var Doctrine\DBAL\Driver\Connection
94     */
95    protected $_conn;
96
97    /**
98     * @var Doctrine\DBAL\Configuration
99     */
100    protected $_config;
101
102    /**
103     * @var Doctrine\Common\EventManager
104     */
105    protected $_eventManager;
106
107    /**
108     * @var Doctrine\DBAL\Query\ExpressionBuilder
109     */
110    protected $_expr;
111
112    /**
113     * Whether or not a connection has been established.
114     *
115     * @var boolean
116     */
117    private $_isConnected = false;
118
119    /**
120     * The transaction nesting level.
121     *
122     * @var integer
123     */
124    private $_transactionNestingLevel = 0;
125
126    /**
127     * The currently active transaction isolation level.
128     *
129     * @var integer
130     */
131    private $_transactionIsolationLevel;
132
133    /**
134     * If nested transations should use savepoints
135     *
136     * @var integer
137     */
138    private $_nestTransactionsWithSavepoints;
139
140    /**
141     * The parameters used during creation of the Connection instance.
142     *
143     * @var array
144     */
145    private $_params = array();
146
147    /**
148     * The DatabasePlatform object that provides information about the
149     * database platform used by the connection.
150     *
151     * @var Doctrine\DBAL\Platforms\AbstractPlatform
152     */
153    protected $_platform;
154
155    /**
156     * The schema manager.
157     *
158     * @var Doctrine\DBAL\Schema\SchemaManager
159     */
160    protected $_schemaManager;
161
162    /**
163     * The used DBAL driver.
164     *
165     * @var Doctrine\DBAL\Driver
166     */
167    protected $_driver;
168
169    /**
170     * Flag that indicates whether the current transaction is marked for rollback only.
171     *
172     * @var boolean
173     */
174    private $_isRollbackOnly = false;
175
176    /**
177     * Initializes a new instance of the Connection class.
178     *
179     * @param array $params  The connection parameters.
180     * @param Driver $driver
181     * @param Configuration $config
182     * @param EventManager $eventManager
183     */
184    public function __construct(array $params, Driver $driver, Configuration $config = null,
185            EventManager $eventManager = null)
186    {
187        $this->_driver = $driver;
188        $this->_params = $params;
189
190        if (isset($params['pdo'])) {
191            $this->_conn = $params['pdo'];
192            $this->_isConnected = true;
193        }
194
195        // Create default config and event manager if none given
196        if ( ! $config) {
197            $config = new Configuration();
198        }
199
200        if ( ! $eventManager) {
201            $eventManager = new EventManager();
202        }
203
204        $this->_config = $config;
205        $this->_eventManager = $eventManager;
206
207        $this->_expr = new Query\Expression\ExpressionBuilder($this);
208
209        if ( ! isset($params['platform'])) {
210            $this->_platform = $driver->getDatabasePlatform();
211        } else if ($params['platform'] instanceof Platforms\AbstractPlatform) {
212            $this->_platform = $params['platform'];
213        } else {
214            throw DBALException::invalidPlatformSpecified();
215        }
216
217        $this->_platform->setEventManager($eventManager);
218
219        $this->_transactionIsolationLevel = $this->_platform->getDefaultTransactionIsolationLevel();
220    }
221
222    /**
223     * Gets the parameters used during instantiation.
224     *
225     * @return array $params
226     */
227    public function getParams()
228    {
229        return $this->_params;
230    }
231
232    /**
233     * Gets the name of the database this Connection is connected to.
234     *
235     * @return string $database
236     */
237    public function getDatabase()
238    {
239        return $this->_driver->getDatabase($this);
240    }
241
242    /**
243     * Gets the hostname of the currently connected database.
244     *
245     * @return string
246     */
247    public function getHost()
248    {
249        return isset($this->_params['host']) ? $this->_params['host'] : null;
250    }
251
252    /**
253     * Gets the port of the currently connected database.
254     *
255     * @return mixed
256     */
257    public function getPort()
258    {
259        return isset($this->_params['port']) ? $this->_params['port'] : null;
260    }
261
262    /**
263     * Gets the username used by this connection.
264     *
265     * @return string
266     */
267    public function getUsername()
268    {
269        return isset($this->_params['user']) ? $this->_params['user'] : null;
270    }
271
272    /**
273     * Gets the password used by this connection.
274     *
275     * @return string
276     */
277    public function getPassword()
278    {
279        return isset($this->_params['password']) ? $this->_params['password'] : null;
280    }
281
282    /**
283     * Gets the DBAL driver instance.
284     *
285     * @return \Doctrine\DBAL\Driver
286     */
287    public function getDriver()
288    {
289        return $this->_driver;
290    }
291
292    /**
293     * Gets the Configuration used by the Connection.
294     *
295     * @return \Doctrine\DBAL\Configuration
296     */
297    public function getConfiguration()
298    {
299        return $this->_config;
300    }
301
302    /**
303     * Gets the EventManager used by the Connection.
304     *
305     * @return \Doctrine\Common\EventManager
306     */
307    public function getEventManager()
308    {
309        return $this->_eventManager;
310    }
311
312    /**
313     * Gets the DatabasePlatform for the connection.
314     *
315     * @return \Doctrine\DBAL\Platforms\AbstractPlatform
316     */
317    public function getDatabasePlatform()
318    {
319        return $this->_platform;
320    }
321
322    /**
323     * Gets the ExpressionBuilder for the connection.
324     *
325     * @return \Doctrine\DBAL\Query\ExpressionBuilder
326     */
327    public function getExpressionBuilder()
328    {
329        return $this->_expr;
330    }
331
332    /**
333     * Establishes the connection with the database.
334     *
335     * @return boolean TRUE if the connection was successfully established, FALSE if
336     *                 the connection is already open.
337     */
338    public function connect()
339    {
340        if ($this->_isConnected) return false;
341
342        $driverOptions = isset($this->_params['driverOptions']) ?
343                $this->_params['driverOptions'] : array();
344        $user = isset($this->_params['user']) ? $this->_params['user'] : null;
345        $password = isset($this->_params['password']) ?
346                $this->_params['password'] : null;
347
348        $this->_conn = $this->_driver->connect($this->_params, $user, $password, $driverOptions);
349        $this->_isConnected = true;
350
351        if ($this->_eventManager->hasListeners(Events::postConnect)) {
352            $eventArgs = new Event\ConnectionEventArgs($this);
353            $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
354        }
355
356        return true;
357    }
358
359    /**
360     * Prepares and executes an SQL query and returns the first row of the result
361     * as an associative array.
362     *
363     * @param string $statement The SQL query.
364     * @param array $params The query parameters.
365     * @return array
366     */
367    public function fetchAssoc($statement, array $params = array())
368    {
369        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_ASSOC);
370    }
371
372    /**
373     * Prepares and executes an SQL query and returns the first row of the result
374     * as a numerically indexed array.
375     *
376     * @param string $statement         sql query to be executed
377     * @param array $params             prepared statement params
378     * @return array
379     */
380    public function fetchArray($statement, array $params = array())
381    {
382        return $this->executeQuery($statement, $params)->fetch(PDO::FETCH_NUM);
383    }
384
385    /**
386     * Prepares and executes an SQL query and returns the value of a single column
387     * of the first row of the result.
388     *
389     * @param string $statement         sql query to be executed
390     * @param array $params             prepared statement params
391     * @param int $colnum               0-indexed column number to retrieve
392     * @return mixed
393     */
394    public function fetchColumn($statement, array $params = array(), $colnum = 0)
395    {
396        return $this->executeQuery($statement, $params)->fetchColumn($colnum);
397    }
398
399    /**
400     * Whether an actual connection to the database is established.
401     *
402     * @return boolean
403     */
404    public function isConnected()
405    {
406        return $this->_isConnected;
407    }
408
409    /**
410     * Checks whether a transaction is currently active.
411     *
412     * @return boolean TRUE if a transaction is currently active, FALSE otherwise.
413     */
414    public function isTransactionActive()
415    {
416        return $this->_transactionNestingLevel > 0;
417    }
418
419    /**
420     * Executes an SQL DELETE statement on a table.
421     *
422     * @param string $table The name of the table on which to delete.
423     * @param array $identifier The deletion criteria. An associateve array containing column-value pairs.
424     * @return integer The number of affected rows.
425     */
426    public function delete($tableName, array $identifier)
427    {
428        $this->connect();
429
430        $criteria = array();
431
432        foreach (array_keys($identifier) as $columnName) {
433            $criteria[] = $columnName . ' = ?';
434        }
435
436        $query = 'DELETE FROM ' . $tableName . ' WHERE ' . implode(' AND ', $criteria);
437
438        return $this->executeUpdate($query, array_values($identifier));
439    }
440
441    /**
442     * Closes the connection.
443     *
444     * @return void
445     */
446    public function close()
447    {
448        unset($this->_conn);
449
450        $this->_isConnected = false;
451    }
452
453    /**
454     * Sets the transaction isolation level.
455     *
456     * @param integer $level The level to set.
457     */
458    public function setTransactionIsolation($level)
459    {
460        $this->_transactionIsolationLevel = $level;
461
462        return $this->executeUpdate($this->_platform->getSetTransactionIsolationSQL($level));
463    }
464
465    /**
466     * Gets the currently active transaction isolation level.
467     *
468     * @return integer The current transaction isolation level.
469     */
470    public function getTransactionIsolation()
471    {
472        return $this->_transactionIsolationLevel;
473    }
474
475    /**
476     * Executes an SQL UPDATE statement on a table.
477     *
478     * @param string $table The name of the table to update.
479     * @param array $identifier The update criteria. An associative array containing column-value pairs.
480     * @param array $types Types of the merged $data and $identifier arrays in that order.
481     * @return integer The number of affected rows.
482     */
483    public function update($tableName, array $data, array $identifier, array $types = array())
484    {
485        $this->connect();
486        $set = array();
487        foreach ($data as $columnName => $value) {
488            $set[] = $columnName . ' = ?';
489        }
490
491        $params = array_merge(array_values($data), array_values($identifier));
492
493        $sql  = 'UPDATE ' . $tableName . ' SET ' . implode(', ', $set)
494                . ' WHERE ' . implode(' = ? AND ', array_keys($identifier))
495                . ' = ?';
496
497        return $this->executeUpdate($sql, $params, $types);
498    }
499
500    /**
501     * Inserts a table row with specified data.
502     *
503     * @param string $table The name of the table to insert data into.
504     * @param array $data An associative array containing column-value pairs.
505     * @param array $types Types of the inserted data.
506     * @return integer The number of affected rows.
507     */
508    public function insert($tableName, array $data, array $types = array())
509    {
510        $this->connect();
511
512        // column names are specified as array keys
513        $cols = array();
514        $placeholders = array();
515
516        foreach ($data as $columnName => $value) {
517            $cols[] = $columnName;
518            $placeholders[] = '?';
519        }
520
521        $query = 'INSERT INTO ' . $tableName
522               . ' (' . implode(', ', $cols) . ')'
523               . ' VALUES (' . implode(', ', $placeholders) . ')';
524
525        return $this->executeUpdate($query, array_values($data), $types);
526    }
527
528    /**
529     * Sets the given charset on the current connection.
530     *
531     * @param string $charset The charset to set.
532     */
533    public function setCharset($charset)
534    {
535        $this->executeUpdate($this->_platform->getSetCharsetSQL($charset));
536    }
537
538    /**
539     * Quote a string so it can be safely used as a table or column name, even if
540     * it is a reserved name.
541     *
542     * Delimiting style depends on the underlying database platform that is being used.
543     *
544     * NOTE: Just because you CAN use quoted identifiers does not mean
545     * you SHOULD use them. In general, they end up causing way more
546     * problems than they solve.
547     *
548     * @param string $str The name to be quoted.
549     * @return string The quoted name.
550     */
551    public function quoteIdentifier($str)
552    {
553        return $this->_platform->quoteIdentifier($str);
554    }
555
556    /**
557     * Quotes a given input parameter.
558     *
559     * @param mixed $input Parameter to be quoted.
560     * @param string $type Type of the parameter.
561     * @return string The quoted parameter.
562     */
563    public function quote($input, $type = null)
564    {
565        $this->connect();
566
567        list($value, $bindingType) = $this->getBindingInfo($input, $type);
568        return $this->_conn->quote($value, $bindingType);
569    }
570
571    /**
572     * Prepares and executes an SQL query and returns the result as an associative array.
573     *
574     * @param string $sql The SQL query.
575     * @param array $params The query parameters.
576     * @return array
577     */
578    public function fetchAll($sql, array $params = array())
579    {
580        return $this->executeQuery($sql, $params)->fetchAll(PDO::FETCH_ASSOC);
581    }
582
583    /**
584     * Prepares an SQL statement.
585     *
586     * @param string $statement The SQL statement to prepare.
587     * @return Doctrine\DBAL\Driver\Statement The prepared statement.
588     */
589    public function prepare($statement)
590    {
591        $this->connect();
592
593        return new Statement($statement, $this);
594    }
595
596    /**
597     * Executes an, optionally parameterized, SQL query.
598     *
599     * If the query is parameterized, a prepared statement is used.
600     * If an SQLLogger is configured, the execution is logged.
601     *
602     * @param string $query The SQL query to execute.
603     * @param array $params The parameters to bind to the query, if any.
604     * @param array $types The types the previous parameters are in.
605     * @param QueryCacheProfile $qcp
606     * @return Doctrine\DBAL\Driver\Statement The executed statement.
607     * @internal PERF: Directly prepares a driver statement, not a wrapper.
608     */
609    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
610    {
611        if ($qcp !== null) {
612            return $this->executeCacheQuery($query, $params, $types, $qcp);
613        }
614
615        $this->connect();
616
617        $hasLogger = $this->_config->getSQLLogger() !== null;
618        if ($hasLogger) {
619            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
620        }
621
622        if ($params) {
623            list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
624
625            $stmt = $this->_conn->prepare($query);
626            if ($types) {
627                $this->_bindTypedValues($stmt, $params, $types);
628                $stmt->execute();
629            } else {
630                $stmt->execute($params);
631            }
632        } else {
633            $stmt = $this->_conn->query($query);
634        }
635
636        if ($hasLogger) {
637            $this->_config->getSQLLogger()->stopQuery();
638        }
639
640        return $stmt;
641    }
642
643    /**
644     * Execute a caching query and
645     *
646     * @param string $query
647     * @param array $params
648     * @param array $types
649     * @param QueryCacheProfile $qcp
650     * @return \Doctrine\DBAL\Driver\ResultStatement
651     */
652    public function executeCacheQuery($query, $params, $types, QueryCacheProfile $qcp)
653    {
654        $resultCache = $qcp->getResultCacheDriver() ?: $this->_config->getResultCacheImpl();
655        if (!$resultCache) {
656            throw CacheException::noResultDriverConfigured();
657        }
658
659        list($cacheKey, $realKey) = $qcp->generateCacheKeys($query, $params, $types);
660
661        // fetch the row pointers entry
662        if ($data = $resultCache->fetch($cacheKey)) {
663            // is the real key part of this row pointers map or is the cache only pointing to other cache keys?
664            if (isset($data[$realKey])) {
665                return new ArrayStatement($data[$realKey]);
666            } else if (array_key_exists($realKey, $data)) {
667                return new ArrayStatement(array());
668            }
669        }
670        return new ResultCacheStatement($this->executeQuery($query, $params, $types), $resultCache, $cacheKey, $realKey, $qcp->getLifetime());
671    }
672
673    /**
674     * Executes an, optionally parameterized, SQL query and returns the result,
675     * applying a given projection/transformation function on each row of the result.
676     *
677     * @param string $query The SQL query to execute.
678     * @param array $params The parameters, if any.
679     * @param Closure $mapper The transformation function that is applied on each row.
680     *                        The function receives a single paramater, an array, that
681     *                        represents a row of the result set.
682     * @return mixed The projected result of the query.
683     */
684    public function project($query, array $params, Closure $function)
685    {
686        $result = array();
687        $stmt = $this->executeQuery($query, $params ?: array());
688
689        while ($row = $stmt->fetch()) {
690            $result[] = $function($row);
691        }
692
693        $stmt->closeCursor();
694
695        return $result;
696    }
697
698    /**
699     * Executes an SQL statement, returning a result set as a Statement object.
700     *
701     * @param string $statement
702     * @param integer $fetchType
703     * @return Doctrine\DBAL\Driver\Statement
704     */
705    public function query()
706    {
707        $this->connect();
708
709        $args = func_get_args();
710
711        $logger = $this->getConfiguration()->getSQLLogger();
712        if ($logger) {
713            $logger->startQuery($args[0]);
714        }
715
716        $statement = call_user_func_array(array($this->_conn, 'query'), $args);
717
718        if ($logger) {
719            $logger->stopQuery();
720        }
721
722        return $statement;
723    }
724
725    /**
726     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
727     * and returns the number of affected rows.
728     *
729     * This method supports PDO binding types as well as DBAL mapping types.
730     *
731     * @param string $query The SQL query.
732     * @param array $params The query parameters.
733     * @param array $types The parameter types.
734     * @return integer The number of affected rows.
735     * @internal PERF: Directly prepares a driver statement, not a wrapper.
736     */
737    public function executeUpdate($query, array $params = array(), array $types = array())
738    {
739        $this->connect();
740
741        $hasLogger = $this->_config->getSQLLogger() !== null;
742        if ($hasLogger) {
743            $this->_config->getSQLLogger()->startQuery($query, $params, $types);
744        }
745
746        if ($params) {
747            list($query, $params, $types) = SQLParserUtils::expandListParameters($query, $params, $types);
748
749            $stmt = $this->_conn->prepare($query);
750            if ($types) {
751                $this->_bindTypedValues($stmt, $params, $types);
752                $stmt->execute();
753            } else {
754                $stmt->execute($params);
755            }
756            $result = $stmt->rowCount();
757        } else {
758            $result = $this->_conn->exec($query);
759        }
760
761        if ($hasLogger) {
762            $this->_config->getSQLLogger()->stopQuery();
763        }
764
765        return $result;
766    }
767
768    /**
769     * Execute an SQL statement and return the number of affected rows.
770     *
771     * @param string $statement
772     * @return integer The number of affected rows.
773     */
774    public function exec($statement)
775    {
776        $this->connect();
777        return $this->_conn->exec($statement);
778    }
779
780    /**
781     * Returns the current transaction nesting level.
782     *
783     * @return integer The nesting level. A value of 0 means there's no active transaction.
784     */
785    public function getTransactionNestingLevel()
786    {
787        return $this->_transactionNestingLevel;
788    }
789
790    /**
791     * Fetch the SQLSTATE associated with the last database operation.
792     *
793     * @return integer The last error code.
794     */
795    public function errorCode()
796    {
797        $this->connect();
798        return $this->_conn->errorCode();
799    }
800
801    /**
802     * Fetch extended error information associated with the last database operation.
803     *
804     * @return array The last error information.
805     */
806    public function errorInfo()
807    {
808        $this->connect();
809        return $this->_conn->errorInfo();
810    }
811
812    /**
813     * Returns the ID of the last inserted row, or the last value from a sequence object,
814     * depending on the underlying driver.
815     *
816     * Note: This method may not return a meaningful or consistent result across different drivers,
817     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
818     * columns or sequences.
819     *
820     * @param string $seqName Name of the sequence object from which the ID should be returned.
821     * @return string A string representation of the last inserted ID.
822     */
823    public function lastInsertId($seqName = null)
824    {
825        $this->connect();
826        return $this->_conn->lastInsertId($seqName);
827    }
828
829    /**
830     * Executes a function in a transaction.
831     *
832     * The function gets passed this Connection instance as an (optional) parameter.
833     *
834     * If an exception occurs during execution of the function or transaction commit,
835     * the transaction is rolled back and the exception re-thrown.
836     *
837     * @param Closure $func The function to execute transactionally.
838     */
839    public function transactional(Closure $func)
840    {
841        $this->beginTransaction();
842        try {
843            $func($this);
844            $this->commit();
845        } catch (Exception $e) {
846            $this->rollback();
847            throw $e;
848        }
849    }
850
851    /**
852     * Set if nested transactions should use savepoints
853     *
854     * @param boolean
855     * @return void
856     */
857    public function setNestTransactionsWithSavepoints($nestTransactionsWithSavepoints)
858    {
859        if ($this->_transactionNestingLevel > 0) {
860            throw ConnectionException::mayNotAlterNestedTransactionWithSavepointsInTransaction();
861        }
862
863        if (!$this->_platform->supportsSavepoints()) {
864            throw ConnectionException::savepointsNotSupported();
865        }
866
867        $this->_nestTransactionsWithSavepoints = $nestTransactionsWithSavepoints;
868    }
869
870    /**
871     * Get if nested transactions should use savepoints
872     *
873     * @return boolean
874     */
875    public function getNestTransactionsWithSavepoints()
876    {
877        return $this->_nestTransactionsWithSavepoints;
878    }
879
880    /**
881     * Returns the savepoint name to use for nested transactions are false if they are not supported
882     * "savepointFormat" parameter is not set
883     *
884     * @return mixed a string with the savepoint name or false
885     */
886    protected function _getNestedTransactionSavePointName()
887    {
888        return 'DOCTRINE2_SAVEPOINT_'.$this->_transactionNestingLevel;
889    }
890
891    /**
892     * Starts a transaction by suspending auto-commit mode.
893     *
894     * @return void
895     */
896    public function beginTransaction()
897    {
898        $this->connect();
899
900        ++$this->_transactionNestingLevel;
901
902        if ($this->_transactionNestingLevel == 1) {
903            $this->_conn->beginTransaction();
904        } else if ($this->_nestTransactionsWithSavepoints) {
905            $this->createSavepoint($this->_getNestedTransactionSavePointName());
906        }
907    }
908
909    /**
910     * Commits the current transaction.
911     *
912     * @return void
913     * @throws ConnectionException If the commit failed due to no active transaction or
914     *                             because the transaction was marked for rollback only.
915     */
916    public function commit()
917    {
918        if ($this->_transactionNestingLevel == 0) {
919            throw ConnectionException::noActiveTransaction();
920        }
921        if ($this->_isRollbackOnly) {
922            throw ConnectionException::commitFailedRollbackOnly();
923        }
924
925        $this->connect();
926
927        if ($this->_transactionNestingLevel == 1) {
928            $this->_conn->commit();
929        } else if ($this->_nestTransactionsWithSavepoints) {
930            $this->releaseSavepoint($this->_getNestedTransactionSavePointName());
931        }
932
933        --$this->_transactionNestingLevel;
934    }
935
936    /**
937     * Cancel any database changes done during the current transaction.
938     *
939     * this method can be listened with onPreTransactionRollback and onTransactionRollback
940     * eventlistener methods
941     *
942     * @throws ConnectionException If the rollback operation failed.
943     */
944    public function rollback()
945    {
946        if ($this->_transactionNestingLevel == 0) {
947            throw ConnectionException::noActiveTransaction();
948        }
949
950        $this->connect();
951
952        if ($this->_transactionNestingLevel == 1) {
953            $this->_transactionNestingLevel = 0;
954            $this->_conn->rollback();
955            $this->_isRollbackOnly = false;
956        } else if ($this->_nestTransactionsWithSavepoints) {
957            $this->rollbackSavepoint($this->_getNestedTransactionSavePointName());
958            --$this->_transactionNestingLevel;
959        } else {
960            $this->_isRollbackOnly = true;
961            --$this->_transactionNestingLevel;
962        }
963    }
964
965    /**
966     * createSavepoint
967     * creates a new savepoint
968     *
969     * @param string $savepoint     name of a savepoint to set
970     * @return void
971     */
972    public function createSavepoint($savepoint)
973    {
974        if (!$this->_platform->supportsSavepoints()) {
975            throw ConnectionException::savepointsNotSupported();
976        }
977
978        $this->_conn->exec($this->_platform->createSavePoint($savepoint));
979    }
980
981    /**
982     * releaseSavePoint
983     * releases given savepoint
984     *
985     * @param string $savepoint     name of a savepoint to release
986     * @return void
987     */
988    public function releaseSavepoint($savepoint)
989    {
990        if (!$this->_platform->supportsSavepoints()) {
991            throw ConnectionException::savepointsNotSupported();
992        }
993
994        if ($this->_platform->supportsReleaseSavepoints()) {
995            $this->_conn->exec($this->_platform->releaseSavePoint($savepoint));
996        }
997    }
998
999    /**
1000     * rollbackSavePoint
1001     * releases given savepoint
1002     *
1003     * @param string $savepoint     name of a savepoint to rollback to
1004     * @return void
1005     */
1006    public function rollbackSavepoint($savepoint)
1007    {
1008        if (!$this->_platform->supportsSavepoints()) {
1009            throw ConnectionException::savepointsNotSupported();
1010        }
1011
1012        $this->_conn->exec($this->_platform->rollbackSavePoint($savepoint));
1013    }
1014
1015    /**
1016     * Gets the wrapped driver connection.
1017     *
1018     * @return Doctrine\DBAL\Driver\Connection
1019     */
1020    public function getWrappedConnection()
1021    {
1022        $this->connect();
1023
1024        return $this->_conn;
1025    }
1026
1027    /**
1028     * Gets the SchemaManager that can be used to inspect or change the
1029     * database schema through the connection.
1030     *
1031     * @return Doctrine\DBAL\Schema\AbstractSchemaManager
1032     */
1033    public function getSchemaManager()
1034    {
1035        if ( ! $this->_schemaManager) {
1036            $this->_schemaManager = $this->_driver->getSchemaManager($this);
1037        }
1038
1039        return $this->_schemaManager;
1040    }
1041
1042    /**
1043     * Marks the current transaction so that the only possible
1044     * outcome for the transaction to be rolled back.
1045     *
1046     * @throws ConnectionException If no transaction is active.
1047     */
1048    public function setRollbackOnly()
1049    {
1050        if ($this->_transactionNestingLevel == 0) {
1051            throw ConnectionException::noActiveTransaction();
1052        }
1053        $this->_isRollbackOnly = true;
1054    }
1055
1056    /**
1057     * Check whether the current transaction is marked for rollback only.
1058     *
1059     * @return boolean
1060     * @throws ConnectionException If no transaction is active.
1061     */
1062    public function isRollbackOnly()
1063    {
1064        if ($this->_transactionNestingLevel == 0) {
1065            throw ConnectionException::noActiveTransaction();
1066        }
1067        return $this->_isRollbackOnly;
1068    }
1069
1070    /**
1071     * Converts a given value to its database representation according to the conversion
1072     * rules of a specific DBAL mapping type.
1073     *
1074     * @param mixed $value The value to convert.
1075     * @param string $type The name of the DBAL mapping type.
1076     * @return mixed The converted value.
1077     */
1078    public function convertToDatabaseValue($value, $type)
1079    {
1080        return Type::getType($type)->convertToDatabaseValue($value, $this->_platform);
1081    }
1082
1083    /**
1084     * Converts a given value to its PHP representation according to the conversion
1085     * rules of a specific DBAL mapping type.
1086     *
1087     * @param mixed $value The value to convert.
1088     * @param string $type The name of the DBAL mapping type.
1089     * @return mixed The converted type.
1090     */
1091    public function convertToPHPValue($value, $type)
1092    {
1093        return Type::getType($type)->convertToPHPValue($value, $this->_platform);
1094    }
1095
1096    /**
1097     * Binds a set of parameters, some or all of which are typed with a PDO binding type
1098     * or DBAL mapping type, to a given statement.
1099     *
1100     * @param $stmt The statement to bind the values to.
1101     * @param array $params The map/list of named/positional parameters.
1102     * @param array $types The parameter types (PDO binding types or DBAL mapping types).
1103     * @internal Duck-typing used on the $stmt parameter to support driver statements as well as
1104     *           raw PDOStatement instances.
1105     */
1106    private function _bindTypedValues($stmt, array $params, array $types)
1107    {
1108        // Check whether parameters are positional or named. Mixing is not allowed, just like in PDO.
1109        if (is_int(key($params))) {
1110            // Positional parameters
1111            $typeOffset = array_key_exists(0, $types) ? -1 : 0;
1112            $bindIndex = 1;
1113            foreach ($params as $position => $value) {
1114                $typeIndex = $bindIndex + $typeOffset;
1115                if (isset($types[$typeIndex])) {
1116                    $type = $types[$typeIndex];
1117                    list($value, $bindingType) = $this->getBindingInfo($value, $type);
1118                    $stmt->bindValue($bindIndex, $value, $bindingType);
1119                } else {
1120                    $stmt->bindValue($bindIndex, $value);
1121                }
1122                ++$bindIndex;
1123            }
1124        } else {
1125            // Named parameters
1126            foreach ($params as $name => $value) {
1127                if (isset($types[$name])) {
1128                    $type = $types[$name];
1129                    list($value, $bindingType) = $this->getBindingInfo($value, $type);
1130                    $stmt->bindValue($name, $value, $bindingType);
1131                } else {
1132                    $stmt->bindValue($name, $value);
1133                }
1134            }
1135        }
1136    }
1137
1138    /**
1139     * Gets the binding type of a given type. The given type can be a PDO or DBAL mapping type.
1140     *
1141     * @param mixed $value The value to bind
1142     * @param mixed $type The type to bind (PDO or DBAL)
1143     * @return array [0] => the (escaped) value, [1] => the binding type
1144     */
1145    private function getBindingInfo($value, $type)
1146    {
1147        if (is_string($type)) {
1148            $type = Type::getType($type);
1149        }
1150        if ($type instanceof Type) {
1151            $value = $type->convertToDatabaseValue($value, $this->_platform);
1152            $bindingType = $type->getBindingType();
1153        } else {
1154            $bindingType = $type; // PDO::PARAM_* constants
1155        }
1156        return array($value, $bindingType);
1157    }
1158
1159    /**
1160     * Create a new instance of a SQL query builder.
1161     *
1162     * @return Query\QueryBuilder
1163     */
1164    public function createQueryBuilder()
1165    {
1166        return new Query\QueryBuilder($this);
1167    }
1168}
Note: See TracBrowser for help on using the repository browser.