Rajout de doctrine/orm
[zf2.biz/galerie.git] / vendor / doctrine / dbal / lib / Doctrine / DBAL / Connections / MasterSlaveConnection.php
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 MIT license. For more information, see
17  * <http://www.doctrine-project.org>.
18  */
19
20 namespace Doctrine\DBAL\Connections;
21
22
23 use Doctrine\DBAL\Connection,
24     Doctrine\DBAL\Driver,
25     Doctrine\DBAL\Configuration,
26     Doctrine\Common\EventManager,
27     Doctrine\DBAL\Event\ConnectionEventArgs,
28     Doctrine\DBAL\Events;
29
30 /**
31  * Master-Slave Connection
32  *
33  * Connection can be used with master-slave setups.
34  *
35  * Important for the understanding of this connection should be how and when
36  * it picks the slave or master.
37  *
38  * 1. Slave if master was never picked before and ONLY if 'getWrappedConnection'
39  *    or 'executeQuery' is used.
40  * 2. Master picked when 'exec', 'executeUpdate', 'insert', 'delete', 'update', 'createSavepoint',
41  *    'releaseSavepoint', 'beginTransaction', 'rollback', 'commit', 'query' or
42  *    'prepare' is called.
43  * 3. If master was picked once during the lifetime of the connection it will always get picked afterwards.
44  * 4. One slave connection is randomly picked ONCE during a request.
45  *
46  * ATTENTION: You can write to the slave with this connection if you execute a write query without
47  * opening up a transaction. For example:
48  *
49  *      $conn = DriverManager::getConnection(...);
50  *      $conn->executeQuery("DELETE FROM table");
51  *
52  * Be aware that Connection#executeQuery is a method specifically for READ
53  * operations only.
54  *
55  * This connection is limited to slave operations using the
56  * Connection#executeQuery operation only, because it wouldn't be compatible
57  * with the ORM or SchemaManager code otherwise. Both use all the other
58  * operations in a context where writes could happen to a slave, which makes
59  * this restricted approach necessary.
60  *
61  * You can manually connect to the master at any time by calling:
62  *
63  *      $conn->connect('master');
64  *
65  * Instantiation through the DriverManager looks like:
66  *
67  * @example
68  *
69  * $conn = DriverManager::getConnection(array(
70  *    'wrapperClass' => 'Doctrine\DBAL\Connections\MasterSlaveConnection',
71  *    'driver' => 'pdo_mysql',
72  *    'master' => array('user' => '', 'password' => '', 'host' => '', 'dbname' => ''),
73  *    'slaves' => array(
74  *        array('user' => 'slave1', 'password', 'host' => '', 'dbname' => ''),
75  *        array('user' => 'slave2', 'password', 'host' => '', 'dbname' => ''),
76  *    )
77  * ));
78  *
79  * You can also pass 'driverOptions' and any other documented option to each of this drivers to pass additional information.
80  *
81  * @author Lars Strojny <lstrojny@php.net>
82  * @author Benjamin Eberlei <kontakt@beberlei.de>
83  */
84 class MasterSlaveConnection extends Connection
85 {
86     /**
87      * Master and slave connection (one of the randomly picked slaves)
88      *
89      * @var Doctrine\DBAL\Driver\Connection[]
90      */
91     protected $connections = array('master' => null, 'slave' => null);
92
93     /**
94      * You can keep the slave connection and then switch back to it
95      * during the request if you know what you are doing.
96      *
97      * @var bool
98      */
99     protected $keepSlave = false;
100
101     /**
102      * Create Master Slave Connection
103      *
104      * @param array $params
105      * @param Driver $driver
106      * @param Configuration $config
107      * @param EventManager $eventManager
108      */
109     public function __construct(array $params, Driver $driver, Configuration $config = null, EventManager $eventManager = null)
110     {
111         if ( !isset($params['slaves']) || !isset($params['master']) ) {
112             throw new \InvalidArgumentException('master or slaves configuration missing');
113         }
114         if ( count($params['slaves']) == 0 ) {
115             throw new \InvalidArgumentException('You have to configure at least one slaves.');
116         }
117
118         $params['master']['driver'] = $params['driver'];
119         foreach ($params['slaves'] as $slaveKey => $slave) {
120             $params['slaves'][$slaveKey]['driver'] = $params['driver'];
121         }
122
123         $this->keepSlave = isset($params['keepSlave']) ? (bool)$params['keepSlave'] : false;
124
125         parent::__construct($params, $driver, $config, $eventManager);
126     }
127
128     /**
129      * Check if the connection is currently towards the master or not.
130      *
131      * @return bool
132      */
133     public function isConnectedToMaster()
134     {
135         return $this->_conn !== null && $this->_conn === $this->connections['master'];
136     }
137
138     /**
139      * {@inheritDoc}
140      */
141     public function connect($connectionName = null)
142     {
143         $requestedConnectionChange = ($connectionName !== null);
144         $connectionName            = $connectionName ?: 'slave';
145
146         if ( $connectionName !== 'slave' && $connectionName !== 'master' ) {
147             throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed.");
148         }
149
150         // If we have a connection open, and this is not an explicit connection
151         // change request, then abort right here, because we are already done.
152         // This prevents writes to the slave in case of "keepSlave" option enabled.
153         if ($this->_conn && !$requestedConnectionChange) {
154             return false;
155         }
156
157         $forceMasterAsSlave = false;
158
159         if ($this->getTransactionNestingLevel() > 0) {
160             $connectionName     = 'master';
161             $forceMasterAsSlave = true;
162         }
163
164         if ($this->connections[$connectionName]) {
165             if ($forceMasterAsSlave) {
166                 $this->connections['slave'] = $this->_conn = $this->connections['master'];
167             } else {
168                 $this->_conn = $this->connections[$connectionName];
169             }
170             return false;
171         }
172
173         if ($connectionName === 'master') {
174             // Set slave connection to master to avoid invalid reads
175             if ($this->connections['slave'] && ! $this->keepSlave) {
176                 unset($this->connections['slave']);
177             }
178
179             $this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
180
181             if ( ! $this->keepSlave) {
182                 $this->connections['slave'] = $this->connections['master'];
183             }
184         } else {
185             $this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
186         }
187
188         if ($this->_eventManager->hasListeners(Events::postConnect)) {
189             $eventArgs = new ConnectionEventArgs($this);
190             $this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
191         }
192
193         return true;
194     }
195
196     /**
197      * Connect to a specific connection
198      *
199      * @param  string $connectionName
200      * @return Driver
201      */
202     protected function connectTo($connectionName)
203     {
204         $params = $this->getParams();
205
206         $driverOptions = isset($params['driverOptions']) ? $params['driverOptions'] : array();
207
208         $connectionParams = $this->chooseConnectionConfiguration($connectionName, $params);
209
210         $user = isset($connectionParams['user']) ? $connectionParams['user'] : null;
211         $password = isset($connectionParams['password']) ? $connectionParams['password'] : null;
212
213         return $this->_driver->connect($connectionParams, $user, $password, $driverOptions);
214     }
215
216     protected function chooseConnectionConfiguration($connectionName, $params)
217     {
218         if ($connectionName === 'master') {
219             return $params['master'];
220         }
221
222         return $params['slaves'][array_rand($params['slaves'])];
223     }
224
225     /**
226      * {@inheritDoc}
227      */
228     public function executeUpdate($query, array $params = array(), array $types = array())
229     {
230         $this->connect('master');
231         return parent::executeUpdate($query, $params, $types);
232     }
233
234     /**
235      * {@inheritDoc}
236      */
237     public function beginTransaction()
238     {
239         $this->connect('master');
240         return parent::beginTransaction();
241     }
242
243     /**
244      * {@inheritDoc}
245      */
246     public function commit()
247     {
248         $this->connect('master');
249         return parent::commit();
250     }
251
252     /**
253      * {@inheritDoc}
254      */
255     public function rollBack()
256     {
257         $this->connect('master');
258         return parent::rollBack();
259     }
260
261     /**
262      * {@inheritDoc}
263      */
264     public function delete($tableName, array $identifier)
265     {
266         $this->connect('master');
267         return parent::delete($tableName, $identifier);
268     }
269
270     /**
271      * {@inheritDoc}
272      */
273     public function update($tableName, array $data, array $identifier, array $types = array())
274     {
275         $this->connect('master');
276         return parent::update($tableName, $data, $identifier, $types);
277     }
278
279     /**
280      * {@inheritDoc}
281      */
282     public function insert($tableName, array $data, array $types = array())
283     {
284         $this->connect('master');
285         return parent::insert($tableName, $data, $types);
286     }
287
288     /**
289      * {@inheritDoc}
290      */
291     public function exec($statement)
292     {
293         $this->connect('master');
294         return parent::exec($statement);
295     }
296
297     /**
298      * {@inheritDoc}
299      */
300     public function createSavepoint($savepoint)
301     {
302         $this->connect('master');
303
304         return parent::createSavepoint($savepoint);
305     }
306
307     /**
308      * {@inheritDoc}
309      */
310     public function releaseSavepoint($savepoint)
311     {
312         $this->connect('master');
313
314         return parent::releaseSavepoint($savepoint);
315     }
316
317     /**
318      * {@inheritDoc}
319      */
320     public function rollbackSavepoint($savepoint)
321     {
322         $this->connect('master');
323
324         return parent::rollbackSavepoint($savepoint);
325     }
326
327     public function query()
328     {
329         $this->connect('master');
330
331         $args = func_get_args();
332
333         $logger = $this->getConfiguration()->getSQLLogger();
334         if ($logger) {
335             $logger->startQuery($args[0]);
336         }
337
338         $statement = call_user_func_array(array($this->_conn, 'query'), $args);
339
340         if ($logger) {
341             $logger->stopQuery();
342         }
343
344         return $statement;
345     }
346
347     public function prepare($statement)
348     {
349         $this->connect('master');
350
351         return parent::prepare($statement);
352     }
353 }