Completed
Pull Request — master (#27041)
by Thomas
12:53
created

Connection::migrateToSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 5
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 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\Schema\Schema;
37
use OC\DB\QueryBuilder\QueryBuilder;
38
use OCP\DB\QueryBuilder\IQueryBuilder;
39
use OCP\IDBConnection;
40
use OCP\PreConditionNotMetException;
41
use OCP\Util;
42
43
class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
44
	/**
45
	 * @var string $tablePrefix
46
	 */
47
	protected $tablePrefix;
48
49
	/**
50
	 * @var \OC\DB\Adapter $adapter
51
	 */
52
	protected $adapter;
53
54
	protected $lockedTable = null;
55
56
	public function connect() {
57
		try {
58
			return parent::connect();
59
		} catch (DBALException $e) {
60
			// throw a new exception to prevent leaking info from the stacktrace
61
			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
		}
63
	}
64
65
	/**
66
	 * Returns a QueryBuilder for the connection.
67
	 *
68
	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
69
	 */
70
	public function getQueryBuilder() {
71
		return new QueryBuilder($this);
72
	}
73
74
	/**
75
	 * Gets the QueryBuilder for the connection.
76
	 *
77
	 * @return \Doctrine\DBAL\Query\QueryBuilder
78
	 * @deprecated please use $this->getQueryBuilder() instead
79
	 */
80
	public function createQueryBuilder() {
81
		$backtrace = $this->getCallerBacktrace();
82
		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
83
		return parent::createQueryBuilder();
84
	}
85
86
	/**
87
	 * Gets the ExpressionBuilder for the connection.
88
	 *
89
	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
90
	 * @deprecated please use $this->getQueryBuilder()->expr() instead
91
	 */
92
	public function getExpressionBuilder() {
93
		$backtrace = $this->getCallerBacktrace();
94
		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
95
		return parent::getExpressionBuilder();
96
	}
97
98
	/**
99
	 * Get the file and line that called the method where `getCallerBacktrace()` was used
100
	 *
101
	 * @return string
102
	 */
103
	protected function getCallerBacktrace() {
104
		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
105
106
		// 0 is the method where we use `getCallerBacktrace`
107
		// 1 is the target method which uses the method we want to log
108
		if (isset($traces[1])) {
109
			return $traces[1]['file'] . ':' . $traces[1]['line'];
110
		}
111
112
		return '';
113
	}
114
115
	/**
116
	 * @return string
117
	 */
118
	public function getPrefix() {
119
		return $this->tablePrefix;
120
	}
121
122
	/**
123
	 * Initializes a new instance of the Connection class.
124
	 *
125
	 * @param array $params  The connection parameters.
126
	 * @param \Doctrine\DBAL\Driver $driver
127
	 * @param \Doctrine\DBAL\Configuration $config
128
	 * @param \Doctrine\Common\EventManager $eventManager
129
	 * @throws \Exception
130
	 */
131
	public function __construct(array $params, Driver $driver, Configuration $config = null,
132
		EventManager $eventManager = null)
133
	{
134
		if (!isset($params['adapter'])) {
135
			throw new \Exception('adapter not set');
136
		}
137
		if (!isset($params['tablePrefix'])) {
138
			throw new \Exception('tablePrefix not set');
139
		}
140
		parent::__construct($params, $driver, $config, $eventManager);
141
		$this->adapter = new $params['adapter']($this);
142
		$this->tablePrefix = $params['tablePrefix'];
143
144
		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...
145
	}
146
147
	/**
148
	 * Prepares an SQL statement.
149
	 *
150
	 * @param string $statement The SQL statement to prepare.
151
	 * @param int $limit
152
	 * @param int $offset
153
	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
154
	 */
155
	public function prepare( $statement, $limit=null, $offset=null ) {
156
		if ($limit === -1) {
157
			$limit = null;
158
		}
159
		if (!is_null($limit)) {
160
			$platform = $this->getDatabasePlatform();
161
			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
162
		}
163
		$statement = $this->replaceTablePrefix($statement);
164
		$statement = $this->adapter->fixupStatement($statement);
165
166
		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
167
			Util::writeLog('core', 'DB prepare : '.$statement, Util::DEBUG);
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
	private function getType($value) {
254
		if (is_bool($value)) {
255
			return IQueryBuilder::PARAM_BOOL;
256
		} else if (is_int($value)) {
257
			return IQueryBuilder::PARAM_INT;
258
		} else {
259
			return IQueryBuilder::PARAM_STR;
260
		}
261
	}
262
263
	/**
264
	 * Insert or update a row value
265
	 *
266
	 * @param string $table
267
	 * @param array $keys (column name => value)
268
	 * @param array $values (column name => value)
269
	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
270
	 * @return int number of new rows
271
	 * @throws \Doctrine\DBAL\DBALException
272
	 * @throws PreConditionNotMetException
273
	 */
274
	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
275
		try {
276
			$insertQb = $this->getQueryBuilder();
277
			$insertQb->insert($table)
278
				->values(
279
					array_map(function($value) use ($insertQb) {
280
						return $insertQb->createNamedParameter($value, $this->getType($value));
281
					}, array_merge($keys, $values))
282
				);
283
			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 283 which is incompatible with the return type declared by the interface OCP\IDBConnection::setValues of type integer.
Loading history...
284
		} catch (ConstraintViolationException $e) {
285
			// value already exists, try update
286
			$updateQb = $this->getQueryBuilder();
287
			$updateQb->update($table);
288
			foreach ($values as $name => $value) {
289
				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
290
			}
291
			$where = $updateQb->expr()->andX();
292
			$whereValues = array_merge($keys, $updatePreconditionValues);
293
			foreach ($whereValues as $name => $value) {
294
				$where->add($updateQb->expr()->eq(
295
					$name,
296
					$updateQb->createNamedParameter($value, $this->getType($value)),
297
					$this->getType($value)
298
				));
299
			}
300
			$updateQb->where($where);
301
			$affected = $updateQb->execute();
302
303
			if ($affected === 0 && !empty($updatePreconditionValues)) {
304
				throw new PreConditionNotMetException();
305
			}
306
307
			return 0;
308
		}
309
	}
310
311
	/**
312
	 * Create an exclusive read+write lock on a table
313
	 *
314
	 * @param string $tableName
315
	 * @throws \BadMethodCallException When trying to acquire a second lock
316
	 * @since 9.1.0
317
	 */
318
	public function lockTable($tableName) {
319
		if ($this->lockedTable !== null) {
320
			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
321
		}
322
323
		$tableName = $this->tablePrefix . $tableName;
324
		$this->lockedTable = $tableName;
325
		$this->adapter->lockTable($tableName);
326
	}
327
328
	/**
329
	 * Release a previous acquired lock again
330
	 *
331
	 * @since 9.1.0
332
	 */
333
	public function unlockTable() {
334
		$this->adapter->unlockTable();
335
		$this->lockedTable = null;
336
	}
337
338
	/**
339
	 * returns the error code and message as a string for logging
340
	 * works with DoctrineException
341
	 * @return string
342
	 */
343
	public function getError() {
344
		$msg = $this->errorCode() . ': ';
345
		$errorInfo = $this->errorInfo();
346
		if (is_array($errorInfo)) {
347
			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
348
			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
349
			$msg .= 'Driver Message = '.$errorInfo[2];
350
		}
351
		return $msg;
352
	}
353
354
	/**
355
	 * Drop a table from the database if it exists
356
	 *
357
	 * @param string $table table name without the prefix
358
	 */
359 View Code Duplication
	public function dropTable($table) {
360
		$table = $this->tablePrefix . trim($table);
361
		$schema = $this->getSchemaManager();
362
		if($schema->tablesExist([$table])) {
363
			$schema->dropTable($table);
364
		}
365
	}
366
367
	/**
368
	 * Check if a table exists
369
	 *
370
	 * @param string $table table name without the prefix
371
	 * @return bool
372
	 */
373
	public function tableExists($table){
374
		$table = $this->tablePrefix . trim($table);
375
		$schema = $this->getSchemaManager();
376
		return $schema->tablesExist([$table]);
377
	}
378
379
	// internal use
380
	/**
381
	 * @param string $statement
382
	 * @return string
383
	 */
384
	protected function replaceTablePrefix($statement) {
385
		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
386
	}
387
388
	/**
389
	 * Check if a transaction is active
390
	 *
391
	 * @return bool
392
	 * @since 8.2.0
393
	 */
394
	public function inTransaction() {
395
		return $this->getTransactionNestingLevel() > 0;
396
	}
397
398
	/**
399
	 * Espace a parameter to be used in a LIKE query
400
	 *
401
	 * @param string $param
402
	 * @return string
403
	 */
404
	public function escapeLikeParameter($param) {
405
		return addcslashes($param, '\\_%');
406
	}
407
408
	/**
409
	 * Create the schema of the connected database
410
	 *
411
	 * @return Schema
412
	 */
413
	public function createSchema() {
414
		$schemaManager = new MDB2SchemaManager($this);
415
		$migrator = $schemaManager->getMigrator();
416
		return $migrator->createSchema();
417
	}
418
419
	/**
420
	 * Migrate the database to the given schema
421
	 *
422
	 * @param Schema $toSchema
423
	 */
424
	public function migrateToSchema(Schema $toSchema) {
425
		$schemaManager = new MDB2SchemaManager($this);
426
		$migrator = $schemaManager->getMigrator();
427
		$migrator->migrate($toSchema);
428
	}
429
430
}
431