Passed
Push — master ( aeb32e...81302f )
by Christoph
15:20 queued 10s
created

Connection::errorInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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