Passed
Push — master ( 9af8c0...c15172 )
by Roeland
15:34 queued 11s
created

Connection::setValues()   B

Complexity

Conditions 8
Paths 40

Size

Total Lines 42
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 31
nc 40
nop 4
dl 0
loc 42
rs 8.1795
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\Platforms\OraclePlatform;
48
use Doctrine\DBAL\Platforms\PostgreSQL94Platform;
49
use Doctrine\DBAL\Platforms\SqlitePlatform;
50
use Doctrine\DBAL\Result;
51
use Doctrine\DBAL\Schema\Schema;
52
use Doctrine\DBAL\Statement;
53
use OC\DB\QueryBuilder\QueryBuilder;
54
use OC\SystemConfig;
55
use OCP\DB\QueryBuilder\IQueryBuilder;
56
use OCP\ILogger;
57
use OCP\PreConditionNotMetException;
58
59
class Connection extends \Doctrine\DBAL\Connection {
60
	/** @var string */
61
	protected $tablePrefix;
62
63
	/** @var \OC\DB\Adapter $adapter */
64
	protected $adapter;
65
66
	/** @var SystemConfig */
67
	private $systemConfig;
68
69
	/** @var ILogger */
70
	private $logger;
71
72
	protected $lockedTable = null;
73
74
	/** @var int */
75
	protected $queriesBuilt = 0;
76
77
	/** @var int */
78
	protected $queriesExecuted = 0;
79
80
	/**
81
	 * @throws Exception
82
	 */
83
	public function connect() {
84
		try {
85
			return parent::connect();
86
		} catch (Exception $e) {
87
			// throw a new exception to prevent leaking info from the stacktrace
88
			throw new Exception('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
89
		}
90
	}
91
92
	public function getStats(): array {
93
		return [
94
			'built' => $this->queriesBuilt,
95
			'executed' => $this->queriesExecuted,
96
		];
97
	}
98
99
	/**
100
	 * Returns a QueryBuilder for the connection.
101
	 */
102
	public function getQueryBuilder(): IQueryBuilder {
103
		$this->queriesBuilt++;
104
		return new QueryBuilder(
105
			new ConnectionAdapter($this),
106
			$this->systemConfig,
107
			$this->logger
108
		);
109
	}
110
111
	/**
112
	 * Gets the QueryBuilder for the connection.
113
	 *
114
	 * @return \Doctrine\DBAL\Query\QueryBuilder
115
	 * @deprecated please use $this->getQueryBuilder() instead
116
	 */
117
	public function createQueryBuilder() {
118
		$backtrace = $this->getCallerBacktrace();
119
		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
120
		$this->queriesBuilt++;
121
		return parent::createQueryBuilder();
122
	}
123
124
	/**
125
	 * Gets the ExpressionBuilder for the connection.
126
	 *
127
	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
128
	 * @deprecated please use $this->getQueryBuilder()->expr() instead
129
	 */
130
	public function getExpressionBuilder() {
131
		$backtrace = $this->getCallerBacktrace();
132
		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
133
		$this->queriesBuilt++;
134
		return parent::getExpressionBuilder();
135
	}
136
137
	/**
138
	 * Get the file and line that called the method where `getCallerBacktrace()` was used
139
	 *
140
	 * @return string
141
	 */
142
	protected function getCallerBacktrace() {
143
		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
144
145
		// 0 is the method where we use `getCallerBacktrace`
146
		// 1 is the target method which uses the method we want to log
147
		if (isset($traces[1])) {
148
			return $traces[1]['file'] . ':' . $traces[1]['line'];
149
		}
150
151
		return '';
152
	}
153
154
	/**
155
	 * @return string
156
	 */
157
	public function getPrefix() {
158
		return $this->tablePrefix;
159
	}
160
161
	/**
162
	 * Initializes a new instance of the Connection class.
163
	 *
164
	 * @param array $params  The connection parameters.
165
	 * @param \Doctrine\DBAL\Driver $driver
166
	 * @param \Doctrine\DBAL\Configuration $config
167
	 * @param \Doctrine\Common\EventManager $eventManager
168
	 * @throws \Exception
169
	 */
170
	public function __construct(array $params, Driver $driver, Configuration $config = null,
171
		EventManager $eventManager = null) {
172
		if (!isset($params['adapter'])) {
173
			throw new \Exception('adapter not set');
174
		}
175
		if (!isset($params['tablePrefix'])) {
176
			throw new \Exception('tablePrefix not set');
177
		}
178
		/**
179
		 * @psalm-suppress InternalMethod
180
		 */
181
		parent::__construct($params, $driver, $config, $eventManager);
182
		$this->adapter = new $params['adapter']($this);
183
		$this->tablePrefix = $params['tablePrefix'];
184
185
		$this->systemConfig = \OC::$server->getSystemConfig();
186
		$this->logger = \OC::$server->getLogger();
187
	}
188
189
	/**
190
	 * Prepares an SQL statement.
191
	 *
192
	 * @param string $statement The SQL statement to prepare.
193
	 * @param int $limit
194
	 * @param int $offset
195
	 *
196
	 * @return Statement The prepared statement.
197
	 * @throws Exception
198
	 */
199
	public function prepare($statement, $limit = null, $offset = null): Statement {
200
		if ($limit === -1) {
201
			$limit = null;
202
		}
203
		if (!is_null($limit)) {
204
			$platform = $this->getDatabasePlatform();
205
			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
206
		}
207
		$statement = $this->replaceTablePrefix($statement);
208
		$statement = $this->adapter->fixupStatement($statement);
209
210
		return parent::prepare($statement);
211
	}
212
213
	/**
214
	 * Executes an, optionally parametrized, SQL query.
215
	 *
216
	 * If the query is parametrized, a prepared statement is used.
217
	 * If an SQLLogger is configured, the execution is logged.
218
	 *
219
	 * @param string                                      $sql  The SQL query to execute.
220
	 * @param array                                       $params The parameters to bind to the query, if any.
221
	 * @param array                                       $types  The types the previous parameters are in.
222
	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
223
	 *
224
	 * @return Result The executed statement.
225
	 *
226
	 * @throws \Doctrine\DBAL\Exception
227
	 */
228
	public function executeQuery(string $sql, array $params = [], $types = [], QueryCacheProfile $qcp = null): Result {
229
		$sql = $this->replaceTablePrefix($sql);
230
		$sql = $this->adapter->fixupStatement($sql);
231
		$this->queriesExecuted++;
232
		return parent::executeQuery($sql, $params, $types, $qcp);
233
	}
234
235
	/**
236
	 * @throws Exception
237
	 */
238
	public function executeUpdate(string $sql, array $params = [], array $types = []): int {
239
		$sql = $this->replaceTablePrefix($sql);
240
		$sql = $this->adapter->fixupStatement($sql);
241
		$this->queriesExecuted++;
242
		return parent::executeUpdate($sql, $params, $types);
243
	}
244
245
	/**
246
	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
247
	 * and returns the number of affected rows.
248
	 *
249
	 * This method supports PDO binding types as well as DBAL mapping types.
250
	 *
251
	 * @param string $sql  The SQL query.
252
	 * @param array  $params The query parameters.
253
	 * @param array  $types  The parameter types.
254
	 *
255
	 * @return int The number of affected rows.
256
	 *
257
	 * @throws \Doctrine\DBAL\Exception
258
	 */
259
	public function executeStatement($sql, array $params = [], array $types = []): int {
260
		$sql = $this->replaceTablePrefix($sql);
261
		$sql = $this->adapter->fixupStatement($sql);
262
		$this->queriesExecuted++;
263
		return parent::executeStatement($sql, $params, $types);
264
	}
265
266
	/**
267
	 * Returns the ID of the last inserted row, or the last value from a sequence object,
268
	 * depending on the underlying driver.
269
	 *
270
	 * Note: This method may not return a meaningful or consistent result across different drivers,
271
	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
272
	 * columns or sequences.
273
	 *
274
	 * @param string $seqName Name of the sequence object from which the ID should be returned.
275
	 *
276
	 * @return string the last inserted ID.
277
	 * @throws Exception
278
	 */
279
	public function lastInsertId($seqName = null) {
280
		if ($seqName) {
281
			$seqName = $this->replaceTablePrefix($seqName);
282
		}
283
		return $this->adapter->lastInsertId($seqName);
284
	}
285
286
	/**
287
	 * @internal
288
	 * @throws Exception
289
	 */
290
	public function realLastInsertId($seqName = null) {
291
		return parent::lastInsertId($seqName);
292
	}
293
294
	/**
295
	 * Insert a row if the matching row does not exists. To accomplish proper race condition avoidance
296
	 * it is needed that there is also a unique constraint on the values. Then this method will
297
	 * catch the exception and return 0.
298
	 *
299
	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
300
	 * @param array $input data that should be inserted into the table  (column name => value)
301
	 * @param array|null $compare List of values that should be checked for "if not exists"
302
	 *				If this is null or an empty array, all keys of $input will be compared
303
	 *				Please note: text fields (clob) must not be used in the compare array
304
	 * @return int number of inserted rows
305
	 * @throws \Doctrine\DBAL\Exception
306
	 * @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
307
	 */
308
	public function insertIfNotExist($table, $input, array $compare = null) {
309
		return $this->adapter->insertIfNotExist($table, $input, $compare);
310
	}
311
312
	public function insertIgnoreConflict(string $table, array $values) : int {
313
		return $this->adapter->insertIgnoreConflict($table, $values);
314
	}
315
316
	private function getType($value) {
317
		if (is_bool($value)) {
318
			return IQueryBuilder::PARAM_BOOL;
319
		} elseif (is_int($value)) {
320
			return IQueryBuilder::PARAM_INT;
321
		} else {
322
			return IQueryBuilder::PARAM_STR;
323
		}
324
	}
325
326
	/**
327
	 * Insert or update a row value
328
	 *
329
	 * @param string $table
330
	 * @param array $keys (column name => value)
331
	 * @param array $values (column name => value)
332
	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
333
	 * @return int number of new rows
334
	 * @throws \Doctrine\DBAL\Exception
335
	 * @throws PreConditionNotMetException
336
	 */
337
	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
338
		try {
339
			$insertQb = $this->getQueryBuilder();
340
			$insertQb->insert($table)
341
				->values(
342
					array_map(function ($value) use ($insertQb) {
343
						return $insertQb->createNamedParameter($value, $this->getType($value));
344
					}, array_merge($keys, $values))
345
				);
346
			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...
347
		} catch (NotNullConstraintViolationException $e) {
348
			throw $e;
349
		} catch (ConstraintViolationException $e) {
350
			// value already exists, try update
351
			$updateQb = $this->getQueryBuilder();
352
			$updateQb->update($table);
353
			foreach ($values as $name => $value) {
354
				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
355
			}
356
			$where = $updateQb->expr()->andX();
357
			$whereValues = array_merge($keys, $updatePreconditionValues);
358
			foreach ($whereValues as $name => $value) {
359
				if ($value === '') {
360
					$where->add($updateQb->expr()->emptyString(
361
						$name
362
					));
363
				} else {
364
					$where->add($updateQb->expr()->eq(
365
						$name,
366
						$updateQb->createNamedParameter($value, $this->getType($value)),
367
						$this->getType($value)
368
					));
369
				}
370
			}
371
			$updateQb->where($where);
372
			$affected = $updateQb->execute();
373
374
			if ($affected === 0 && !empty($updatePreconditionValues)) {
0 ignored issues
show
introduced by
The condition $affected === 0 is always false.
Loading history...
375
				throw new PreConditionNotMetException();
376
			}
377
378
			return 0;
379
		}
380
	}
381
382
	/**
383
	 * Create an exclusive read+write lock on a table
384
	 *
385
	 * @param string $tableName
386
	 *
387
	 * @throws \BadMethodCallException When trying to acquire a second lock
388
	 * @throws Exception
389
	 * @since 9.1.0
390
	 */
391
	public function lockTable($tableName) {
392
		if ($this->lockedTable !== null) {
393
			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
394
		}
395
396
		$tableName = $this->tablePrefix . $tableName;
397
		$this->lockedTable = $tableName;
398
		$this->adapter->lockTable($tableName);
399
	}
400
401
	/**
402
	 * Release a previous acquired lock again
403
	 *
404
	 * @throws Exception
405
	 * @since 9.1.0
406
	 */
407
	public function unlockTable() {
408
		$this->adapter->unlockTable();
409
		$this->lockedTable = null;
410
	}
411
412
	/**
413
	 * returns the error code and message as a string for logging
414
	 * works with DoctrineException
415
	 * @return string
416
	 */
417
	public function getError() {
418
		$msg = $this->errorCode() . ': ';
419
		$errorInfo = $this->errorInfo();
420
		if (!empty($errorInfo)) {
421
			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
422
			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
423
			$msg .= 'Driver Message = '.$errorInfo[2];
424
		}
425
		return $msg;
426
	}
427
428
	public function errorCode() {
429
		return -1;
430
	}
431
432
	public function errorInfo() {
433
		return [];
434
	}
435
436
	/**
437
	 * Drop a table from the database if it exists
438
	 *
439
	 * @param string $table table name without the prefix
440
	 *
441
	 * @throws Exception
442
	 */
443
	public function dropTable($table) {
444
		$table = $this->tablePrefix . trim($table);
445
		$schema = $this->getSchemaManager();
446
		if ($schema->tablesExist([$table])) {
447
			$schema->dropTable($table);
448
		}
449
	}
450
451
	/**
452
	 * Check if a table exists
453
	 *
454
	 * @param string $table table name without the prefix
455
	 *
456
	 * @return bool
457
	 * @throws Exception
458
	 */
459
	public function tableExists($table) {
460
		$table = $this->tablePrefix . trim($table);
461
		$schema = $this->getSchemaManager();
462
		return $schema->tablesExist([$table]);
463
	}
464
465
	// internal use
466
	/**
467
	 * @param string $statement
468
	 * @return string
469
	 */
470
	protected function replaceTablePrefix($statement) {
471
		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
472
	}
473
474
	/**
475
	 * Check if a transaction is active
476
	 *
477
	 * @return bool
478
	 * @since 8.2.0
479
	 */
480
	public function inTransaction() {
481
		return $this->getTransactionNestingLevel() > 0;
482
	}
483
484
	/**
485
	 * Escape a parameter to be used in a LIKE query
486
	 *
487
	 * @param string $param
488
	 * @return string
489
	 */
490
	public function escapeLikeParameter($param) {
491
		return addcslashes($param, '\\_%');
492
	}
493
494
	/**
495
	 * Check whether or not the current database support 4byte wide unicode
496
	 *
497
	 * @return bool
498
	 * @since 11.0.0
499
	 */
500
	public function supports4ByteText() {
501
		if (!$this->getDatabasePlatform() instanceof MySQLPlatform) {
502
			return true;
503
		}
504
		return $this->getParams()['charset'] === 'utf8mb4';
505
	}
506
507
508
	/**
509
	 * Create the schema of the connected database
510
	 *
511
	 * @return Schema
512
	 * @throws Exception
513
	 */
514
	public function createSchema() {
515
		$migrator = $this->getMigrator();
516
		return $migrator->createSchema();
517
	}
518
519
	/**
520
	 * Migrate the database to the given schema
521
	 *
522
	 * @param Schema $toSchema
523
	 *
524
	 * @throws Exception
525
	 */
526
	public function migrateToSchema(Schema $toSchema) {
527
		$migrator = $this->getMigrator();
528
		$migrator->migrate($toSchema);
529
	}
530
531
	private function getMigrator() {
532
		// TODO properly inject those dependencies
533
		$random = \OC::$server->getSecureRandom();
0 ignored issues
show
Unused Code introduced by
The assignment to $random is dead and can be removed.
Loading history...
534
		$platform = $this->getDatabasePlatform();
535
		$config = \OC::$server->getConfig();
536
		$dispatcher = \OC::$server->getEventDispatcher();
537
		if ($platform instanceof SqlitePlatform) {
538
			return new SQLiteMigrator($this, $config, $dispatcher);
539
		} elseif ($platform instanceof OraclePlatform) {
540
			return new OracleMigrator($this, $config, $dispatcher);
541
		} elseif ($platform instanceof MySQLPlatform) {
542
			return new MySQLMigrator($this, $config, $dispatcher);
543
		} elseif ($platform instanceof PostgreSQL94Platform) {
544
			return new PostgreSqlMigrator($this, $config, $dispatcher);
545
		} else {
546
			return new Migrator($this, $config, $dispatcher);
547
		}
548
	}
549
}
550