Completed
Push — master ( 718d85...a50954 )
by Piotr
43:28
created

Connection::lastInsertId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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