Completed
Pull Request — master (#29676)
by Tom
09:20
created

Connection::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 4
dl 0
loc 15
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Bart Visscher <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Morris Jobke <[email protected]>
6
 * @author Philipp Schaffrath <[email protected]>
7
 * @author Robin Appelman <[email protected]>
8
 * @author Robin McCorkell <[email protected]>
9
 * @author Roeland Jago Douma <[email protected]>
10
 * @author Thomas Müller <[email protected]>
11
 *
12
 * @copyright Copyright (c) 2017, ownCloud GmbH
13
 * @license AGPL-3.0
14
 *
15
 * This code is free software: you can redistribute it and/or modify
16
 * it under the terms of the GNU Affero General Public License, version 3,
17
 * as published by the Free Software Foundation.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22
 * GNU Affero General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Affero General Public License, version 3,
25
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
26
 *
27
 */
28
29
namespace OC\DB;
30
31
use Doctrine\DBAL\DBALException;
32
use Doctrine\DBAL\Driver;
33
use Doctrine\DBAL\Configuration;
34
use Doctrine\DBAL\Cache\QueryCacheProfile;
35
use Doctrine\Common\EventManager;
36
use Doctrine\DBAL\Driver\ServerInfoAwareConnection;
37
use Doctrine\DBAL\Exception\ConstraintViolationException;
38
use Doctrine\DBAL\Platforms\MySqlPlatform;
39
use Doctrine\DBAL\Schema\Schema;
40
use OC\DB\QueryBuilder\QueryBuilder;
41
use OCP\DB\QueryBuilder\IQueryBuilder;
42
use OCP\IDBConnection;
43
use OCP\PreConditionNotMetException;
44
use OCP\Util;
45
46
class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
47
	/**
48
	 * @var string $tablePrefix
49
	 */
50
	protected $tablePrefix;
51
52
	/**
53
	 * @var \OC\DB\Adapter $adapter
54
	 */
55
	protected $adapter;
56
57
	protected $lockedTable = null;
58
59
	public function connect() {
60
		try {
61
			return parent::connect();
62
		} catch (DBALException $e) {
63
			// throw a new exception to prevent leaking info from the stacktrace
64
			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
65
		}
66
	}
67
68
	/**
69
	 * Returns a QueryBuilder for the connection.
70
	 *
71
	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
72
	 */
73
	public function getQueryBuilder() {
74
		return new QueryBuilder($this);
75
	}
76
77
	/**
78
	 * Gets the QueryBuilder for the connection.
79
	 *
80
	 * @return \Doctrine\DBAL\Query\QueryBuilder
81
	 * @deprecated please use $this->getQueryBuilder() instead
82
	 */
83
	public function createQueryBuilder() {
84
		$backtrace = $this->getCallerBacktrace();
85
		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
86
		return parent::createQueryBuilder();
87
	}
88
89
	/**
90
	 * Gets the ExpressionBuilder for the connection.
91
	 *
92
	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
93
	 * @deprecated please use $this->getQueryBuilder()->expr() instead
94
	 */
95
	public function getExpressionBuilder() {
96
		$backtrace = $this->getCallerBacktrace();
97
		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
98
		return parent::getExpressionBuilder();
99
	}
100
101
	/**
102
	 * Get the file and line that called the method where `getCallerBacktrace()` was used
103
	 *
104
	 * @return string
105
	 */
106
	protected function getCallerBacktrace() {
107
		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
108
109
		// 0 is the method where we use `getCallerBacktrace`
110
		// 1 is the target method which uses the method we want to log
111
		if (isset($traces[1])) {
112
			return $traces[1]['file'] . ':' . $traces[1]['line'];
113
		}
114
115
		return '';
116
	}
117
118
	/**
119
	 * @return string
120
	 */
121
	public function getPrefix() {
122
		return $this->tablePrefix;
123
	}
124
125
	/**
126
	 * Initializes a new instance of the Connection class.
127
	 *
128
	 * @param array $params  The connection parameters.
129
	 * @param \Doctrine\DBAL\Driver $driver
130
	 * @param \Doctrine\DBAL\Configuration $config
131
	 * @param \Doctrine\Common\EventManager $eventManager
132
	 * @throws \Exception
133
	 */
134
	public function __construct(array $params, Driver $driver, Configuration $config = null,
135
		EventManager $eventManager = null)
136
	{
137
		if (!isset($params['adapter'])) {
138
			throw new \Exception('adapter not set');
139
		}
140
		if (!isset($params['tablePrefix'])) {
141
			throw new \Exception('tablePrefix not set');
142
		}
143
		parent::__construct($params, $driver, $config, $eventManager);
144
		$this->adapter = new $params['adapter']($this);
145
		$this->tablePrefix = $params['tablePrefix'];
146
147
		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (setTransactionIsolation() instead of __construct()). Are you sure this is correct? If so, you might want to change this to $this->setTransactionIsolation().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
148
	}
149
150
	/**
151
	 * Prepares an SQL statement.
152
	 *
153
	 * @param string $statement The SQL statement to prepare.
154
	 * @param int $limit
155
	 * @param int $offset
156
	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
157
	 */
158
	public function prepare( $statement, $limit=null, $offset=null ) {
159
		if ($limit === -1) {
160
			$limit = null;
161
		}
162
		if (!is_null($limit)) {
163
			$platform = $this->getDatabasePlatform();
164
			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
165
		}
166
		$statement = $this->replaceTablePrefix($statement);
167
		$statement = $this->adapter->fixupStatement($statement);
168
169
		return parent::prepare($statement);
170
	}
171
172
	/**
173
	 * Executes an, optionally parametrized, SQL query.
174
	 *
175
	 * If the query is parametrized, a prepared statement is used.
176
	 * If an SQLLogger is configured, the execution is logged.
177
	 *
178
	 * @param string                                      $query  The SQL query to execute.
179
	 * @param array                                       $params The parameters to bind to the query, if any.
180
	 * @param array                                       $types  The types the previous parameters are in.
181
	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
182
	 *
183
	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
184
	 *
185
	 * @throws \Doctrine\DBAL\DBALException
186
	 */
187
	public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null)
188
	{
189
		$query = $this->replaceTablePrefix($query);
190
		$query = $this->adapter->fixupStatement($query);
191
		return parent::executeQuery($query, $params, $types, $qcp);
192
	}
193
194
	/**
195
	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
196
	 * and returns the number of affected rows.
197
	 *
198
	 * This method supports PDO binding types as well as DBAL mapping types.
199
	 *
200
	 * @param string $query  The SQL query.
201
	 * @param array  $params The query parameters.
202
	 * @param array  $types  The parameter types.
203
	 *
204
	 * @return integer The number of affected rows.
205
	 *
206
	 * @throws \Doctrine\DBAL\DBALException
207
	 */
208
	public function executeUpdate($query, array $params = [], array $types = [])
209
	{
210
		$query = $this->replaceTablePrefix($query);
211
		$query = $this->adapter->fixupStatement($query);
212
		return parent::executeUpdate($query, $params, $types);
213
	}
214
215
	/**
216
	 * Returns the ID of the last inserted row, or the last value from a sequence object,
217
	 * depending on the underlying driver.
218
	 *
219
	 * Note: This method may not return a meaningful or consistent result across different drivers,
220
	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
221
	 * columns or sequences.
222
	 *
223
	 * @param string $seqName Name of the sequence object from which the ID should be returned.
224
	 * @return string A string representation of the last inserted ID.
225
	 */
226
	public function lastInsertId($seqName = null) {
227
		if ($seqName) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $seqName of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
228
			$seqName = $this->replaceTablePrefix($seqName);
229
		}
230
		return $this->adapter->lastInsertId($seqName);
231
	}
232
233
	// internal use
234
	public function realLastInsertId($seqName = null) {
235
		return parent::lastInsertId($seqName);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (lastInsertId() instead of realLastInsertId()). Are you sure this is correct? If so, you might want to change this to $this->lastInsertId().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
236
	}
237
238
	/**
239
	 * Insert a row if the matching row does not exists.
240
	 *
241
	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
242
	 * @param array $input data that should be inserted into the table  (column name => value)
243
	 * @param array|null $compare List of values that should be checked for "if not exists"
244
	 *				If this is null or an empty array, all keys of $input will be compared
245
	 *				Please note: text fields (clob) must not be used in the compare array
246
	 * @return int number of inserted rows
247
	 * @throws \Doctrine\DBAL\DBALException
248
	 */
249
	public function insertIfNotExist($table, $input, array $compare = null) {
250
		return $this->adapter->insertIfNotExist($table, $input, $compare);
251
	}
252
253
	/**
254
	 * Attempt to update a row, else insert a new one
255
	 *
256
	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
257
	 * @param array $input data that should be inserted into the table  (column name => value)
258
	 * @param array|null $compare List of values that should be checked for "if not exists"
259
	 *				If this is null or an empty array, all keys of $input will be compared
260
	 *				Please note: text fields (clob) must not be used in the compare array
261
	 * @return int number of affected rows
262
	 * @throws \Doctrine\DBAL\DBALException
263
	 */
264
	public function upsert($table, $input, array $compare = null) {
265
		return $this->adapter->upsert($table, $input, $compare);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->adapter->upsert($table, $input, $compare); of type Doctrine\DBAL\Driver\Statement|integer adds the type Doctrine\DBAL\Driver\Statement to the return on line 265 which is incompatible with the return type declared by the interface OCP\IDBConnection::upsert of type integer.
Loading history...
266
	}
267
268
	private function getType($value) {
269
		if (is_bool($value)) {
270
			return IQueryBuilder::PARAM_BOOL;
271
		} else if (is_int($value)) {
272
			return IQueryBuilder::PARAM_INT;
273
		} else {
274
			return IQueryBuilder::PARAM_STR;
275
		}
276
	}
277
278
	/**
279
	 * Insert or update a row value.
280
	 *
281
	 * @param string $table
282
	 * @param array $keys (column name => value)
283
	 * @param array $values (column name => value)
284
	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
285
	 * @return int number of new rows
286
	 * @throws \Doctrine\DBAL\DBALException
287
	 * @throws PreConditionNotMetException
288
	 */
289
	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
290
		// Try to insert whole record into the table ($toInsert) if predicate NOT EXISTS ($compare) is satisfied
291
		$toInsert = array_merge($keys, $values);
292
		$compare = array_keys($keys);
293
		$tableName = $this->tablePrefix . $table;
294
		$affected = $this->adapter->insertIfNotExist($tableName, $toInsert, $compare);
295
296
		if ($affected === 0) {
297
			// value already exists, try update
298
			$updateQb = $this->getQueryBuilder();
299
			$updateQb->update($table);
300
			foreach ($values as $name => $value) {
301
				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
302
			}
303
			$where = $updateQb->expr()->andX();
304
			$whereValues = array_merge($keys, $updatePreconditionValues);
305
			foreach ($whereValues as $name => $value) {
306
				$where->add($updateQb->expr()->eq(
307
					$name,
308
					$updateQb->createNamedParameter($value, $this->getType($value)),
309
					$this->getType($value)
310
				));
311
			}
312
			$updateQb->where($where);
313
			$affected = $updateQb->execute();
0 ignored issues
show
Bug Compatibility introduced by
The expression $updateQb->execute(); of type Doctrine\DBAL\Driver\Statement|integer adds the type Doctrine\DBAL\Driver\Statement to the return on line 321 which is incompatible with the return type declared by the interface OCP\IDBConnection::setValues of type integer.
Loading history...
314
315
			if ($affected === 0 && !empty($updatePreconditionValues)) {
316
				throw new PreConditionNotMetException();
317
			}
318
319
		}
320
321
		return $affected;
322
	}
323
324
	/**
325
	 * Create an exclusive read+write lock on a table
326
	 *
327
	 * @param string $tableName
328
	 * @throws \BadMethodCallException When trying to acquire a second lock
329
	 * @since 9.1.0
330
	 */
331
	public function lockTable($tableName) {
332
		if ($this->lockedTable !== null) {
333
			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
334
		}
335
336
		$tableName = $this->tablePrefix . $tableName;
337
		$this->lockedTable = $tableName;
338
		$this->adapter->lockTable($tableName);
339
	}
340
341
	/**
342
	 * Release a previous acquired lock again
343
	 *
344
	 * @since 9.1.0
345
	 */
346
	public function unlockTable() {
347
		$this->adapter->unlockTable();
348
		$this->lockedTable = null;
349
	}
350
351
	/**
352
	 * returns the error code and message as a string for logging
353
	 * works with DoctrineException
354
	 * @return string
355
	 */
356
	public function getError() {
357
		$msg = $this->errorCode() . ': ';
358
		$errorInfo = $this->errorInfo();
359
		if (is_array($errorInfo)) {
360
			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
361
			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
362
			$msg .= 'Driver Message = '.$errorInfo[2];
363
		}
364
		return $msg;
365
	}
366
367
	/**
368
	 * Drop a table from the database if it exists
369
	 *
370
	 * @param string $table table name without the prefix
371
	 */
372 View Code Duplication
	public function dropTable($table) {
373
		$table = $this->tablePrefix . trim($table);
374
		$schema = $this->getSchemaManager();
375
		if($schema->tablesExist([$table])) {
376
			$schema->dropTable($table);
377
		}
378
	}
379
380
	/**
381
	 * Check if a table exists
382
	 *
383
	 * @param string $table table name without the prefix
384
	 * @return bool
385
	 */
386
	public function tableExists($table){
387
		$table = $this->tablePrefix . trim($table);
388
		$schema = $this->getSchemaManager();
389
		return $schema->tablesExist([$table]);
390
	}
391
392
	// internal use
393
	/**
394
	 * @param string $statement
395
	 * @return string
396
	 */
397
	protected function replaceTablePrefix($statement) {
398
		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
399
	}
400
401
	/**
402
	 * Check if a transaction is active
403
	 *
404
	 * @return bool
405
	 * @since 8.2.0
406
	 */
407
	public function inTransaction() {
408
		return $this->getTransactionNestingLevel() > 0;
409
	}
410
411
	/**
412
	 * Espace a parameter to be used in a LIKE query
413
	 *
414
	 * @param string $param
415
	 * @return string
416
	 */
417
	public function escapeLikeParameter($param) {
418
		return addcslashes($param, '\\_%');
419
	}
420
421
	/**
422
	 * Create the schema of the connected database
423
	 *
424
	 * @return Schema
425
	 */
426
	public function createSchema() {
427
		$schemaManager = new MDB2SchemaManager($this);
428
		$migrator = $schemaManager->getMigrator();
429
		return $migrator->createSchema();
430
	}
431
432
	/**
433
	 * Migrate the database to the given schema
434
	 *
435
	 * @param Schema $toSchema
436
	 */
437
	public function migrateToSchema(Schema $toSchema) {
438
		$schemaManager = new MDB2SchemaManager($this);
439
		$migrator = $schemaManager->getMigrator();
440
		$migrator->migrate($toSchema);
441
	}
442
443
	/**
444
	 * Are 4-byte characters allowed or only 3-byte
445
	 *
446
	 * @return bool
447
	 * @since 10.0
448
	 */
449
	public function allows4ByteCharacters() {
450
		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
451
			return true;
452
		}
453
		if ($this->getParams()['charset'] === 'utf8mb4') {
454
			return true;
455
		}
456
		return false;
457
	}
458
459
	/**
460
	 * Returns the version of the related platform if applicable.
461
	 *
462
	 * Returns null if either the driver is not capable to create version
463
	 * specific platform instances, no explicit server version was specified
464
	 * or the underlying driver connection cannot determine the platform
465
	 * version without having to query it (performance reasons).
466
	 *
467
	 * @return null|string
468
	 */
469
	public function getDatabaseVersionString()
470
	{
471
		// Automatic platform version detection.
472
		if ($this->_conn instanceof ServerInfoAwareConnection &&
473
			! $this->_conn->requiresQueryForServerVersion()
474
		) {
475
			return $this->_conn->getServerVersion();
476
		}
477
478
		// Unable to detect platform version.
479
		return null;
480
	}
481
}
482