| Total Complexity | 51 | 
| Total Lines | 446 | 
| Duplicated Lines | 0 % | 
| Changes | 0 | ||
Complex classes like Connection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Connection, and based on these observations, apply Extract Interface, too.
| 1 | <?php | ||
| 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() { | ||
| 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(); | ||
|  | |||
| 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)) { | ||
| 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() { | ||
| 491 | } | ||
| 492 | |||
| 493 | /** | ||
| 494 | * Migrate the database to the given schema | ||
| 495 | * | ||
| 496 | * @param Schema $toSchema | ||
| 497 | */ | ||
| 498 | 	public function migrateToSchema(Schema $toSchema) { | ||
| 502 | } | ||
| 503 | } | ||
| 504 |