Completed
Push — master ( 599977...a7d112 )
by Thomas
10:10
created

Connection::allows4ByteCharacters()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 0
dl 0
loc 9
rs 9.6666
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 Robin Appelman <[email protected]>
7
 * @author Robin McCorkell <[email protected]>
8
 * @author Roeland Jago Douma <[email protected]>
9
 * @author Thomas Müller <[email protected]>
10
 *
11
 * @copyright Copyright (c) 2016, ownCloud GmbH.
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
25
 *
26
 */
27
28
namespace OC\DB;
29
30
use Doctrine\DBAL\DBALException;
31
use Doctrine\DBAL\Driver;
32
use Doctrine\DBAL\Configuration;
33
use Doctrine\DBAL\Cache\QueryCacheProfile;
34
use Doctrine\Common\EventManager;
35
use Doctrine\DBAL\Exception\ConstraintViolationException;
36
use Doctrine\DBAL\Platforms\MySqlPlatform;
37
use Doctrine\DBAL\Schema\Schema;
38
use OC\DB\QueryBuilder\QueryBuilder;
39
use OCP\DB\QueryBuilder\IQueryBuilder;
40
use OCP\IDBConnection;
41
use OCP\PreConditionNotMetException;
42
use OCP\Util;
43
44
class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
45
	/**
46
	 * @var string $tablePrefix
47
	 */
48
	protected $tablePrefix;
49
50
	/**
51
	 * @var \OC\DB\Adapter $adapter
52
	 */
53
	protected $adapter;
54
55
	protected $lockedTable = null;
56
57
	public function connect() {
58
		try {
59
			return parent::connect();
60
		} catch (DBALException $e) {
61
			// throw a new exception to prevent leaking info from the stacktrace
62
			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
63
		}
64
	}
65
66
	/**
67
	 * Returns a QueryBuilder for the connection.
68
	 *
69
	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
70
	 */
71
	public function getQueryBuilder() {
72
		return new QueryBuilder($this);
73
	}
74
75
	/**
76
	 * Gets the QueryBuilder for the connection.
77
	 *
78
	 * @return \Doctrine\DBAL\Query\QueryBuilder
79
	 * @deprecated please use $this->getQueryBuilder() instead
80
	 */
81
	public function createQueryBuilder() {
82
		$backtrace = $this->getCallerBacktrace();
83
		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
84
		return parent::createQueryBuilder();
85
	}
86
87
	/**
88
	 * Gets the ExpressionBuilder for the connection.
89
	 *
90
	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
91
	 * @deprecated please use $this->getQueryBuilder()->expr() instead
92
	 */
93
	public function getExpressionBuilder() {
94
		$backtrace = $this->getCallerBacktrace();
95
		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
96
		return parent::getExpressionBuilder();
97
	}
98
99
	/**
100
	 * Get the file and line that called the method where `getCallerBacktrace()` was used
101
	 *
102
	 * @return string
103
	 */
104
	protected function getCallerBacktrace() {
105
		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
106
107
		// 0 is the method where we use `getCallerBacktrace`
108
		// 1 is the target method which uses the method we want to log
109
		if (isset($traces[1])) {
110
			return $traces[1]['file'] . ':' . $traces[1]['line'];
111
		}
112
113
		return '';
114
	}
115
116
	/**
117
	 * @return string
118
	 */
119
	public function getPrefix() {
120
		return $this->tablePrefix;
121
	}
122
123
	/**
124
	 * Initializes a new instance of the Connection class.
125
	 *
126
	 * @param array $params  The connection parameters.
127
	 * @param \Doctrine\DBAL\Driver $driver
128
	 * @param \Doctrine\DBAL\Configuration $config
129
	 * @param \Doctrine\Common\EventManager $eventManager
130
	 * @throws \Exception
131
	 */
132
	public function __construct(array $params, Driver $driver, Configuration $config = null,
133
		EventManager $eventManager = null)
134
	{
135
		if (!isset($params['adapter'])) {
136
			throw new \Exception('adapter not set');
137
		}
138
		if (!isset($params['tablePrefix'])) {
139
			throw new \Exception('tablePrefix not set');
140
		}
141
		parent::__construct($params, $driver, $config, $eventManager);
142
		$this->adapter = new $params['adapter']($this);
143
		$this->tablePrefix = $params['tablePrefix'];
144
145
		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...
146
	}
147
148
	/**
149
	 * Prepares an SQL statement.
150
	 *
151
	 * @param string $statement The SQL statement to prepare.
152
	 * @param int $limit
153
	 * @param int $offset
154
	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
155
	 */
156
	public function prepare( $statement, $limit=null, $offset=null ) {
157
		if ($limit === -1) {
158
			$limit = null;
159
		}
160
		if (!is_null($limit)) {
161
			$platform = $this->getDatabasePlatform();
162
			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
163
		}
164
		$statement = $this->replaceTablePrefix($statement);
165
		$statement = $this->adapter->fixupStatement($statement);
166
167
		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
168
			Util::writeLog('core', 'DB prepare : '.$statement, Util::DEBUG);
169
		}
170
		return parent::prepare($statement);
171
	}
172
173
	/**
174
	 * Executes an, optionally parametrized, SQL query.
175
	 *
176
	 * If the query is parametrized, a prepared statement is used.
177
	 * If an SQLLogger is configured, the execution is logged.
178
	 *
179
	 * @param string                                      $query  The SQL query to execute.
180
	 * @param array                                       $params The parameters to bind to the query, if any.
181
	 * @param array                                       $types  The types the previous parameters are in.
182
	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
183
	 *
184
	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
185
	 *
186
	 * @throws \Doctrine\DBAL\DBALException
187
	 */
188
	public function executeQuery($query, array $params = [], $types = [], QueryCacheProfile $qcp = null)
189
	{
190
		$query = $this->replaceTablePrefix($query);
191
		$query = $this->adapter->fixupStatement($query);
192
		return parent::executeQuery($query, $params, $types, $qcp);
193
	}
194
195
	/**
196
	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
197
	 * and returns the number of affected rows.
198
	 *
199
	 * This method supports PDO binding types as well as DBAL mapping types.
200
	 *
201
	 * @param string $query  The SQL query.
202
	 * @param array  $params The query parameters.
203
	 * @param array  $types  The parameter types.
204
	 *
205
	 * @return integer The number of affected rows.
206
	 *
207
	 * @throws \Doctrine\DBAL\DBALException
208
	 */
209
	public function executeUpdate($query, array $params = [], array $types = [])
210
	{
211
		$query = $this->replaceTablePrefix($query);
212
		$query = $this->adapter->fixupStatement($query);
213
		return parent::executeUpdate($query, $params, $types);
214
	}
215
216
	/**
217
	 * Returns the ID of the last inserted row, or the last value from a sequence object,
218
	 * depending on the underlying driver.
219
	 *
220
	 * Note: This method may not return a meaningful or consistent result across different drivers,
221
	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
222
	 * columns or sequences.
223
	 *
224
	 * @param string $seqName Name of the sequence object from which the ID should be returned.
225
	 * @return string A string representation of the last inserted ID.
226
	 */
227
	public function lastInsertId($seqName = null) {
228
		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...
229
			$seqName = $this->replaceTablePrefix($seqName);
230
		}
231
		return $this->adapter->lastInsertId($seqName);
232
	}
233
234
	// internal use
235
	public function realLastInsertId($seqName = null) {
236
		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...
237
	}
238
239
	/**
240
	 * Insert a row if the matching row does not exists.
241
	 *
242
	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
243
	 * @param array $input data that should be inserted into the table  (column name => value)
244
	 * @param array|null $compare List of values that should be checked for "if not exists"
245
	 *				If this is null or an empty array, all keys of $input will be compared
246
	 *				Please note: text fields (clob) must not be used in the compare array
247
	 * @return int number of inserted rows
248
	 * @throws \Doctrine\DBAL\DBALException
249
	 */
250
	public function insertIfNotExist($table, $input, array $compare = null) {
251
		return $this->adapter->insertIfNotExist($table, $input, $compare);
252
	}
253
254
	private function getType($value) {
255
		if (is_bool($value)) {
256
			return IQueryBuilder::PARAM_BOOL;
257
		} else if (is_int($value)) {
258
			return IQueryBuilder::PARAM_INT;
259
		} else {
260
			return IQueryBuilder::PARAM_STR;
261
		}
262
	}
263
264
	/**
265
	 * Insert or update a row value
266
	 *
267
	 * @param string $table
268
	 * @param array $keys (column name => value)
269
	 * @param array $values (column name => value)
270
	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
271
	 * @return int number of new rows
272
	 * @throws \Doctrine\DBAL\DBALException
273
	 * @throws PreConditionNotMetException
274
	 */
275
	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
276
		try {
277
			$insertQb = $this->getQueryBuilder();
278
			$insertQb->insert($table)
279
				->values(
280
					array_map(function($value) use ($insertQb) {
281
						return $insertQb->createNamedParameter($value, $this->getType($value));
282
					}, array_merge($keys, $values))
283
				);
284
			return $insertQb->execute();
0 ignored issues
show
Bug Compatibility introduced by
The expression $insertQb->execute(); of type Doctrine\DBAL\Driver\Statement|integer adds the type Doctrine\DBAL\Driver\Statement to the return on line 284 which is incompatible with the return type declared by the interface OCP\IDBConnection::setValues of type integer.
Loading history...
285
		} catch (ConstraintViolationException $e) {
286
			// value already exists, try update
287
			$updateQb = $this->getQueryBuilder();
288
			$updateQb->update($table);
289
			foreach ($values as $name => $value) {
290
				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
291
			}
292
			$where = $updateQb->expr()->andX();
293
			$whereValues = array_merge($keys, $updatePreconditionValues);
294
			foreach ($whereValues as $name => $value) {
295
				$where->add($updateQb->expr()->eq(
296
					$name,
297
					$updateQb->createNamedParameter($value, $this->getType($value)),
298
					$this->getType($value)
299
				));
300
			}
301
			$updateQb->where($where);
302
			$affected = $updateQb->execute();
303
304
			if ($affected === 0 && !empty($updatePreconditionValues)) {
305
				throw new PreConditionNotMetException();
306
			}
307
308
			return 0;
309
		}
310
	}
311
312
	/**
313
	 * Create an exclusive read+write lock on a table
314
	 *
315
	 * @param string $tableName
316
	 * @throws \BadMethodCallException When trying to acquire a second lock
317
	 * @since 9.1.0
318
	 */
319
	public function lockTable($tableName) {
320
		if ($this->lockedTable !== null) {
321
			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
322
		}
323
324
		$tableName = $this->tablePrefix . $tableName;
325
		$this->lockedTable = $tableName;
326
		$this->adapter->lockTable($tableName);
327
	}
328
329
	/**
330
	 * Release a previous acquired lock again
331
	 *
332
	 * @since 9.1.0
333
	 */
334
	public function unlockTable() {
335
		$this->adapter->unlockTable();
336
		$this->lockedTable = null;
337
	}
338
339
	/**
340
	 * returns the error code and message as a string for logging
341
	 * works with DoctrineException
342
	 * @return string
343
	 */
344
	public function getError() {
345
		$msg = $this->errorCode() . ': ';
346
		$errorInfo = $this->errorInfo();
347
		if (is_array($errorInfo)) {
348
			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
349
			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
350
			$msg .= 'Driver Message = '.$errorInfo[2];
351
		}
352
		return $msg;
353
	}
354
355
	/**
356
	 * Drop a table from the database if it exists
357
	 *
358
	 * @param string $table table name without the prefix
359
	 */
360 View Code Duplication
	public function dropTable($table) {
361
		$table = $this->tablePrefix . trim($table);
362
		$schema = $this->getSchemaManager();
363
		if($schema->tablesExist([$table])) {
364
			$schema->dropTable($table);
365
		}
366
	}
367
368
	/**
369
	 * Check if a table exists
370
	 *
371
	 * @param string $table table name without the prefix
372
	 * @return bool
373
	 */
374
	public function tableExists($table){
375
		$table = $this->tablePrefix . trim($table);
376
		$schema = $this->getSchemaManager();
377
		return $schema->tablesExist([$table]);
378
	}
379
380
	// internal use
381
	/**
382
	 * @param string $statement
383
	 * @return string
384
	 */
385
	protected function replaceTablePrefix($statement) {
386
		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
387
	}
388
389
	/**
390
	 * Check if a transaction is active
391
	 *
392
	 * @return bool
393
	 * @since 8.2.0
394
	 */
395
	public function inTransaction() {
396
		return $this->getTransactionNestingLevel() > 0;
397
	}
398
399
	/**
400
	 * Espace a parameter to be used in a LIKE query
401
	 *
402
	 * @param string $param
403
	 * @return string
404
	 */
405
	public function escapeLikeParameter($param) {
406
		return addcslashes($param, '\\_%');
407
	}
408
409
	/**
410
	 * Create the schema of the connected database
411
	 *
412
	 * @return Schema
413
	 */
414
	public function createSchema() {
415
		$schemaManager = new MDB2SchemaManager($this);
416
		$migrator = $schemaManager->getMigrator();
417
		return $migrator->createSchema();
418
	}
419
420
	/**
421
	 * Migrate the database to the given schema
422
	 *
423
	 * @param Schema $toSchema
424
	 */
425
	public function migrateToSchema(Schema $toSchema) {
426
		$schemaManager = new MDB2SchemaManager($this);
427
		$migrator = $schemaManager->getMigrator();
428
		$migrator->migrate($toSchema);
429
	}
430
431
	/**
432
	 * Are 4-byte characters allowed or only 3-byte
433
	 *
434
	 * @return bool
435
	 * @since 10.0
436
	 */
437
	public function allows4ByteCharacters() {
438
		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
439
			return true;
440
		}
441
		if ($this->getParams()['charset'] === 'utf8mb4') {
442
			return true;
443
		}
444
		return false;
445
	}
446
}
447