Passed
Push — master ( eba83d...f4707d )
by Roeland
11:39 queued 14s
created

Connection::getStats()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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