Completed
Push — master ( d197f6...1397b8 )
by Morris
32:43 queued 21:43
created
lib/private/DB/Connection.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 			return parent::connect();
57 57
 		} catch (DBALException $e) {
58 58
 			// throw a new exception to prevent leaking info from the stacktrace
59
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
59
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
60 60
 		}
61 61
 	}
62 62
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		// 0 is the method where we use `getCallerBacktrace`
105 105
 		// 1 is the target method which uses the method we want to log
106 106
 		if (isset($traces[1])) {
107
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
107
+			return $traces[1]['file'].':'.$traces[1]['line'];
108 108
 		}
109 109
 
110 110
 		return '';
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	 * @param int $offset
151 151
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
152 152
 	 */
153
-	public function prepare( $statement, $limit=null, $offset=null ) {
153
+	public function prepare($statement, $limit = null, $offset = null) {
154 154
 		if ($limit === -1) {
155 155
 			$limit = null;
156 156
 		}
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 		$statement = $this->replaceTablePrefix($statement);
162 162
 		$statement = $this->adapter->fixupStatement($statement);
163 163
 
164
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
164
+		if (\OC::$server->getSystemConfig()->getValue('log_query', false)) {
165 165
 			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
166 166
 		}
167 167
 		return parent::prepare($statement);
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
319 319
 		}
320 320
 
321
-		$tableName = $this->tablePrefix . $tableName;
321
+		$tableName = $this->tablePrefix.$tableName;
322 322
 		$this->lockedTable = $tableName;
323 323
 		$this->adapter->lockTable($tableName);
324 324
 	}
@@ -339,11 +339,11 @@  discard block
 block discarded – undo
339 339
 	 * @return string
340 340
 	 */
341 341
 	public function getError() {
342
-		$msg = $this->errorCode() . ': ';
342
+		$msg = $this->errorCode().': ';
343 343
 		$errorInfo = $this->errorInfo();
344 344
 		if (is_array($errorInfo)) {
345
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
346
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
345
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
346
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
347 347
 			$msg .= 'Driver Message = '.$errorInfo[2];
348 348
 		}
349 349
 		return $msg;
@@ -355,9 +355,9 @@  discard block
 block discarded – undo
355 355
 	 * @param string $table table name without the prefix
356 356
 	 */
357 357
 	public function dropTable($table) {
358
-		$table = $this->tablePrefix . trim($table);
358
+		$table = $this->tablePrefix.trim($table);
359 359
 		$schema = $this->getSchemaManager();
360
-		if($schema->tablesExist(array($table))) {
360
+		if ($schema->tablesExist(array($table))) {
361 361
 			$schema->dropTable($table);
362 362
 		}
363 363
 	}
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 	 * @param string $table table name without the prefix
369 369
 	 * @return bool
370 370
 	 */
371
-	public function tableExists($table){
372
-		$table = $this->tablePrefix . trim($table);
371
+	public function tableExists($table) {
372
+		$table = $this->tablePrefix.trim($table);
373 373
 		$schema = $this->getSchemaManager();
374 374
 		return $schema->tablesExist(array($table));
375 375
 	}
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * @return string
381 381
 	 */
382 382
 	protected function replaceTablePrefix($statement) {
383
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
383
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
384 384
 	}
385 385
 
386 386
 	/**
Please login to merge, or discard this patch.
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -41,384 +41,384 @@
 block discarded – undo
41 41
 use OCP\PreConditionNotMetException;
42 42
 
43 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(
72
-			$this,
73
-			\OC::$server->getSystemConfig(),
74
-			\OC::$server->getLogger()
75
-		);
76
-	}
77
-
78
-	/**
79
-	 * Gets the QueryBuilder for the connection.
80
-	 *
81
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
82
-	 * @deprecated please use $this->getQueryBuilder() instead
83
-	 */
84
-	public function createQueryBuilder() {
85
-		$backtrace = $this->getCallerBacktrace();
86
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
-		return parent::createQueryBuilder();
88
-	}
89
-
90
-	/**
91
-	 * Gets the ExpressionBuilder for the connection.
92
-	 *
93
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
95
-	 */
96
-	public function getExpressionBuilder() {
97
-		$backtrace = $this->getCallerBacktrace();
98
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
-		return parent::getExpressionBuilder();
100
-	}
101
-
102
-	/**
103
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
104
-	 *
105
-	 * @return string
106
-	 */
107
-	protected function getCallerBacktrace() {
108
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
-
110
-		// 0 is the method where we use `getCallerBacktrace`
111
-		// 1 is the target method which uses the method we want to log
112
-		if (isset($traces[1])) {
113
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
114
-		}
115
-
116
-		return '';
117
-	}
118
-
119
-	/**
120
-	 * @return string
121
-	 */
122
-	public function getPrefix() {
123
-		return $this->tablePrefix;
124
-	}
125
-
126
-	/**
127
-	 * Initializes a new instance of the Connection class.
128
-	 *
129
-	 * @param array $params  The connection parameters.
130
-	 * @param \Doctrine\DBAL\Driver $driver
131
-	 * @param \Doctrine\DBAL\Configuration $config
132
-	 * @param \Doctrine\Common\EventManager $eventManager
133
-	 * @throws \Exception
134
-	 */
135
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
136
-		EventManager $eventManager = null)
137
-	{
138
-		if (!isset($params['adapter'])) {
139
-			throw new \Exception('adapter not set');
140
-		}
141
-		if (!isset($params['tablePrefix'])) {
142
-			throw new \Exception('tablePrefix not set');
143
-		}
144
-		parent::__construct($params, $driver, $config, $eventManager);
145
-		$this->adapter = new $params['adapter']($this);
146
-		$this->tablePrefix = $params['tablePrefix'];
147
-
148
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
-	}
150
-
151
-	/**
152
-	 * Prepares an SQL statement.
153
-	 *
154
-	 * @param string $statement The SQL statement to prepare.
155
-	 * @param int $limit
156
-	 * @param int $offset
157
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
-	 */
159
-	public function prepare( $statement, $limit=null, $offset=null ) {
160
-		if ($limit === -1) {
161
-			$limit = null;
162
-		}
163
-		if (!is_null($limit)) {
164
-			$platform = $this->getDatabasePlatform();
165
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
-		}
167
-		$statement = $this->replaceTablePrefix($statement);
168
-		$statement = $this->adapter->fixupStatement($statement);
169
-
170
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
171
-			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
172
-		}
173
-		return parent::prepare($statement);
174
-	}
175
-
176
-	/**
177
-	 * Executes an, optionally parametrized, SQL query.
178
-	 *
179
-	 * If the query is parametrized, a prepared statement is used.
180
-	 * If an SQLLogger is configured, the execution is logged.
181
-	 *
182
-	 * @param string                                      $query  The SQL query to execute.
183
-	 * @param array                                       $params The parameters to bind to the query, if any.
184
-	 * @param array                                       $types  The types the previous parameters are in.
185
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
186
-	 *
187
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
188
-	 *
189
-	 * @throws \Doctrine\DBAL\DBALException
190
-	 */
191
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
192
-	{
193
-		$query = $this->replaceTablePrefix($query);
194
-		$query = $this->adapter->fixupStatement($query);
195
-		return parent::executeQuery($query, $params, $types, $qcp);
196
-	}
197
-
198
-	/**
199
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
200
-	 * and returns the number of affected rows.
201
-	 *
202
-	 * This method supports PDO binding types as well as DBAL mapping types.
203
-	 *
204
-	 * @param string $query  The SQL query.
205
-	 * @param array  $params The query parameters.
206
-	 * @param array  $types  The parameter types.
207
-	 *
208
-	 * @return integer The number of affected rows.
209
-	 *
210
-	 * @throws \Doctrine\DBAL\DBALException
211
-	 */
212
-	public function executeUpdate($query, array $params = array(), array $types = array())
213
-	{
214
-		$query = $this->replaceTablePrefix($query);
215
-		$query = $this->adapter->fixupStatement($query);
216
-		return parent::executeUpdate($query, $params, $types);
217
-	}
218
-
219
-	/**
220
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
221
-	 * depending on the underlying driver.
222
-	 *
223
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
224
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
225
-	 * columns or sequences.
226
-	 *
227
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
228
-	 * @return string A string representation of the last inserted ID.
229
-	 */
230
-	public function lastInsertId($seqName = null) {
231
-		if ($seqName) {
232
-			$seqName = $this->replaceTablePrefix($seqName);
233
-		}
234
-		return $this->adapter->lastInsertId($seqName);
235
-	}
236
-
237
-	// internal use
238
-	public function realLastInsertId($seqName = null) {
239
-		return parent::lastInsertId($seqName);
240
-	}
241
-
242
-	/**
243
-	 * Insert a row if the matching row does not exists.
244
-	 *
245
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
246
-	 * @param array $input data that should be inserted into the table  (column name => value)
247
-	 * @param array|null $compare List of values that should be checked for "if not exists"
248
-	 *				If this is null or an empty array, all keys of $input will be compared
249
-	 *				Please note: text fields (clob) must not be used in the compare array
250
-	 * @return int number of inserted rows
251
-	 * @throws \Doctrine\DBAL\DBALException
252
-	 */
253
-	public function insertIfNotExist($table, $input, array $compare = null) {
254
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
255
-	}
256
-
257
-	private function getType($value) {
258
-		if (is_bool($value)) {
259
-			return IQueryBuilder::PARAM_BOOL;
260
-		} else if (is_int($value)) {
261
-			return IQueryBuilder::PARAM_INT;
262
-		} else {
263
-			return IQueryBuilder::PARAM_STR;
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * Insert or update a row value
269
-	 *
270
-	 * @param string $table
271
-	 * @param array $keys (column name => value)
272
-	 * @param array $values (column name => value)
273
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
274
-	 * @return int number of new rows
275
-	 * @throws \Doctrine\DBAL\DBALException
276
-	 * @throws PreConditionNotMetException
277
-	 */
278
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
279
-		try {
280
-			$insertQb = $this->getQueryBuilder();
281
-			$insertQb->insert($table)
282
-				->values(
283
-					array_map(function($value) use ($insertQb) {
284
-						return $insertQb->createNamedParameter($value, $this->getType($value));
285
-					}, array_merge($keys, $values))
286
-				);
287
-			return $insertQb->execute();
288
-		} catch (ConstraintViolationException $e) {
289
-			// value already exists, try update
290
-			$updateQb = $this->getQueryBuilder();
291
-			$updateQb->update($table);
292
-			foreach ($values as $name => $value) {
293
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
294
-			}
295
-			$where = $updateQb->expr()->andX();
296
-			$whereValues = array_merge($keys, $updatePreconditionValues);
297
-			foreach ($whereValues as $name => $value) {
298
-				$where->add($updateQb->expr()->eq(
299
-					$name,
300
-					$updateQb->createNamedParameter($value, $this->getType($value)),
301
-					$this->getType($value)
302
-				));
303
-			}
304
-			$updateQb->where($where);
305
-			$affected = $updateQb->execute();
306
-
307
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
308
-				throw new PreConditionNotMetException();
309
-			}
310
-
311
-			return 0;
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * Create an exclusive read+write lock on a table
317
-	 *
318
-	 * @param string $tableName
319
-	 * @throws \BadMethodCallException When trying to acquire a second lock
320
-	 * @since 9.1.0
321
-	 */
322
-	public function lockTable($tableName) {
323
-		if ($this->lockedTable !== null) {
324
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325
-		}
326
-
327
-		$tableName = $this->tablePrefix . $tableName;
328
-		$this->lockedTable = $tableName;
329
-		$this->adapter->lockTable($tableName);
330
-	}
331
-
332
-	/**
333
-	 * Release a previous acquired lock again
334
-	 *
335
-	 * @since 9.1.0
336
-	 */
337
-	public function unlockTable() {
338
-		$this->adapter->unlockTable();
339
-		$this->lockedTable = null;
340
-	}
341
-
342
-	/**
343
-	 * returns the error code and message as a string for logging
344
-	 * works with DoctrineException
345
-	 * @return string
346
-	 */
347
-	public function getError() {
348
-		$msg = $this->errorCode() . ': ';
349
-		$errorInfo = $this->errorInfo();
350
-		if (is_array($errorInfo)) {
351
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
353
-			$msg .= 'Driver Message = '.$errorInfo[2];
354
-		}
355
-		return $msg;
356
-	}
357
-
358
-	/**
359
-	 * Drop a table from the database if it exists
360
-	 *
361
-	 * @param string $table table name without the prefix
362
-	 */
363
-	public function dropTable($table) {
364
-		$table = $this->tablePrefix . trim($table);
365
-		$schema = $this->getSchemaManager();
366
-		if($schema->tablesExist(array($table))) {
367
-			$schema->dropTable($table);
368
-		}
369
-	}
370
-
371
-	/**
372
-	 * Check if a table exists
373
-	 *
374
-	 * @param string $table table name without the prefix
375
-	 * @return bool
376
-	 */
377
-	public function tableExists($table){
378
-		$table = $this->tablePrefix . trim($table);
379
-		$schema = $this->getSchemaManager();
380
-		return $schema->tablesExist(array($table));
381
-	}
382
-
383
-	// internal use
384
-	/**
385
-	 * @param string $statement
386
-	 * @return string
387
-	 */
388
-	protected function replaceTablePrefix($statement) {
389
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
390
-	}
391
-
392
-	/**
393
-	 * Check if a transaction is active
394
-	 *
395
-	 * @return bool
396
-	 * @since 8.2.0
397
-	 */
398
-	public function inTransaction() {
399
-		return $this->getTransactionNestingLevel() > 0;
400
-	}
401
-
402
-	/**
403
-	 * Espace a parameter to be used in a LIKE query
404
-	 *
405
-	 * @param string $param
406
-	 * @return string
407
-	 */
408
-	public function escapeLikeParameter($param) {
409
-		return addcslashes($param, '\\_%');
410
-	}
411
-
412
-	/**
413
-	 * Check whether or not the current database support 4byte wide unicode
414
-	 *
415
-	 * @return bool
416
-	 * @since 11.0.0
417
-	 */
418
-	public function supports4ByteText() {
419
-		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
420
-			return true;
421
-		}
422
-		return $this->getParams()['charset'] === 'utf8mb4';
423
-	}
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(
72
+            $this,
73
+            \OC::$server->getSystemConfig(),
74
+            \OC::$server->getLogger()
75
+        );
76
+    }
77
+
78
+    /**
79
+     * Gets the QueryBuilder for the connection.
80
+     *
81
+     * @return \Doctrine\DBAL\Query\QueryBuilder
82
+     * @deprecated please use $this->getQueryBuilder() instead
83
+     */
84
+    public function createQueryBuilder() {
85
+        $backtrace = $this->getCallerBacktrace();
86
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
+        return parent::createQueryBuilder();
88
+    }
89
+
90
+    /**
91
+     * Gets the ExpressionBuilder for the connection.
92
+     *
93
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
95
+     */
96
+    public function getExpressionBuilder() {
97
+        $backtrace = $this->getCallerBacktrace();
98
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
+        return parent::getExpressionBuilder();
100
+    }
101
+
102
+    /**
103
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
104
+     *
105
+     * @return string
106
+     */
107
+    protected function getCallerBacktrace() {
108
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
+
110
+        // 0 is the method where we use `getCallerBacktrace`
111
+        // 1 is the target method which uses the method we want to log
112
+        if (isset($traces[1])) {
113
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
114
+        }
115
+
116
+        return '';
117
+    }
118
+
119
+    /**
120
+     * @return string
121
+     */
122
+    public function getPrefix() {
123
+        return $this->tablePrefix;
124
+    }
125
+
126
+    /**
127
+     * Initializes a new instance of the Connection class.
128
+     *
129
+     * @param array $params  The connection parameters.
130
+     * @param \Doctrine\DBAL\Driver $driver
131
+     * @param \Doctrine\DBAL\Configuration $config
132
+     * @param \Doctrine\Common\EventManager $eventManager
133
+     * @throws \Exception
134
+     */
135
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
136
+        EventManager $eventManager = null)
137
+    {
138
+        if (!isset($params['adapter'])) {
139
+            throw new \Exception('adapter not set');
140
+        }
141
+        if (!isset($params['tablePrefix'])) {
142
+            throw new \Exception('tablePrefix not set');
143
+        }
144
+        parent::__construct($params, $driver, $config, $eventManager);
145
+        $this->adapter = new $params['adapter']($this);
146
+        $this->tablePrefix = $params['tablePrefix'];
147
+
148
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
+    }
150
+
151
+    /**
152
+     * Prepares an SQL statement.
153
+     *
154
+     * @param string $statement The SQL statement to prepare.
155
+     * @param int $limit
156
+     * @param int $offset
157
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
+     */
159
+    public function prepare( $statement, $limit=null, $offset=null ) {
160
+        if ($limit === -1) {
161
+            $limit = null;
162
+        }
163
+        if (!is_null($limit)) {
164
+            $platform = $this->getDatabasePlatform();
165
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
+        }
167
+        $statement = $this->replaceTablePrefix($statement);
168
+        $statement = $this->adapter->fixupStatement($statement);
169
+
170
+        if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
171
+            \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
172
+        }
173
+        return parent::prepare($statement);
174
+    }
175
+
176
+    /**
177
+     * Executes an, optionally parametrized, SQL query.
178
+     *
179
+     * If the query is parametrized, a prepared statement is used.
180
+     * If an SQLLogger is configured, the execution is logged.
181
+     *
182
+     * @param string                                      $query  The SQL query to execute.
183
+     * @param array                                       $params The parameters to bind to the query, if any.
184
+     * @param array                                       $types  The types the previous parameters are in.
185
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
186
+     *
187
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
188
+     *
189
+     * @throws \Doctrine\DBAL\DBALException
190
+     */
191
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
192
+    {
193
+        $query = $this->replaceTablePrefix($query);
194
+        $query = $this->adapter->fixupStatement($query);
195
+        return parent::executeQuery($query, $params, $types, $qcp);
196
+    }
197
+
198
+    /**
199
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
200
+     * and returns the number of affected rows.
201
+     *
202
+     * This method supports PDO binding types as well as DBAL mapping types.
203
+     *
204
+     * @param string $query  The SQL query.
205
+     * @param array  $params The query parameters.
206
+     * @param array  $types  The parameter types.
207
+     *
208
+     * @return integer The number of affected rows.
209
+     *
210
+     * @throws \Doctrine\DBAL\DBALException
211
+     */
212
+    public function executeUpdate($query, array $params = array(), array $types = array())
213
+    {
214
+        $query = $this->replaceTablePrefix($query);
215
+        $query = $this->adapter->fixupStatement($query);
216
+        return parent::executeUpdate($query, $params, $types);
217
+    }
218
+
219
+    /**
220
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
221
+     * depending on the underlying driver.
222
+     *
223
+     * Note: This method may not return a meaningful or consistent result across different drivers,
224
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
225
+     * columns or sequences.
226
+     *
227
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
228
+     * @return string A string representation of the last inserted ID.
229
+     */
230
+    public function lastInsertId($seqName = null) {
231
+        if ($seqName) {
232
+            $seqName = $this->replaceTablePrefix($seqName);
233
+        }
234
+        return $this->adapter->lastInsertId($seqName);
235
+    }
236
+
237
+    // internal use
238
+    public function realLastInsertId($seqName = null) {
239
+        return parent::lastInsertId($seqName);
240
+    }
241
+
242
+    /**
243
+     * Insert a row if the matching row does not exists.
244
+     *
245
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
246
+     * @param array $input data that should be inserted into the table  (column name => value)
247
+     * @param array|null $compare List of values that should be checked for "if not exists"
248
+     *				If this is null or an empty array, all keys of $input will be compared
249
+     *				Please note: text fields (clob) must not be used in the compare array
250
+     * @return int number of inserted rows
251
+     * @throws \Doctrine\DBAL\DBALException
252
+     */
253
+    public function insertIfNotExist($table, $input, array $compare = null) {
254
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
255
+    }
256
+
257
+    private function getType($value) {
258
+        if (is_bool($value)) {
259
+            return IQueryBuilder::PARAM_BOOL;
260
+        } else if (is_int($value)) {
261
+            return IQueryBuilder::PARAM_INT;
262
+        } else {
263
+            return IQueryBuilder::PARAM_STR;
264
+        }
265
+    }
266
+
267
+    /**
268
+     * Insert or update a row value
269
+     *
270
+     * @param string $table
271
+     * @param array $keys (column name => value)
272
+     * @param array $values (column name => value)
273
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
274
+     * @return int number of new rows
275
+     * @throws \Doctrine\DBAL\DBALException
276
+     * @throws PreConditionNotMetException
277
+     */
278
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
279
+        try {
280
+            $insertQb = $this->getQueryBuilder();
281
+            $insertQb->insert($table)
282
+                ->values(
283
+                    array_map(function($value) use ($insertQb) {
284
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
285
+                    }, array_merge($keys, $values))
286
+                );
287
+            return $insertQb->execute();
288
+        } catch (ConstraintViolationException $e) {
289
+            // value already exists, try update
290
+            $updateQb = $this->getQueryBuilder();
291
+            $updateQb->update($table);
292
+            foreach ($values as $name => $value) {
293
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
294
+            }
295
+            $where = $updateQb->expr()->andX();
296
+            $whereValues = array_merge($keys, $updatePreconditionValues);
297
+            foreach ($whereValues as $name => $value) {
298
+                $where->add($updateQb->expr()->eq(
299
+                    $name,
300
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
301
+                    $this->getType($value)
302
+                ));
303
+            }
304
+            $updateQb->where($where);
305
+            $affected = $updateQb->execute();
306
+
307
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
308
+                throw new PreConditionNotMetException();
309
+            }
310
+
311
+            return 0;
312
+        }
313
+    }
314
+
315
+    /**
316
+     * Create an exclusive read+write lock on a table
317
+     *
318
+     * @param string $tableName
319
+     * @throws \BadMethodCallException When trying to acquire a second lock
320
+     * @since 9.1.0
321
+     */
322
+    public function lockTable($tableName) {
323
+        if ($this->lockedTable !== null) {
324
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325
+        }
326
+
327
+        $tableName = $this->tablePrefix . $tableName;
328
+        $this->lockedTable = $tableName;
329
+        $this->adapter->lockTable($tableName);
330
+    }
331
+
332
+    /**
333
+     * Release a previous acquired lock again
334
+     *
335
+     * @since 9.1.0
336
+     */
337
+    public function unlockTable() {
338
+        $this->adapter->unlockTable();
339
+        $this->lockedTable = null;
340
+    }
341
+
342
+    /**
343
+     * returns the error code and message as a string for logging
344
+     * works with DoctrineException
345
+     * @return string
346
+     */
347
+    public function getError() {
348
+        $msg = $this->errorCode() . ': ';
349
+        $errorInfo = $this->errorInfo();
350
+        if (is_array($errorInfo)) {
351
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
353
+            $msg .= 'Driver Message = '.$errorInfo[2];
354
+        }
355
+        return $msg;
356
+    }
357
+
358
+    /**
359
+     * Drop a table from the database if it exists
360
+     *
361
+     * @param string $table table name without the prefix
362
+     */
363
+    public function dropTable($table) {
364
+        $table = $this->tablePrefix . trim($table);
365
+        $schema = $this->getSchemaManager();
366
+        if($schema->tablesExist(array($table))) {
367
+            $schema->dropTable($table);
368
+        }
369
+    }
370
+
371
+    /**
372
+     * Check if a table exists
373
+     *
374
+     * @param string $table table name without the prefix
375
+     * @return bool
376
+     */
377
+    public function tableExists($table){
378
+        $table = $this->tablePrefix . trim($table);
379
+        $schema = $this->getSchemaManager();
380
+        return $schema->tablesExist(array($table));
381
+    }
382
+
383
+    // internal use
384
+    /**
385
+     * @param string $statement
386
+     * @return string
387
+     */
388
+    protected function replaceTablePrefix($statement) {
389
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
390
+    }
391
+
392
+    /**
393
+     * Check if a transaction is active
394
+     *
395
+     * @return bool
396
+     * @since 8.2.0
397
+     */
398
+    public function inTransaction() {
399
+        return $this->getTransactionNestingLevel() > 0;
400
+    }
401
+
402
+    /**
403
+     * Espace a parameter to be used in a LIKE query
404
+     *
405
+     * @param string $param
406
+     * @return string
407
+     */
408
+    public function escapeLikeParameter($param) {
409
+        return addcslashes($param, '\\_%');
410
+    }
411
+
412
+    /**
413
+     * Check whether or not the current database support 4byte wide unicode
414
+     *
415
+     * @return bool
416
+     * @since 11.0.0
417
+     */
418
+    public function supports4ByteText() {
419
+        if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
420
+            return true;
421
+        }
422
+        return $this->getParams()['charset'] === 'utf8mb4';
423
+    }
424 424
 }
Please login to merge, or discard this patch.
lib/private/DB/MDB2SchemaReader.php 3 patches
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 					$this->loadTable($schema, $child);
95 95
 					break;
96 96
 				default:
97
-					throw new \DomainException('Unknown element: ' . $child->getName());
97
+					throw new \DomainException('Unknown element: '.$child->getName());
98 98
 
99 99
 			}
100 100
 		}
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			 */
115 115
 			switch ($child->getName()) {
116 116
 				case 'name':
117
-					$name = (string)$child;
117
+					$name = (string) $child;
118 118
 					$name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
119 119
 					$name = $this->platform->quoteIdentifier($name);
120 120
 					$table = $schema->createTable($name);
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 					$this->loadDeclaration($table, $child);
133 133
 					break;
134 134
 				default:
135
-					throw new \DomainException('Unknown element: ' . $child->getName());
135
+					throw new \DomainException('Unknown element: '.$child->getName());
136 136
 
137 137
 			}
138 138
 		}
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 					$this->loadIndex($table, $child);
157 157
 					break;
158 158
 				default:
159
-					throw new \DomainException('Unknown element: ' . $child->getName());
159
+					throw new \DomainException('Unknown element: '.$child->getName());
160 160
 
161 161
 			}
162 162
 		}
@@ -168,18 +168,18 @@  discard block
 block discarded – undo
168 168
 	 * @throws \DomainException
169 169
 	 */
170 170
 	private function loadField($table, $xml) {
171
-		$options = array( 'notnull' => false );
171
+		$options = array('notnull' => false);
172 172
 		foreach ($xml->children() as $child) {
173 173
 			/**
174 174
 			 * @var \SimpleXMLElement $child
175 175
 			 */
176 176
 			switch ($child->getName()) {
177 177
 				case 'name':
178
-					$name = (string)$child;
178
+					$name = (string) $child;
179 179
 					$name = $this->platform->quoteIdentifier($name);
180 180
 					break;
181 181
 				case 'type':
182
-					$type = (string)$child;
182
+					$type = (string) $child;
183 183
 					switch ($type) {
184 184
 						case 'text':
185 185
 							$type = 'string';
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 					}
197 197
 					break;
198 198
 				case 'length':
199
-					$length = (string)$child;
199
+					$length = (string) $child;
200 200
 					$options['length'] = $length;
201 201
 					break;
202 202
 				case 'unsigned':
@@ -212,11 +212,11 @@  discard block
 block discarded – undo
212 212
 					$options['autoincrement'] = $autoincrement;
213 213
 					break;
214 214
 				case 'default':
215
-					$default = (string)$child;
215
+					$default = (string) $child;
216 216
 					$options['default'] = $default;
217 217
 					break;
218 218
 				case 'comments':
219
-					$comment = (string)$child;
219
+					$comment = (string) $child;
220 220
 					$options['comment'] = $comment;
221 221
 					break;
222 222
 				case 'primary':
@@ -224,15 +224,15 @@  discard block
 block discarded – undo
224 224
 					$options['primary'] = $primary;
225 225
 					break;
226 226
 				case 'precision':
227
-					$precision = (string)$child;
227
+					$precision = (string) $child;
228 228
 					$options['precision'] = $precision;
229 229
 					break;
230 230
 				case 'scale':
231
-					$scale = (string)$child;
231
+					$scale = (string) $child;
232 232
 					$options['scale'] = $scale;
233 233
 					break;
234 234
 				default:
235
-					throw new \DomainException('Unknown element: ' . $child->getName());
235
+					throw new \DomainException('Unknown element: '.$child->getName());
236 236
 
237 237
 			}
238 238
 		}
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 				}
255 255
 			}
256 256
 			if ($type === 'integer' && isset($options['default'])) {
257
-				$options['default'] = (int)$options['default'];
257
+				$options['default'] = (int) $options['default'];
258 258
 			}
259 259
 			if ($type === 'integer' && isset($options['length'])) {
260 260
 				$length = $options['length'];
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
 			 */
294 294
 			switch ($child->getName()) {
295 295
 				case 'name':
296
-					$name = (string)$child;
296
+					$name = (string) $child;
297 297
 					break;
298 298
 				case 'primary':
299 299
 					$primary = $this->asBool($child);
@@ -308,20 +308,20 @@  discard block
 block discarded – undo
308 308
 						 */
309 309
 						switch ($field->getName()) {
310 310
 							case 'name':
311
-								$field_name = (string)$field;
311
+								$field_name = (string) $field;
312 312
 								$field_name = $this->platform->quoteIdentifier($field_name);
313 313
 								$fields[] = $field_name;
314 314
 								break;
315 315
 							case 'sorting':
316 316
 								break;
317 317
 							default:
318
-								throw new \DomainException('Unknown element: ' . $field->getName());
318
+								throw new \DomainException('Unknown element: '.$field->getName());
319 319
 
320 320
 						}
321 321
 					}
322 322
 					break;
323 323
 				default:
324
-					throw new \DomainException('Unknown element: ' . $child->getName());
324
+					throw new \DomainException('Unknown element: '.$child->getName());
325 325
 
326 326
 			}
327 327
 		}
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 				}
340 340
 			}
341 341
 		} else {
342
-			throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
342
+			throw new \DomainException('Empty index definition: '.$name.' options:'.print_r($fields, true));
343 343
 		}
344 344
 	}
345 345
 
@@ -348,13 +348,13 @@  discard block
 block discarded – undo
348 348
 	 * @return bool
349 349
 	 */
350 350
 	private function asBool($xml) {
351
-		$result = (string)$xml;
351
+		$result = (string) $xml;
352 352
 		if ($result == 'true') {
353 353
 			$result = true;
354 354
 		} elseif ($result == 'false') {
355 355
 			$result = false;
356 356
 		}
357
-		return (bool)$result;
357
+		return (bool) $result;
358 358
 	}
359 359
 
360 360
 }
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -32,8 +32,6 @@
 block discarded – undo
32 32
 namespace OC\DB;
33 33
 
34 34
 use Doctrine\DBAL\Platforms\AbstractPlatform;
35
-use Doctrine\DBAL\Schema\SchemaConfig;
36
-use Doctrine\DBAL\Platforms\MySqlPlatform;
37 35
 use Doctrine\DBAL\Schema\Schema;
38 36
 use OCP\IConfig;
39 37
 
Please login to merge, or discard this patch.
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -39,313 +39,313 @@
 block discarded – undo
39 39
 
40 40
 class MDB2SchemaReader {
41 41
 
42
-	/**
43
-	 * @var string $DBTABLEPREFIX
44
-	 */
45
-	protected $DBTABLEPREFIX;
42
+    /**
43
+     * @var string $DBTABLEPREFIX
44
+     */
45
+    protected $DBTABLEPREFIX;
46 46
 
47
-	/**
48
-	 * @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform
49
-	 */
50
-	protected $platform;
47
+    /**
48
+     * @var \Doctrine\DBAL\Platforms\AbstractPlatform $platform
49
+     */
50
+    protected $platform;
51 51
 
52
-	/** @var IConfig */
53
-	protected $config;
52
+    /** @var IConfig */
53
+    protected $config;
54 54
 
55
-	/**
56
-	 * @param \OCP\IConfig $config
57
-	 * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
58
-	 */
59
-	public function __construct(IConfig $config, AbstractPlatform $platform) {
60
-		$this->platform = $platform;
61
-		$this->config = $config;
62
-		$this->DBTABLEPREFIX = $config->getSystemValue('dbtableprefix', 'oc_');
63
-	}
55
+    /**
56
+     * @param \OCP\IConfig $config
57
+     * @param \Doctrine\DBAL\Platforms\AbstractPlatform $platform
58
+     */
59
+    public function __construct(IConfig $config, AbstractPlatform $platform) {
60
+        $this->platform = $platform;
61
+        $this->config = $config;
62
+        $this->DBTABLEPREFIX = $config->getSystemValue('dbtableprefix', 'oc_');
63
+    }
64 64
 
65
-	/**
66
-	 * @param string $file
67
-	 * @param Schema $schema
68
-	 * @return Schema
69
-	 * @throws \DomainException
70
-	 */
71
-	public function loadSchemaFromFile($file, Schema $schema) {
72
-		$loadEntities = libxml_disable_entity_loader(false);
73
-		$xml = simplexml_load_file($file);
74
-		libxml_disable_entity_loader($loadEntities);
75
-		foreach ($xml->children() as $child) {
76
-			/**
77
-			 * @var \SimpleXMLElement $child
78
-			 */
79
-			switch ($child->getName()) {
80
-				case 'name':
81
-				case 'create':
82
-				case 'overwrite':
83
-				case 'charset':
84
-					break;
85
-				case 'table':
86
-					$this->loadTable($schema, $child);
87
-					break;
88
-				default:
89
-					throw new \DomainException('Unknown element: ' . $child->getName());
65
+    /**
66
+     * @param string $file
67
+     * @param Schema $schema
68
+     * @return Schema
69
+     * @throws \DomainException
70
+     */
71
+    public function loadSchemaFromFile($file, Schema $schema) {
72
+        $loadEntities = libxml_disable_entity_loader(false);
73
+        $xml = simplexml_load_file($file);
74
+        libxml_disable_entity_loader($loadEntities);
75
+        foreach ($xml->children() as $child) {
76
+            /**
77
+             * @var \SimpleXMLElement $child
78
+             */
79
+            switch ($child->getName()) {
80
+                case 'name':
81
+                case 'create':
82
+                case 'overwrite':
83
+                case 'charset':
84
+                    break;
85
+                case 'table':
86
+                    $this->loadTable($schema, $child);
87
+                    break;
88
+                default:
89
+                    throw new \DomainException('Unknown element: ' . $child->getName());
90 90
 
91
-			}
92
-		}
93
-		return $schema;
94
-	}
91
+            }
92
+        }
93
+        return $schema;
94
+    }
95 95
 
96
-	/**
97
-	 * @param \Doctrine\DBAL\Schema\Schema $schema
98
-	 * @param \SimpleXMLElement $xml
99
-	 * @throws \DomainException
100
-	 */
101
-	private function loadTable($schema, $xml) {
102
-		$table = null;
103
-		foreach ($xml->children() as $child) {
104
-			/**
105
-			 * @var \SimpleXMLElement $child
106
-			 */
107
-			switch ($child->getName()) {
108
-				case 'name':
109
-					$name = (string)$child;
110
-					$name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
111
-					$name = $this->platform->quoteIdentifier($name);
112
-					$table = $schema->createTable($name);
113
-					break;
114
-				case 'create':
115
-				case 'overwrite':
116
-				case 'charset':
117
-					break;
118
-				case 'declaration':
119
-					if (is_null($table)) {
120
-						throw new \DomainException('Table declaration before table name');
121
-					}
122
-					$this->loadDeclaration($table, $child);
123
-					break;
124
-				default:
125
-					throw new \DomainException('Unknown element: ' . $child->getName());
96
+    /**
97
+     * @param \Doctrine\DBAL\Schema\Schema $schema
98
+     * @param \SimpleXMLElement $xml
99
+     * @throws \DomainException
100
+     */
101
+    private function loadTable($schema, $xml) {
102
+        $table = null;
103
+        foreach ($xml->children() as $child) {
104
+            /**
105
+             * @var \SimpleXMLElement $child
106
+             */
107
+            switch ($child->getName()) {
108
+                case 'name':
109
+                    $name = (string)$child;
110
+                    $name = str_replace('*dbprefix*', $this->DBTABLEPREFIX, $name);
111
+                    $name = $this->platform->quoteIdentifier($name);
112
+                    $table = $schema->createTable($name);
113
+                    break;
114
+                case 'create':
115
+                case 'overwrite':
116
+                case 'charset':
117
+                    break;
118
+                case 'declaration':
119
+                    if (is_null($table)) {
120
+                        throw new \DomainException('Table declaration before table name');
121
+                    }
122
+                    $this->loadDeclaration($table, $child);
123
+                    break;
124
+                default:
125
+                    throw new \DomainException('Unknown element: ' . $child->getName());
126 126
 
127
-			}
128
-		}
129
-	}
127
+            }
128
+        }
129
+    }
130 130
 
131
-	/**
132
-	 * @param \Doctrine\DBAL\Schema\Table $table
133
-	 * @param \SimpleXMLElement $xml
134
-	 * @throws \DomainException
135
-	 */
136
-	private function loadDeclaration($table, $xml) {
137
-		foreach ($xml->children() as $child) {
138
-			/**
139
-			 * @var \SimpleXMLElement $child
140
-			 */
141
-			switch ($child->getName()) {
142
-				case 'field':
143
-					$this->loadField($table, $child);
144
-					break;
145
-				case 'index':
146
-					$this->loadIndex($table, $child);
147
-					break;
148
-				default:
149
-					throw new \DomainException('Unknown element: ' . $child->getName());
131
+    /**
132
+     * @param \Doctrine\DBAL\Schema\Table $table
133
+     * @param \SimpleXMLElement $xml
134
+     * @throws \DomainException
135
+     */
136
+    private function loadDeclaration($table, $xml) {
137
+        foreach ($xml->children() as $child) {
138
+            /**
139
+             * @var \SimpleXMLElement $child
140
+             */
141
+            switch ($child->getName()) {
142
+                case 'field':
143
+                    $this->loadField($table, $child);
144
+                    break;
145
+                case 'index':
146
+                    $this->loadIndex($table, $child);
147
+                    break;
148
+                default:
149
+                    throw new \DomainException('Unknown element: ' . $child->getName());
150 150
 
151
-			}
152
-		}
153
-	}
151
+            }
152
+        }
153
+    }
154 154
 
155
-	/**
156
-	 * @param \Doctrine\DBAL\Schema\Table $table
157
-	 * @param \SimpleXMLElement $xml
158
-	 * @throws \DomainException
159
-	 */
160
-	private function loadField($table, $xml) {
161
-		$options = array( 'notnull' => false );
162
-		foreach ($xml->children() as $child) {
163
-			/**
164
-			 * @var \SimpleXMLElement $child
165
-			 */
166
-			switch ($child->getName()) {
167
-				case 'name':
168
-					$name = (string)$child;
169
-					$name = $this->platform->quoteIdentifier($name);
170
-					break;
171
-				case 'type':
172
-					$type = (string)$child;
173
-					switch ($type) {
174
-						case 'text':
175
-							$type = 'string';
176
-							break;
177
-						case 'clob':
178
-							$type = 'text';
179
-							break;
180
-						case 'timestamp':
181
-							$type = 'datetime';
182
-							break;
183
-						case 'numeric':
184
-							$type = 'decimal';
185
-							break;
186
-					}
187
-					break;
188
-				case 'length':
189
-					$length = (string)$child;
190
-					$options['length'] = $length;
191
-					break;
192
-				case 'unsigned':
193
-					$unsigned = $this->asBool($child);
194
-					$options['unsigned'] = $unsigned;
195
-					break;
196
-				case 'notnull':
197
-					$notnull = $this->asBool($child);
198
-					$options['notnull'] = $notnull;
199
-					break;
200
-				case 'autoincrement':
201
-					$autoincrement = $this->asBool($child);
202
-					$options['autoincrement'] = $autoincrement;
203
-					break;
204
-				case 'default':
205
-					$default = (string)$child;
206
-					$options['default'] = $default;
207
-					break;
208
-				case 'comments':
209
-					$comment = (string)$child;
210
-					$options['comment'] = $comment;
211
-					break;
212
-				case 'primary':
213
-					$primary = $this->asBool($child);
214
-					$options['primary'] = $primary;
215
-					break;
216
-				case 'precision':
217
-					$precision = (string)$child;
218
-					$options['precision'] = $precision;
219
-					break;
220
-				case 'scale':
221
-					$scale = (string)$child;
222
-					$options['scale'] = $scale;
223
-					break;
224
-				default:
225
-					throw new \DomainException('Unknown element: ' . $child->getName());
155
+    /**
156
+     * @param \Doctrine\DBAL\Schema\Table $table
157
+     * @param \SimpleXMLElement $xml
158
+     * @throws \DomainException
159
+     */
160
+    private function loadField($table, $xml) {
161
+        $options = array( 'notnull' => false );
162
+        foreach ($xml->children() as $child) {
163
+            /**
164
+             * @var \SimpleXMLElement $child
165
+             */
166
+            switch ($child->getName()) {
167
+                case 'name':
168
+                    $name = (string)$child;
169
+                    $name = $this->platform->quoteIdentifier($name);
170
+                    break;
171
+                case 'type':
172
+                    $type = (string)$child;
173
+                    switch ($type) {
174
+                        case 'text':
175
+                            $type = 'string';
176
+                            break;
177
+                        case 'clob':
178
+                            $type = 'text';
179
+                            break;
180
+                        case 'timestamp':
181
+                            $type = 'datetime';
182
+                            break;
183
+                        case 'numeric':
184
+                            $type = 'decimal';
185
+                            break;
186
+                    }
187
+                    break;
188
+                case 'length':
189
+                    $length = (string)$child;
190
+                    $options['length'] = $length;
191
+                    break;
192
+                case 'unsigned':
193
+                    $unsigned = $this->asBool($child);
194
+                    $options['unsigned'] = $unsigned;
195
+                    break;
196
+                case 'notnull':
197
+                    $notnull = $this->asBool($child);
198
+                    $options['notnull'] = $notnull;
199
+                    break;
200
+                case 'autoincrement':
201
+                    $autoincrement = $this->asBool($child);
202
+                    $options['autoincrement'] = $autoincrement;
203
+                    break;
204
+                case 'default':
205
+                    $default = (string)$child;
206
+                    $options['default'] = $default;
207
+                    break;
208
+                case 'comments':
209
+                    $comment = (string)$child;
210
+                    $options['comment'] = $comment;
211
+                    break;
212
+                case 'primary':
213
+                    $primary = $this->asBool($child);
214
+                    $options['primary'] = $primary;
215
+                    break;
216
+                case 'precision':
217
+                    $precision = (string)$child;
218
+                    $options['precision'] = $precision;
219
+                    break;
220
+                case 'scale':
221
+                    $scale = (string)$child;
222
+                    $options['scale'] = $scale;
223
+                    break;
224
+                default:
225
+                    throw new \DomainException('Unknown element: ' . $child->getName());
226 226
 
227
-			}
228
-		}
229
-		if (isset($name) && isset($type)) {
230
-			if (isset($options['default']) && empty($options['default'])) {
231
-				if (empty($options['notnull']) || !$options['notnull']) {
232
-					unset($options['default']);
233
-					$options['notnull'] = false;
234
-				} else {
235
-					$options['default'] = '';
236
-				}
237
-				if ($type == 'integer' || $type == 'decimal') {
238
-					$options['default'] = 0;
239
-				} elseif ($type == 'boolean') {
240
-					$options['default'] = false;
241
-				}
242
-				if (!empty($options['autoincrement']) && $options['autoincrement']) {
243
-					unset($options['default']);
244
-				}
245
-			}
246
-			if ($type === 'integer' && isset($options['default'])) {
247
-				$options['default'] = (int)$options['default'];
248
-			}
249
-			if ($type === 'integer' && isset($options['length'])) {
250
-				$length = $options['length'];
251
-				if ($length < 4) {
252
-					$type = 'smallint';
253
-				} else if ($length > 4) {
254
-					$type = 'bigint';
255
-				}
256
-			}
257
-			if ($type === 'boolean' && isset($options['default'])) {
258
-				$options['default'] = $this->asBool($options['default']);
259
-			}
260
-			if (!empty($options['autoincrement'])
261
-				&& !empty($options['notnull'])
262
-			) {
263
-				$options['primary'] = true;
264
-			}
227
+            }
228
+        }
229
+        if (isset($name) && isset($type)) {
230
+            if (isset($options['default']) && empty($options['default'])) {
231
+                if (empty($options['notnull']) || !$options['notnull']) {
232
+                    unset($options['default']);
233
+                    $options['notnull'] = false;
234
+                } else {
235
+                    $options['default'] = '';
236
+                }
237
+                if ($type == 'integer' || $type == 'decimal') {
238
+                    $options['default'] = 0;
239
+                } elseif ($type == 'boolean') {
240
+                    $options['default'] = false;
241
+                }
242
+                if (!empty($options['autoincrement']) && $options['autoincrement']) {
243
+                    unset($options['default']);
244
+                }
245
+            }
246
+            if ($type === 'integer' && isset($options['default'])) {
247
+                $options['default'] = (int)$options['default'];
248
+            }
249
+            if ($type === 'integer' && isset($options['length'])) {
250
+                $length = $options['length'];
251
+                if ($length < 4) {
252
+                    $type = 'smallint';
253
+                } else if ($length > 4) {
254
+                    $type = 'bigint';
255
+                }
256
+            }
257
+            if ($type === 'boolean' && isset($options['default'])) {
258
+                $options['default'] = $this->asBool($options['default']);
259
+            }
260
+            if (!empty($options['autoincrement'])
261
+                && !empty($options['notnull'])
262
+            ) {
263
+                $options['primary'] = true;
264
+            }
265 265
 
266
-			$table->addColumn($name, $type, $options);
267
-			if (!empty($options['primary']) && $options['primary']) {
268
-				$table->setPrimaryKey(array($name));
269
-			}
270
-		}
271
-	}
266
+            $table->addColumn($name, $type, $options);
267
+            if (!empty($options['primary']) && $options['primary']) {
268
+                $table->setPrimaryKey(array($name));
269
+            }
270
+        }
271
+    }
272 272
 
273
-	/**
274
-	 * @param \Doctrine\DBAL\Schema\Table $table
275
-	 * @param \SimpleXMLElement $xml
276
-	 * @throws \DomainException
277
-	 */
278
-	private function loadIndex($table, $xml) {
279
-		$name = null;
280
-		$fields = array();
281
-		foreach ($xml->children() as $child) {
282
-			/**
283
-			 * @var \SimpleXMLElement $child
284
-			 */
285
-			switch ($child->getName()) {
286
-				case 'name':
287
-					$name = (string)$child;
288
-					break;
289
-				case 'primary':
290
-					$primary = $this->asBool($child);
291
-					break;
292
-				case 'unique':
293
-					$unique = $this->asBool($child);
294
-					break;
295
-				case 'field':
296
-					foreach ($child->children() as $field) {
297
-						/**
298
-						 * @var \SimpleXMLElement $field
299
-						 */
300
-						switch ($field->getName()) {
301
-							case 'name':
302
-								$field_name = (string)$field;
303
-								$field_name = $this->platform->quoteIdentifier($field_name);
304
-								$fields[] = $field_name;
305
-								break;
306
-							case 'sorting':
307
-								break;
308
-							default:
309
-								throw new \DomainException('Unknown element: ' . $field->getName());
273
+    /**
274
+     * @param \Doctrine\DBAL\Schema\Table $table
275
+     * @param \SimpleXMLElement $xml
276
+     * @throws \DomainException
277
+     */
278
+    private function loadIndex($table, $xml) {
279
+        $name = null;
280
+        $fields = array();
281
+        foreach ($xml->children() as $child) {
282
+            /**
283
+             * @var \SimpleXMLElement $child
284
+             */
285
+            switch ($child->getName()) {
286
+                case 'name':
287
+                    $name = (string)$child;
288
+                    break;
289
+                case 'primary':
290
+                    $primary = $this->asBool($child);
291
+                    break;
292
+                case 'unique':
293
+                    $unique = $this->asBool($child);
294
+                    break;
295
+                case 'field':
296
+                    foreach ($child->children() as $field) {
297
+                        /**
298
+                         * @var \SimpleXMLElement $field
299
+                         */
300
+                        switch ($field->getName()) {
301
+                            case 'name':
302
+                                $field_name = (string)$field;
303
+                                $field_name = $this->platform->quoteIdentifier($field_name);
304
+                                $fields[] = $field_name;
305
+                                break;
306
+                            case 'sorting':
307
+                                break;
308
+                            default:
309
+                                throw new \DomainException('Unknown element: ' . $field->getName());
310 310
 
311
-						}
312
-					}
313
-					break;
314
-				default:
315
-					throw new \DomainException('Unknown element: ' . $child->getName());
311
+                        }
312
+                    }
313
+                    break;
314
+                default:
315
+                    throw new \DomainException('Unknown element: ' . $child->getName());
316 316
 
317
-			}
318
-		}
319
-		if (!empty($fields)) {
320
-			if (isset($primary) && $primary) {
321
-				if ($table->hasPrimaryKey()) {
322
-					return;
323
-				}
324
-				$table->setPrimaryKey($fields, $name);
325
-			} else {
326
-				if (isset($unique) && $unique) {
327
-					$table->addUniqueIndex($fields, $name);
328
-				} else {
329
-					$table->addIndex($fields, $name);
330
-				}
331
-			}
332
-		} else {
333
-			throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
334
-		}
335
-	}
317
+            }
318
+        }
319
+        if (!empty($fields)) {
320
+            if (isset($primary) && $primary) {
321
+                if ($table->hasPrimaryKey()) {
322
+                    return;
323
+                }
324
+                $table->setPrimaryKey($fields, $name);
325
+            } else {
326
+                if (isset($unique) && $unique) {
327
+                    $table->addUniqueIndex($fields, $name);
328
+                } else {
329
+                    $table->addIndex($fields, $name);
330
+                }
331
+            }
332
+        } else {
333
+            throw new \DomainException('Empty index definition: ' . $name . ' options:' . print_r($fields, true));
334
+        }
335
+    }
336 336
 
337
-	/**
338
-	 * @param \SimpleXMLElement|string $xml
339
-	 * @return bool
340
-	 */
341
-	private function asBool($xml) {
342
-		$result = (string)$xml;
343
-		if ($result == 'true') {
344
-			$result = true;
345
-		} elseif ($result == 'false') {
346
-			$result = false;
347
-		}
348
-		return (bool)$result;
349
-	}
337
+    /**
338
+     * @param \SimpleXMLElement|string $xml
339
+     * @return bool
340
+     */
341
+    private function asBool($xml) {
342
+        $result = (string)$xml;
343
+        if ($result == 'true') {
344
+            $result = true;
345
+        } elseif ($result == 'false') {
346
+            $result = false;
347
+        }
348
+        return (bool)$result;
349
+    }
350 350
 
351 351
 }
Please login to merge, or discard this patch.
lib/private/Migration/ConsoleOutput.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -37,57 +37,57 @@
 block discarded – undo
37 37
  */
38 38
 class ConsoleOutput implements IOutput {
39 39
 
40
-	/** @var OutputInterface */
41
-	private $output;
40
+    /** @var OutputInterface */
41
+    private $output;
42 42
 
43
-	/** @var ProgressBar */
44
-	private $progressBar;
43
+    /** @var ProgressBar */
44
+    private $progressBar;
45 45
 
46
-	public function __construct(OutputInterface $output) {
47
-		$this->output = $output;
48
-	}
46
+    public function __construct(OutputInterface $output) {
47
+        $this->output = $output;
48
+    }
49 49
 
50
-	/**
51
-	 * @param string $message
52
-	 */
53
-	public function info($message) {
54
-		$this->output->writeln("<info>$message</info>");
55
-	}
50
+    /**
51
+     * @param string $message
52
+     */
53
+    public function info($message) {
54
+        $this->output->writeln("<info>$message</info>");
55
+    }
56 56
 
57
-	/**
58
-	 * @param string $message
59
-	 */
60
-	public function warning($message) {
61
-		$this->output->writeln("<comment>$message</comment>");
62
-	}
57
+    /**
58
+     * @param string $message
59
+     */
60
+    public function warning($message) {
61
+        $this->output->writeln("<comment>$message</comment>");
62
+    }
63 63
 
64
-	/**
65
-	 * @param int $max
66
-	 */
67
-	public function startProgress($max = 0) {
68
-		if (!is_null($this->progressBar)) {
69
-			$this->progressBar->finish();
70
-		}
71
-		$this->progressBar = new ProgressBar($this->output);
72
-		$this->progressBar->start($max);
73
-	}
64
+    /**
65
+     * @param int $max
66
+     */
67
+    public function startProgress($max = 0) {
68
+        if (!is_null($this->progressBar)) {
69
+            $this->progressBar->finish();
70
+        }
71
+        $this->progressBar = new ProgressBar($this->output);
72
+        $this->progressBar->start($max);
73
+    }
74 74
 
75
-	/**
76
-	 * @param int $step
77
-	 * @param string $description
78
-	 */
79
-	public function advance($step = 1, $description = '') {
80
-		if (!is_null($this->progressBar)) {
81
-			$this->progressBar = new ProgressBar($this->output);
82
-			$this->progressBar->start();
83
-		}
84
-		$this->progressBar->advance($step);
85
-	}
75
+    /**
76
+     * @param int $step
77
+     * @param string $description
78
+     */
79
+    public function advance($step = 1, $description = '') {
80
+        if (!is_null($this->progressBar)) {
81
+            $this->progressBar = new ProgressBar($this->output);
82
+            $this->progressBar->start();
83
+        }
84
+        $this->progressBar->advance($step);
85
+    }
86 86
 
87
-	public function finishProgress() {
88
-		if (is_null($this->progressBar)) {
89
-			return;
90
-		}
91
-		$this->progressBar->finish();
92
-	}
87
+    public function finishProgress() {
88
+        if (is_null($this->progressBar)) {
89
+            return;
90
+        }
91
+        $this->progressBar->finish();
92
+    }
93 93
 }
Please login to merge, or discard this patch.
lib/private/Repair/Collation.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -33,120 +33,120 @@
 block discarded – undo
33 33
 use OCP\Migration\IRepairStep;
34 34
 
35 35
 class Collation implements IRepairStep {
36
-	/**  @var IConfig */
37
-	protected $config;
38
-
39
-	/** @var ILogger */
40
-	protected $logger;
41
-
42
-	/** @var IDBConnection */
43
-	protected $connection;
44
-
45
-	/** @var bool */
46
-	protected $ignoreFailures;
47
-
48
-	/**
49
-	 * @param IConfig $config
50
-	 * @param ILogger $logger
51
-	 * @param IDBConnection $connection
52
-	 * @param bool $ignoreFailures
53
-	 */
54
-	public function __construct(IConfig $config, ILogger $logger, IDBConnection $connection, $ignoreFailures) {
55
-		$this->connection = $connection;
56
-		$this->config = $config;
57
-		$this->logger = $logger;
58
-		$this->ignoreFailures = $ignoreFailures;
59
-	}
60
-
61
-	public function getName() {
62
-		return 'Repair MySQL collation';
63
-	}
64
-
65
-	/**
66
-	 * Fix mime types
67
-	 */
68
-	public function run(IOutput $output) {
69
-		if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
70
-			$output->info('Not a mysql database -> nothing to do');
71
-			return;
72
-		}
73
-
74
-		$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
75
-
76
-		$tables = $this->getAllNonUTF8BinTables($this->connection);
77
-		foreach ($tables as $table) {
78
-			$output->info("Change row format for $table ...");
79
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT = DYNAMIC;');
80
-			try {
81
-				$query->execute();
82
-			} catch (DriverException $e) {
83
-				// Just log this
84
-				$this->logger->logException($e);
85
-				if (!$this->ignoreFailures) {
86
-					throw $e;
87
-				}
88
-			}
89
-
90
-			$output->info("Change collation for $table ...");
91
-			if ($characterSet === 'utf8mb4') {
92
-				// need to set row compression first
93
-				$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT=COMPRESSED;');
94
-				$query->execute();
95
-			}
96
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $characterSet . '_bin;');
97
-			try {
98
-				$query->execute();
99
-			} catch (DriverException $e) {
100
-				// Just log this
101
-				$this->logger->logException($e);
102
-				if (!$this->ignoreFailures) {
103
-					throw $e;
104
-				}
105
-			}
106
-		}
107
-		if (empty($tables)) {
108
-			$output->info('All tables already have the correct collation -> nothing to do');
109
-		}
110
-	}
111
-
112
-	/**
113
-	 * @param IDBConnection $connection
114
-	 * @return string[]
115
-	 */
116
-	protected function getAllNonUTF8BinTables(IDBConnection $connection) {
117
-		$dbName = $this->config->getSystemValue("dbname");
118
-		$characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
119
-
120
-		// fetch tables by columns
121
-		$statement = $connection->executeQuery(
122
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
123
-			"	FROM INFORMATION_SCHEMA . COLUMNS" .
124
-			"	WHERE TABLE_SCHEMA = ?" .
125
-			"	AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" .
126
-			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
127
-			array($dbName)
128
-		);
129
-		$rows = $statement->fetchAll();
130
-		$result = [];
131
-		foreach ($rows as $row) {
132
-			$result[$row['table']] = true;
133
-		}
134
-
135
-		// fetch tables by collation
136
-		$statement = $connection->executeQuery(
137
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
138
-			"	FROM INFORMATION_SCHEMA . TABLES" .
139
-			"	WHERE TABLE_SCHEMA = ?" .
140
-			"	AND TABLE_COLLATION <> '" . $characterSet . "_bin'" .
141
-			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
142
-			[$dbName]
143
-		);
144
-		$rows = $statement->fetchAll();
145
-		foreach ($rows as $row) {
146
-			$result[$row['table']] = true;
147
-		}
148
-
149
-		return array_keys($result);
150
-	}
36
+    /**  @var IConfig */
37
+    protected $config;
38
+
39
+    /** @var ILogger */
40
+    protected $logger;
41
+
42
+    /** @var IDBConnection */
43
+    protected $connection;
44
+
45
+    /** @var bool */
46
+    protected $ignoreFailures;
47
+
48
+    /**
49
+     * @param IConfig $config
50
+     * @param ILogger $logger
51
+     * @param IDBConnection $connection
52
+     * @param bool $ignoreFailures
53
+     */
54
+    public function __construct(IConfig $config, ILogger $logger, IDBConnection $connection, $ignoreFailures) {
55
+        $this->connection = $connection;
56
+        $this->config = $config;
57
+        $this->logger = $logger;
58
+        $this->ignoreFailures = $ignoreFailures;
59
+    }
60
+
61
+    public function getName() {
62
+        return 'Repair MySQL collation';
63
+    }
64
+
65
+    /**
66
+     * Fix mime types
67
+     */
68
+    public function run(IOutput $output) {
69
+        if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
70
+            $output->info('Not a mysql database -> nothing to do');
71
+            return;
72
+        }
73
+
74
+        $characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
75
+
76
+        $tables = $this->getAllNonUTF8BinTables($this->connection);
77
+        foreach ($tables as $table) {
78
+            $output->info("Change row format for $table ...");
79
+            $query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT = DYNAMIC;');
80
+            try {
81
+                $query->execute();
82
+            } catch (DriverException $e) {
83
+                // Just log this
84
+                $this->logger->logException($e);
85
+                if (!$this->ignoreFailures) {
86
+                    throw $e;
87
+                }
88
+            }
89
+
90
+            $output->info("Change collation for $table ...");
91
+            if ($characterSet === 'utf8mb4') {
92
+                // need to set row compression first
93
+                $query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT=COMPRESSED;');
94
+                $query->execute();
95
+            }
96
+            $query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $characterSet . '_bin;');
97
+            try {
98
+                $query->execute();
99
+            } catch (DriverException $e) {
100
+                // Just log this
101
+                $this->logger->logException($e);
102
+                if (!$this->ignoreFailures) {
103
+                    throw $e;
104
+                }
105
+            }
106
+        }
107
+        if (empty($tables)) {
108
+            $output->info('All tables already have the correct collation -> nothing to do');
109
+        }
110
+    }
111
+
112
+    /**
113
+     * @param IDBConnection $connection
114
+     * @return string[]
115
+     */
116
+    protected function getAllNonUTF8BinTables(IDBConnection $connection) {
117
+        $dbName = $this->config->getSystemValue("dbname");
118
+        $characterSet = $this->config->getSystemValue('mysql.utf8mb4', false) ? 'utf8mb4' : 'utf8';
119
+
120
+        // fetch tables by columns
121
+        $statement = $connection->executeQuery(
122
+            "SELECT DISTINCT(TABLE_NAME) AS `table`" .
123
+            "	FROM INFORMATION_SCHEMA . COLUMNS" .
124
+            "	WHERE TABLE_SCHEMA = ?" .
125
+            "	AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" .
126
+            "	AND TABLE_NAME LIKE \"*PREFIX*%\"",
127
+            array($dbName)
128
+        );
129
+        $rows = $statement->fetchAll();
130
+        $result = [];
131
+        foreach ($rows as $row) {
132
+            $result[$row['table']] = true;
133
+        }
134
+
135
+        // fetch tables by collation
136
+        $statement = $connection->executeQuery(
137
+            "SELECT DISTINCT(TABLE_NAME) AS `table`" .
138
+            "	FROM INFORMATION_SCHEMA . TABLES" .
139
+            "	WHERE TABLE_SCHEMA = ?" .
140
+            "	AND TABLE_COLLATION <> '" . $characterSet . "_bin'" .
141
+            "	AND TABLE_NAME LIKE \"*PREFIX*%\"",
142
+            [$dbName]
143
+        );
144
+        $rows = $statement->fetchAll();
145
+        foreach ($rows as $row) {
146
+            $result[$row['table']] = true;
147
+        }
148
+
149
+        return array_keys($result);
150
+    }
151 151
 }
152 152
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 		$tables = $this->getAllNonUTF8BinTables($this->connection);
77 77
 		foreach ($tables as $table) {
78 78
 			$output->info("Change row format for $table ...");
79
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT = DYNAMIC;');
79
+			$query = $this->connection->prepare('ALTER TABLE `'.$table.'` ROW_FORMAT = DYNAMIC;');
80 80
 			try {
81 81
 				$query->execute();
82 82
 			} catch (DriverException $e) {
@@ -90,10 +90,10 @@  discard block
 block discarded – undo
90 90
 			$output->info("Change collation for $table ...");
91 91
 			if ($characterSet === 'utf8mb4') {
92 92
 				// need to set row compression first
93
-				$query = $this->connection->prepare('ALTER TABLE `' . $table . '` ROW_FORMAT=COMPRESSED;');
93
+				$query = $this->connection->prepare('ALTER TABLE `'.$table.'` ROW_FORMAT=COMPRESSED;');
94 94
 				$query->execute();
95 95
 			}
96
-			$query = $this->connection->prepare('ALTER TABLE `' . $table . '` CONVERT TO CHARACTER SET ' . $characterSet . ' COLLATE ' . $characterSet . '_bin;');
96
+			$query = $this->connection->prepare('ALTER TABLE `'.$table.'` CONVERT TO CHARACTER SET '.$characterSet.' COLLATE '.$characterSet.'_bin;');
97 97
 			try {
98 98
 				$query->execute();
99 99
 			} catch (DriverException $e) {
@@ -119,10 +119,10 @@  discard block
 block discarded – undo
119 119
 
120 120
 		// fetch tables by columns
121 121
 		$statement = $connection->executeQuery(
122
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
123
-			"	FROM INFORMATION_SCHEMA . COLUMNS" .
124
-			"	WHERE TABLE_SCHEMA = ?" .
125
-			"	AND (COLLATION_NAME <> '" . $characterSet . "_bin' OR CHARACTER_SET_NAME <> '" . $characterSet . "')" .
122
+			"SELECT DISTINCT(TABLE_NAME) AS `table`".
123
+			"	FROM INFORMATION_SCHEMA . COLUMNS".
124
+			"	WHERE TABLE_SCHEMA = ?".
125
+			"	AND (COLLATION_NAME <> '".$characterSet."_bin' OR CHARACTER_SET_NAME <> '".$characterSet."')".
126 126
 			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
127 127
 			array($dbName)
128 128
 		);
@@ -134,10 +134,10 @@  discard block
 block discarded – undo
134 134
 
135 135
 		// fetch tables by collation
136 136
 		$statement = $connection->executeQuery(
137
-			"SELECT DISTINCT(TABLE_NAME) AS `table`" .
138
-			"	FROM INFORMATION_SCHEMA . TABLES" .
139
-			"	WHERE TABLE_SCHEMA = ?" .
140
-			"	AND TABLE_COLLATION <> '" . $characterSet . "_bin'" .
137
+			"SELECT DISTINCT(TABLE_NAME) AS `table`".
138
+			"	FROM INFORMATION_SCHEMA . TABLES".
139
+			"	WHERE TABLE_SCHEMA = ?".
140
+			"	AND TABLE_COLLATION <> '".$characterSet."_bin'".
141 141
 			"	AND TABLE_NAME LIKE \"*PREFIX*%\"",
142 142
 			[$dbName]
143 143
 		);
Please login to merge, or discard this patch.
lib/private/DB/MDB2SchemaManager.php 1 patch
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -37,136 +37,136 @@
 block discarded – undo
37 37
 use OCP\IDBConnection;
38 38
 
39 39
 class MDB2SchemaManager {
40
-	/** @var \OC\DB\Connection $conn */
41
-	protected $conn;
40
+    /** @var \OC\DB\Connection $conn */
41
+    protected $conn;
42 42
 
43
-	/**
44
-	 * @param IDBConnection $conn
45
-	 */
46
-	public function __construct($conn) {
47
-		$this->conn = $conn;
48
-	}
43
+    /**
44
+     * @param IDBConnection $conn
45
+     */
46
+    public function __construct($conn) {
47
+        $this->conn = $conn;
48
+    }
49 49
 
50
-	/**
51
-	 * saves database scheme to xml file
52
-	 * @param string $file name of file
53
-	 * @return bool
54
-	 *
55
-	 * TODO: write more documentation
56
-	 */
57
-	public function getDbStructure($file) {
58
-		return \OC\DB\MDB2SchemaWriter::saveSchemaToFile($file, $this->conn);
59
-	}
50
+    /**
51
+     * saves database scheme to xml file
52
+     * @param string $file name of file
53
+     * @return bool
54
+     *
55
+     * TODO: write more documentation
56
+     */
57
+    public function getDbStructure($file) {
58
+        return \OC\DB\MDB2SchemaWriter::saveSchemaToFile($file, $this->conn);
59
+    }
60 60
 
61
-	/**
62
-	 * Creates tables from XML file
63
-	 * @param string $file file to read structure from
64
-	 * @return bool
65
-	 *
66
-	 * TODO: write more documentation
67
-	 */
68
-	public function createDbFromStructure($file) {
69
-		$schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $this->conn->getDatabasePlatform());
70
-		$toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
71
-		$toSchema = $schemaReader->loadSchemaFromFile($file, $toSchema);
72
-		return $this->executeSchemaChange($toSchema);
73
-	}
61
+    /**
62
+     * Creates tables from XML file
63
+     * @param string $file file to read structure from
64
+     * @return bool
65
+     *
66
+     * TODO: write more documentation
67
+     */
68
+    public function createDbFromStructure($file) {
69
+        $schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $this->conn->getDatabasePlatform());
70
+        $toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
71
+        $toSchema = $schemaReader->loadSchemaFromFile($file, $toSchema);
72
+        return $this->executeSchemaChange($toSchema);
73
+    }
74 74
 
75
-	/**
76
-	 * @return \OC\DB\Migrator
77
-	 */
78
-	public function getMigrator() {
79
-		$random = \OC::$server->getSecureRandom();
80
-		$platform = $this->conn->getDatabasePlatform();
81
-		$config = \OC::$server->getConfig();
82
-		$dispatcher = \OC::$server->getEventDispatcher();
83
-		if ($platform instanceof SqlitePlatform) {
84
-			return new SQLiteMigrator($this->conn, $random, $config, $dispatcher);
85
-		} else if ($platform instanceof OraclePlatform) {
86
-			return new OracleMigrator($this->conn, $random, $config, $dispatcher);
87
-		} else if ($platform instanceof MySqlPlatform) {
88
-			return new MySQLMigrator($this->conn, $random, $config, $dispatcher);
89
-		} else if ($platform instanceof PostgreSqlPlatform) {
90
-			return new PostgreSqlMigrator($this->conn, $random, $config, $dispatcher);
91
-		} else {
92
-			return new NoCheckMigrator($this->conn, $random, $config, $dispatcher);
93
-		}
94
-	}
75
+    /**
76
+     * @return \OC\DB\Migrator
77
+     */
78
+    public function getMigrator() {
79
+        $random = \OC::$server->getSecureRandom();
80
+        $platform = $this->conn->getDatabasePlatform();
81
+        $config = \OC::$server->getConfig();
82
+        $dispatcher = \OC::$server->getEventDispatcher();
83
+        if ($platform instanceof SqlitePlatform) {
84
+            return new SQLiteMigrator($this->conn, $random, $config, $dispatcher);
85
+        } else if ($platform instanceof OraclePlatform) {
86
+            return new OracleMigrator($this->conn, $random, $config, $dispatcher);
87
+        } else if ($platform instanceof MySqlPlatform) {
88
+            return new MySQLMigrator($this->conn, $random, $config, $dispatcher);
89
+        } else if ($platform instanceof PostgreSqlPlatform) {
90
+            return new PostgreSqlMigrator($this->conn, $random, $config, $dispatcher);
91
+        } else {
92
+            return new NoCheckMigrator($this->conn, $random, $config, $dispatcher);
93
+        }
94
+    }
95 95
 
96
-	/**
97
-	 * Reads database schema from file
98
-	 *
99
-	 * @param string $file file to read from
100
-	 * @return \Doctrine\DBAL\Schema\Schema
101
-	 */
102
-	private function readSchemaFromFile($file) {
103
-		$platform = $this->conn->getDatabasePlatform();
104
-		$schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $platform);
105
-		$toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
106
-		return $schemaReader->loadSchemaFromFile($file, $toSchema);
107
-	}
96
+    /**
97
+     * Reads database schema from file
98
+     *
99
+     * @param string $file file to read from
100
+     * @return \Doctrine\DBAL\Schema\Schema
101
+     */
102
+    private function readSchemaFromFile($file) {
103
+        $platform = $this->conn->getDatabasePlatform();
104
+        $schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $platform);
105
+        $toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
106
+        return $schemaReader->loadSchemaFromFile($file, $toSchema);
107
+    }
108 108
 
109
-	/**
110
-	 * update the database scheme
111
-	 * @param string $file file to read structure from
112
-	 * @param bool $generateSql only return the sql needed for the upgrade
113
-	 * @return string|boolean
114
-	 */
115
-	public function updateDbFromStructure($file, $generateSql = false) {
116
-		$toSchema = $this->readSchemaFromFile($file);
117
-		$migrator = $this->getMigrator();
109
+    /**
110
+     * update the database scheme
111
+     * @param string $file file to read structure from
112
+     * @param bool $generateSql only return the sql needed for the upgrade
113
+     * @return string|boolean
114
+     */
115
+    public function updateDbFromStructure($file, $generateSql = false) {
116
+        $toSchema = $this->readSchemaFromFile($file);
117
+        $migrator = $this->getMigrator();
118 118
 
119
-		if ($generateSql) {
120
-			return $migrator->generateChangeScript($toSchema);
121
-		} else {
122
-			$migrator->migrate($toSchema);
123
-			return true;
124
-		}
125
-	}
119
+        if ($generateSql) {
120
+            return $migrator->generateChangeScript($toSchema);
121
+        } else {
122
+            $migrator->migrate($toSchema);
123
+            return true;
124
+        }
125
+    }
126 126
 
127
-	/**
128
-	 * @param \Doctrine\DBAL\Schema\Schema $schema
129
-	 * @return string
130
-	 */
131
-	public function generateChangeScript($schema) {
132
-		$migrator = $this->getMigrator();
133
-		return $migrator->generateChangeScript($schema);
134
-	}
127
+    /**
128
+     * @param \Doctrine\DBAL\Schema\Schema $schema
129
+     * @return string
130
+     */
131
+    public function generateChangeScript($schema) {
132
+        $migrator = $this->getMigrator();
133
+        return $migrator->generateChangeScript($schema);
134
+    }
135 135
 
136
-	/**
137
-	 * remove all tables defined in a database structure xml file
138
-	 *
139
-	 * @param string $file the xml file describing the tables
140
-	 */
141
-	public function removeDBStructure($file) {
142
-		$schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $this->conn->getDatabasePlatform());
143
-		$toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
144
-		$fromSchema = $schemaReader->loadSchemaFromFile($file, $toSchema);
145
-		$toSchema = clone $fromSchema;
146
-		/** @var $table \Doctrine\DBAL\Schema\Table */
147
-		foreach ($toSchema->getTables() as $table) {
148
-			$toSchema->dropTable($table->getName());
149
-		}
150
-		$comparator = new \Doctrine\DBAL\Schema\Comparator();
151
-		$schemaDiff = $comparator->compare($fromSchema, $toSchema);
152
-		$this->executeSchemaChange($schemaDiff);
153
-	}
136
+    /**
137
+     * remove all tables defined in a database structure xml file
138
+     *
139
+     * @param string $file the xml file describing the tables
140
+     */
141
+    public function removeDBStructure($file) {
142
+        $schemaReader = new MDB2SchemaReader(\OC::$server->getConfig(), $this->conn->getDatabasePlatform());
143
+        $toSchema = new Schema([], [], $this->conn->getSchemaManager()->createSchemaConfig());
144
+        $fromSchema = $schemaReader->loadSchemaFromFile($file, $toSchema);
145
+        $toSchema = clone $fromSchema;
146
+        /** @var $table \Doctrine\DBAL\Schema\Table */
147
+        foreach ($toSchema->getTables() as $table) {
148
+            $toSchema->dropTable($table->getName());
149
+        }
150
+        $comparator = new \Doctrine\DBAL\Schema\Comparator();
151
+        $schemaDiff = $comparator->compare($fromSchema, $toSchema);
152
+        $this->executeSchemaChange($schemaDiff);
153
+    }
154 154
 
155
-	/**
156
-	 * @param \Doctrine\DBAL\Schema\Schema|\Doctrine\DBAL\Schema\SchemaDiff $schema
157
-	 * @return bool
158
-	 */
159
-	private function executeSchemaChange($schema) {
160
-		$this->conn->beginTransaction();
161
-		foreach ($schema->toSql($this->conn->getDatabasePlatform()) as $sql) {
162
-			$this->conn->query($sql);
163
-		}
164
-		$this->conn->commit();
155
+    /**
156
+     * @param \Doctrine\DBAL\Schema\Schema|\Doctrine\DBAL\Schema\SchemaDiff $schema
157
+     * @return bool
158
+     */
159
+    private function executeSchemaChange($schema) {
160
+        $this->conn->beginTransaction();
161
+        foreach ($schema->toSql($this->conn->getDatabasePlatform()) as $sql) {
162
+            $this->conn->query($sql);
163
+        }
164
+        $this->conn->commit();
165 165
 
166
-		if ($this->conn->getDatabasePlatform() instanceof SqlitePlatform) {
167
-			$this->conn->close();
168
-			$this->conn->connect();
169
-		}
170
-		return true;
171
-	}
166
+        if ($this->conn->getDatabasePlatform() instanceof SqlitePlatform) {
167
+            $this->conn->close();
168
+            $this->conn->connect();
169
+        }
170
+        return true;
171
+    }
172 172
 }
Please login to merge, or discard this patch.
lib/private/DB/ConnectionFactory.php 2 patches
Indentation   +182 added lines, -182 removed lines patch added patch discarded remove patch
@@ -36,186 +36,186 @@
 block discarded – undo
36 36
 * Takes care of creating and configuring Doctrine connections.
37 37
 */
38 38
 class ConnectionFactory {
39
-	/**
40
-	* @var array
41
-	*
42
-	* Array mapping DBMS type to default connection parameters passed to
43
-	* \Doctrine\DBAL\DriverManager::getConnection().
44
-	*/
45
-	protected $defaultConnectionParams = [
46
-		'mysql' => [
47
-			'adapter' => '\OC\DB\AdapterMySQL',
48
-			'charset' => 'UTF8',
49
-			'driver' => 'pdo_mysql',
50
-			'wrapperClass' => 'OC\DB\Connection',
51
-		],
52
-		'oci' => [
53
-			'adapter' => '\OC\DB\AdapterOCI8',
54
-			'charset' => 'AL32UTF8',
55
-			'driver' => 'oci8',
56
-			'wrapperClass' => 'OC\DB\OracleConnection',
57
-		],
58
-		'pgsql' => [
59
-			'adapter' => '\OC\DB\AdapterPgSql',
60
-			'driver' => 'pdo_pgsql',
61
-			'wrapperClass' => 'OC\DB\Connection',
62
-		],
63
-		'sqlite3' => [
64
-			'adapter' => '\OC\DB\AdapterSqlite',
65
-			'driver' => 'pdo_sqlite',
66
-			'wrapperClass' => 'OC\DB\Connection',
67
-		],
68
-	];
69
-
70
-	/** @var SystemConfig */
71
-	private $config;
72
-
73
-	/**
74
-	 * ConnectionFactory constructor.
75
-	 *
76
-	 * @param SystemConfig $systemConfig
77
-	 */
78
-	public function __construct(SystemConfig $systemConfig) {
79
-		$this->config = $systemConfig;
80
-		if($this->config->getValue('mysql.utf8mb4', false)) {
81
-			$this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
82
-		}
83
-	}
84
-
85
-	/**
86
-	* @brief Get default connection parameters for a given DBMS.
87
-	* @param string $type DBMS type
88
-	* @throws \InvalidArgumentException If $type is invalid
89
-	* @return array Default connection parameters.
90
-	*/
91
-	public function getDefaultConnectionParams($type) {
92
-		$normalizedType = $this->normalizeType($type);
93
-		if (!isset($this->defaultConnectionParams[$normalizedType])) {
94
-			throw new \InvalidArgumentException("Unsupported type: $type");
95
-		}
96
-		$result = $this->defaultConnectionParams[$normalizedType];
97
-		// \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
98
-		// driver is missing. In this case, we won't be able to connect anyway.
99
-		if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
100
-			$result['driverOptions'] = array(
101
-				\PDO::MYSQL_ATTR_FOUND_ROWS => true,
102
-			);
103
-		}
104
-		return $result;
105
-	}
106
-
107
-	/**
108
-	* @brief Get default connection parameters for a given DBMS.
109
-	* @param string $type DBMS type
110
-	* @param array $additionalConnectionParams Additional connection parameters
111
-	* @return \OC\DB\Connection
112
-	*/
113
-	public function getConnection($type, $additionalConnectionParams) {
114
-		$normalizedType = $this->normalizeType($type);
115
-		$eventManager = new EventManager();
116
-		switch ($normalizedType) {
117
-			case 'mysql':
118
-				$eventManager->addEventSubscriber(
119
-					new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
120
-				break;
121
-			case 'oci':
122
-				$eventManager->addEventSubscriber(new OracleSessionInit);
123
-				// the driverOptions are unused in dbal and need to be mapped to the parameters
124
-				if (isset($additionalConnectionParams['driverOptions'])) {
125
-					$additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
126
-				}
127
-				break;
128
-			case 'sqlite3':
129
-				$journalMode = $additionalConnectionParams['sqlite.journal_mode'];
130
-				$additionalConnectionParams['platform'] = new OCSqlitePlatform();
131
-				$eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
132
-				break;
133
-		}
134
-		/** @var Connection $connection */
135
-		$connection = DriverManager::getConnection(
136
-			array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
137
-			new Configuration(),
138
-			$eventManager
139
-		);
140
-		return $connection;
141
-	}
142
-
143
-	/**
144
-	* @brief Normalize DBMS type
145
-	* @param string $type DBMS type
146
-	* @return string Normalized DBMS type
147
-	*/
148
-	public function normalizeType($type) {
149
-		return $type === 'sqlite' ? 'sqlite3' : $type;
150
-	}
151
-
152
-	/**
153
-	 * Checks whether the specified DBMS type is valid.
154
-	 *
155
-	 * @param string $type
156
-	 * @return bool
157
-	 */
158
-	public function isValidType($type) {
159
-		$normalizedType = $this->normalizeType($type);
160
-		return isset($this->defaultConnectionParams[$normalizedType]);
161
-	}
162
-
163
-	/**
164
-	 * Create the connection parameters for the config
165
-	 *
166
-	 * @return array
167
-	 */
168
-	public function createConnectionParams() {
169
-		$type = $this->config->getValue('dbtype', 'sqlite');
170
-
171
-		$connectionParams = [
172
-			'user' => $this->config->getValue('dbuser', ''),
173
-			'password' => $this->config->getValue('dbpassword', ''),
174
-		];
175
-		$name = $this->config->getValue('dbname', 'owncloud');
176
-
177
-		if ($this->normalizeType($type) === 'sqlite3') {
178
-			$dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
179
-			$connectionParams['path'] = $dataDir . '/' . $name . '.db';
180
-		} else {
181
-			$host = $this->config->getValue('dbhost', '');
182
-			if (strpos($host, ':')) {
183
-				// Host variable may carry a port or socket.
184
-				list($host, $portOrSocket) = explode(':', $host, 2);
185
-				if (ctype_digit($portOrSocket)) {
186
-					$connectionParams['port'] = $portOrSocket;
187
-				} else {
188
-					$connectionParams['unix_socket'] = $portOrSocket;
189
-				}
190
-			}
191
-			$connectionParams['host'] = $host;
192
-			$connectionParams['dbname'] = $name;
193
-		}
194
-
195
-		$connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', 'oc_');
196
-		$connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
197
-
198
-		//additional driver options, eg. for mysql ssl
199
-		$driverOptions = $this->config->getValue('dbdriveroptions', null);
200
-		if ($driverOptions) {
201
-			$connectionParams['driverOptions'] = $driverOptions;
202
-		}
203
-
204
-		// set default table creation options
205
-		$connectionParams['defaultTableOptions'] = [
206
-			'collate' => 'utf8_bin',
207
-			'tablePrefix' => $connectionParams['tablePrefix']
208
-		];
209
-
210
-		if($this->config->getValue('mysql.utf8mb4', false)) {
211
-			$connectionParams['defaultTableOptions'] = [
212
-				'collate' => 'utf8mb4_bin',
213
-				'charset' => 'utf8mb4',
214
-				'row_format' => 'compressed',
215
-				'tablePrefix' => $connectionParams['tablePrefix']
216
-			];
217
-		}
218
-
219
-		return $connectionParams;
220
-	}
39
+    /**
40
+     * @var array
41
+     *
42
+     * Array mapping DBMS type to default connection parameters passed to
43
+     * \Doctrine\DBAL\DriverManager::getConnection().
44
+     */
45
+    protected $defaultConnectionParams = [
46
+        'mysql' => [
47
+            'adapter' => '\OC\DB\AdapterMySQL',
48
+            'charset' => 'UTF8',
49
+            'driver' => 'pdo_mysql',
50
+            'wrapperClass' => 'OC\DB\Connection',
51
+        ],
52
+        'oci' => [
53
+            'adapter' => '\OC\DB\AdapterOCI8',
54
+            'charset' => 'AL32UTF8',
55
+            'driver' => 'oci8',
56
+            'wrapperClass' => 'OC\DB\OracleConnection',
57
+        ],
58
+        'pgsql' => [
59
+            'adapter' => '\OC\DB\AdapterPgSql',
60
+            'driver' => 'pdo_pgsql',
61
+            'wrapperClass' => 'OC\DB\Connection',
62
+        ],
63
+        'sqlite3' => [
64
+            'adapter' => '\OC\DB\AdapterSqlite',
65
+            'driver' => 'pdo_sqlite',
66
+            'wrapperClass' => 'OC\DB\Connection',
67
+        ],
68
+    ];
69
+
70
+    /** @var SystemConfig */
71
+    private $config;
72
+
73
+    /**
74
+     * ConnectionFactory constructor.
75
+     *
76
+     * @param SystemConfig $systemConfig
77
+     */
78
+    public function __construct(SystemConfig $systemConfig) {
79
+        $this->config = $systemConfig;
80
+        if($this->config->getValue('mysql.utf8mb4', false)) {
81
+            $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
82
+        }
83
+    }
84
+
85
+    /**
86
+     * @brief Get default connection parameters for a given DBMS.
87
+     * @param string $type DBMS type
88
+     * @throws \InvalidArgumentException If $type is invalid
89
+     * @return array Default connection parameters.
90
+     */
91
+    public function getDefaultConnectionParams($type) {
92
+        $normalizedType = $this->normalizeType($type);
93
+        if (!isset($this->defaultConnectionParams[$normalizedType])) {
94
+            throw new \InvalidArgumentException("Unsupported type: $type");
95
+        }
96
+        $result = $this->defaultConnectionParams[$normalizedType];
97
+        // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
98
+        // driver is missing. In this case, we won't be able to connect anyway.
99
+        if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
100
+            $result['driverOptions'] = array(
101
+                \PDO::MYSQL_ATTR_FOUND_ROWS => true,
102
+            );
103
+        }
104
+        return $result;
105
+    }
106
+
107
+    /**
108
+     * @brief Get default connection parameters for a given DBMS.
109
+     * @param string $type DBMS type
110
+     * @param array $additionalConnectionParams Additional connection parameters
111
+     * @return \OC\DB\Connection
112
+     */
113
+    public function getConnection($type, $additionalConnectionParams) {
114
+        $normalizedType = $this->normalizeType($type);
115
+        $eventManager = new EventManager();
116
+        switch ($normalizedType) {
117
+            case 'mysql':
118
+                $eventManager->addEventSubscriber(
119
+                    new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
120
+                break;
121
+            case 'oci':
122
+                $eventManager->addEventSubscriber(new OracleSessionInit);
123
+                // the driverOptions are unused in dbal and need to be mapped to the parameters
124
+                if (isset($additionalConnectionParams['driverOptions'])) {
125
+                    $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
126
+                }
127
+                break;
128
+            case 'sqlite3':
129
+                $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
130
+                $additionalConnectionParams['platform'] = new OCSqlitePlatform();
131
+                $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
132
+                break;
133
+        }
134
+        /** @var Connection $connection */
135
+        $connection = DriverManager::getConnection(
136
+            array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
137
+            new Configuration(),
138
+            $eventManager
139
+        );
140
+        return $connection;
141
+    }
142
+
143
+    /**
144
+     * @brief Normalize DBMS type
145
+     * @param string $type DBMS type
146
+     * @return string Normalized DBMS type
147
+     */
148
+    public function normalizeType($type) {
149
+        return $type === 'sqlite' ? 'sqlite3' : $type;
150
+    }
151
+
152
+    /**
153
+     * Checks whether the specified DBMS type is valid.
154
+     *
155
+     * @param string $type
156
+     * @return bool
157
+     */
158
+    public function isValidType($type) {
159
+        $normalizedType = $this->normalizeType($type);
160
+        return isset($this->defaultConnectionParams[$normalizedType]);
161
+    }
162
+
163
+    /**
164
+     * Create the connection parameters for the config
165
+     *
166
+     * @return array
167
+     */
168
+    public function createConnectionParams() {
169
+        $type = $this->config->getValue('dbtype', 'sqlite');
170
+
171
+        $connectionParams = [
172
+            'user' => $this->config->getValue('dbuser', ''),
173
+            'password' => $this->config->getValue('dbpassword', ''),
174
+        ];
175
+        $name = $this->config->getValue('dbname', 'owncloud');
176
+
177
+        if ($this->normalizeType($type) === 'sqlite3') {
178
+            $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
179
+            $connectionParams['path'] = $dataDir . '/' . $name . '.db';
180
+        } else {
181
+            $host = $this->config->getValue('dbhost', '');
182
+            if (strpos($host, ':')) {
183
+                // Host variable may carry a port or socket.
184
+                list($host, $portOrSocket) = explode(':', $host, 2);
185
+                if (ctype_digit($portOrSocket)) {
186
+                    $connectionParams['port'] = $portOrSocket;
187
+                } else {
188
+                    $connectionParams['unix_socket'] = $portOrSocket;
189
+                }
190
+            }
191
+            $connectionParams['host'] = $host;
192
+            $connectionParams['dbname'] = $name;
193
+        }
194
+
195
+        $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', 'oc_');
196
+        $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
197
+
198
+        //additional driver options, eg. for mysql ssl
199
+        $driverOptions = $this->config->getValue('dbdriveroptions', null);
200
+        if ($driverOptions) {
201
+            $connectionParams['driverOptions'] = $driverOptions;
202
+        }
203
+
204
+        // set default table creation options
205
+        $connectionParams['defaultTableOptions'] = [
206
+            'collate' => 'utf8_bin',
207
+            'tablePrefix' => $connectionParams['tablePrefix']
208
+        ];
209
+
210
+        if($this->config->getValue('mysql.utf8mb4', false)) {
211
+            $connectionParams['defaultTableOptions'] = [
212
+                'collate' => 'utf8mb4_bin',
213
+                'charset' => 'utf8mb4',
214
+                'row_format' => 'compressed',
215
+                'tablePrefix' => $connectionParams['tablePrefix']
216
+            ];
217
+        }
218
+
219
+        return $connectionParams;
220
+    }
221 221
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 	 */
78 78
 	public function __construct(SystemConfig $systemConfig) {
79 79
 		$this->config = $systemConfig;
80
-		if($this->config->getValue('mysql.utf8mb4', false)) {
80
+		if ($this->config->getValue('mysql.utf8mb4', false)) {
81 81
 			$this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
82 82
 		}
83 83
 	}
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
 		$name = $this->config->getValue('dbname', 'owncloud');
176 176
 
177 177
 		if ($this->normalizeType($type) === 'sqlite3') {
178
-			$dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
179
-			$connectionParams['path'] = $dataDir . '/' . $name . '.db';
178
+			$dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT.'/data');
179
+			$connectionParams['path'] = $dataDir.'/'.$name.'.db';
180 180
 		} else {
181 181
 			$host = $this->config->getValue('dbhost', '');
182 182
 			if (strpos($host, ':')) {
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 			'tablePrefix' => $connectionParams['tablePrefix']
208 208
 		];
209 209
 
210
-		if($this->config->getValue('mysql.utf8mb4', false)) {
210
+		if ($this->config->getValue('mysql.utf8mb4', false)) {
211 211
 			$connectionParams['defaultTableOptions'] = [
212 212
 				'collate' => 'utf8mb4_bin',
213 213
 				'charset' => 'utf8mb4',
Please login to merge, or discard this patch.
core/register_command.php 1 patch
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -40,115 +40,115 @@
 block discarded – undo
40 40
 $application->add(new OC\Core\Command\App\CheckCode($infoParser));
41 41
 $application->add(new OC\Core\Command\L10n\CreateJs());
42 42
 $application->add(new \OC\Core\Command\Integrity\SignApp(
43
-		\OC::$server->getIntegrityCodeChecker(),
44
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
45
-		\OC::$server->getURLGenerator()
43
+        \OC::$server->getIntegrityCodeChecker(),
44
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper(),
45
+        \OC::$server->getURLGenerator()
46 46
 ));
47 47
 $application->add(new \OC\Core\Command\Integrity\SignCore(
48
-		\OC::$server->getIntegrityCodeChecker(),
49
-		new \OC\IntegrityCheck\Helpers\FileAccessHelper()
48
+        \OC::$server->getIntegrityCodeChecker(),
49
+        new \OC\IntegrityCheck\Helpers\FileAccessHelper()
50 50
 ));
51 51
 $application->add(new \OC\Core\Command\Integrity\CheckApp(
52
-		\OC::$server->getIntegrityCodeChecker()
52
+        \OC::$server->getIntegrityCodeChecker()
53 53
 ));
54 54
 $application->add(new \OC\Core\Command\Integrity\CheckCore(
55
-		\OC::$server->getIntegrityCodeChecker()
55
+        \OC::$server->getIntegrityCodeChecker()
56 56
 ));
57 57
 
58 58
 
59 59
 if (\OC::$server->getConfig()->getSystemValue('installed', false)) {
60
-	$application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
61
-	$application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
62
-	$application->add(new OC\Core\Command\App\GetPath());
63
-	$application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
60
+    $application->add(new OC\Core\Command\App\Disable(\OC::$server->getAppManager()));
61
+    $application->add(new OC\Core\Command\App\Enable(\OC::$server->getAppManager()));
62
+    $application->add(new OC\Core\Command\App\GetPath());
63
+    $application->add(new OC\Core\Command\App\ListApps(\OC::$server->getAppManager()));
64 64
 	
65
-	$application->add(new OC\Core\Command\TwoFactorAuth\Enable(
66
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
67
-	));
68
-	$application->add(new OC\Core\Command\TwoFactorAuth\Disable(
69
-		\OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
70
-	));
65
+    $application->add(new OC\Core\Command\TwoFactorAuth\Enable(
66
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
67
+    ));
68
+    $application->add(new OC\Core\Command\TwoFactorAuth\Disable(
69
+        \OC::$server->getTwoFactorAuthManager(), \OC::$server->getUserManager()
70
+    ));
71 71
 
72
-	$application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
73
-	$application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
74
-	$application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
72
+    $application->add(new OC\Core\Command\Background\Cron(\OC::$server->getConfig()));
73
+    $application->add(new OC\Core\Command\Background\WebCron(\OC::$server->getConfig()));
74
+    $application->add(new OC\Core\Command\Background\Ajax(\OC::$server->getConfig()));
75 75
 
76
-	$application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
77
-	$application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
78
-	$application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
79
-	$application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
80
-	$application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
81
-	$application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
82
-	$application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
83
-	$application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
76
+    $application->add(new OC\Core\Command\Config\App\DeleteConfig(\OC::$server->getConfig()));
77
+    $application->add(new OC\Core\Command\Config\App\GetConfig(\OC::$server->getConfig()));
78
+    $application->add(new OC\Core\Command\Config\App\SetConfig(\OC::$server->getConfig()));
79
+    $application->add(new OC\Core\Command\Config\Import(\OC::$server->getConfig()));
80
+    $application->add(new OC\Core\Command\Config\ListConfigs(\OC::$server->getSystemConfig(), \OC::$server->getAppConfig()));
81
+    $application->add(new OC\Core\Command\Config\System\DeleteConfig(\OC::$server->getSystemConfig()));
82
+    $application->add(new OC\Core\Command\Config\System\GetConfig(\OC::$server->getSystemConfig()));
83
+    $application->add(new OC\Core\Command\Config\System\SetConfig(\OC::$server->getSystemConfig()));
84 84
 
85
-	$application->add(new OC\Core\Command\Db\GenerateChangeScript());
86
-	$application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
87
-	$application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
85
+    $application->add(new OC\Core\Command\Db\GenerateChangeScript());
86
+    $application->add(new OC\Core\Command\Db\ConvertType(\OC::$server->getConfig(), new \OC\DB\ConnectionFactory(\OC::$server->getSystemConfig())));
87
+    $application->add(new OC\Core\Command\Db\ConvertMysqlToMB4(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection(), \OC::$server->getURLGenerator(), \OC::$server->getLogger()));
88 88
 
89
-	$application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
90
-	$application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
91
-	$application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
92
-	$application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
93
-	$application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
94
-	$application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
95
-	$application->add(new OC\Core\Command\Encryption\DecryptAll(
96
-		\OC::$server->getEncryptionManager(),
97
-		\OC::$server->getAppManager(),
98
-		\OC::$server->getConfig(),
99
-		new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
100
-		new \Symfony\Component\Console\Helper\QuestionHelper())
101
-	);
89
+    $application->add(new OC\Core\Command\Encryption\Disable(\OC::$server->getConfig()));
90
+    $application->add(new OC\Core\Command\Encryption\Enable(\OC::$server->getConfig(), \OC::$server->getEncryptionManager()));
91
+    $application->add(new OC\Core\Command\Encryption\ListModules(\OC::$server->getEncryptionManager()));
92
+    $application->add(new OC\Core\Command\Encryption\SetDefaultModule(\OC::$server->getEncryptionManager()));
93
+    $application->add(new OC\Core\Command\Encryption\Status(\OC::$server->getEncryptionManager()));
94
+    $application->add(new OC\Core\Command\Encryption\EncryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getAppManager(), \OC::$server->getConfig(), new \Symfony\Component\Console\Helper\QuestionHelper()));
95
+    $application->add(new OC\Core\Command\Encryption\DecryptAll(
96
+        \OC::$server->getEncryptionManager(),
97
+        \OC::$server->getAppManager(),
98
+        \OC::$server->getConfig(),
99
+        new \OC\Encryption\DecryptAll(\OC::$server->getEncryptionManager(), \OC::$server->getUserManager(), new \OC\Files\View()),
100
+        new \Symfony\Component\Console\Helper\QuestionHelper())
101
+    );
102 102
 
103
-	$application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
104
-	$application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
103
+    $application->add(new OC\Core\Command\Log\Manage(\OC::$server->getConfig()));
104
+    $application->add(new OC\Core\Command\Log\File(\OC::$server->getConfig()));
105 105
 
106
-	$view = new \OC\Files\View();
107
-	$util = new \OC\Encryption\Util(
108
-		$view,
109
-		\OC::$server->getUserManager(),
110
-		\OC::$server->getGroupManager(),
111
-		\OC::$server->getConfig()
112
-	);
113
-	$application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
114
-			$view,
115
-			\OC::$server->getUserManager(),
116
-			\OC::$server->getConfig(),
117
-			$util,
118
-			new \Symfony\Component\Console\Helper\QuestionHelper()
119
-		)
120
-	);
121
-	$application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
106
+    $view = new \OC\Files\View();
107
+    $util = new \OC\Encryption\Util(
108
+        $view,
109
+        \OC::$server->getUserManager(),
110
+        \OC::$server->getGroupManager(),
111
+        \OC::$server->getConfig()
112
+    );
113
+    $application->add(new OC\Core\Command\Encryption\ChangeKeyStorageRoot(
114
+            $view,
115
+            \OC::$server->getUserManager(),
116
+            \OC::$server->getConfig(),
117
+            $util,
118
+            new \Symfony\Component\Console\Helper\QuestionHelper()
119
+        )
120
+    );
121
+    $application->add(new OC\Core\Command\Encryption\ShowKeyStorageRoot($util));
122 122
 
123
-	$application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
124
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
125
-	$application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
126
-	$application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
127
-	$application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
123
+    $application->add(new OC\Core\Command\Maintenance\DataFingerprint(\OC::$server->getConfig(), new \OC\AppFramework\Utility\TimeFactory()));
124
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateDB(\OC::$server->getMimeTypeDetector(), \OC::$server->getMimeTypeLoader()));
125
+    $application->add(new OC\Core\Command\Maintenance\Mimetype\UpdateJS(\OC::$server->getMimeTypeDetector()));
126
+    $application->add(new OC\Core\Command\Maintenance\Mode(\OC::$server->getConfig()));
127
+    $application->add(new OC\Core\Command\Maintenance\UpdateHtaccess());
128 128
 
129
-	$application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger()));
130
-	$application->add(new OC\Core\Command\Maintenance\Repair(
131
-		new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
132
-		\OC::$server->getEventDispatcher()));
129
+    $application->add(new OC\Core\Command\Upgrade(\OC::$server->getConfig(), \OC::$server->getLogger()));
130
+    $application->add(new OC\Core\Command\Maintenance\Repair(
131
+        new \OC\Repair(\OC\Repair::getRepairSteps(), \OC::$server->getEventDispatcher()), \OC::$server->getConfig(),
132
+        \OC::$server->getEventDispatcher()));
133 133
 
134
-	$application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
135
-	$application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
136
-	$application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
137
-	$application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
138
-	$application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
139
-	$application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
140
-	$application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
141
-	$application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
142
-	$application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
143
-	$application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
134
+    $application->add(new OC\Core\Command\User\Add(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
135
+    $application->add(new OC\Core\Command\User\Delete(\OC::$server->getUserManager()));
136
+    $application->add(new OC\Core\Command\User\Disable(\OC::$server->getUserManager()));
137
+    $application->add(new OC\Core\Command\User\Enable(\OC::$server->getUserManager()));
138
+    $application->add(new OC\Core\Command\User\LastSeen(\OC::$server->getUserManager()));
139
+    $application->add(new OC\Core\Command\User\Report(\OC::$server->getUserManager()));
140
+    $application->add(new OC\Core\Command\User\ResetPassword(\OC::$server->getUserManager()));
141
+    $application->add(new OC\Core\Command\User\Setting(\OC::$server->getUserManager(), \OC::$server->getConfig(), \OC::$server->getDatabaseConnection()));
142
+    $application->add(new OC\Core\Command\User\ListCommand(\OC::$server->getUserManager()));
143
+    $application->add(new OC\Core\Command\User\Info(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
144 144
 
145
-	$application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
146
-	$application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
147
-	$application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
145
+    $application->add(new OC\Core\Command\Group\ListCommand(\OC::$server->getGroupManager()));
146
+    $application->add(new OC\Core\Command\Group\AddUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
147
+    $application->add(new OC\Core\Command\Group\RemoveUser(\OC::$server->getUserManager(), \OC::$server->getGroupManager()));
148 148
 
149
-	$application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
150
-	$application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
151
-	$application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
149
+    $application->add(new OC\Core\Command\Security\ListCertificates(\OC::$server->getCertificateManager(null), \OC::$server->getL10N('core')));
150
+    $application->add(new OC\Core\Command\Security\ImportCertificate(\OC::$server->getCertificateManager(null)));
151
+    $application->add(new OC\Core\Command\Security\RemoveCertificate(\OC::$server->getCertificateManager(null)));
152 152
 } else {
153
-	$application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
153
+    $application->add(new OC\Core\Command\Maintenance\Install(\OC::$server->getSystemConfig()));
154 154
 }
Please login to merge, or discard this patch.
core/Command/Db/ConvertMysqlToMB4.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -33,60 +33,60 @@
 block discarded – undo
33 33
 use Symfony\Component\Console\Output\OutputInterface;
34 34
 
35 35
 class ConvertMysqlToMB4 extends Command {
36
-	/** @var IConfig */
37
-	private $config;
36
+    /** @var IConfig */
37
+    private $config;
38 38
 
39
-	/** @var IDBConnection */
40
-	private $connection;
39
+    /** @var IDBConnection */
40
+    private $connection;
41 41
 
42
-	/** @var IURLGenerator */
43
-	private $urlGenerator;
42
+    /** @var IURLGenerator */
43
+    private $urlGenerator;
44 44
 
45
-	/** @var ILogger */
46
-	private $logger;
45
+    /** @var ILogger */
46
+    private $logger;
47 47
 
48
-	/**
49
-	 * @param IConfig $config
50
-	 * @param IDBConnection $connection
51
-	 * @param IURLGenerator $urlGenerator
52
-	 * @param ILogger $logger
53
-	 */
54
-	public function __construct(IConfig $config, IDBConnection $connection, IURLGenerator $urlGenerator, ILogger $logger) {
55
-		$this->config = $config;
56
-		$this->connection = $connection;
57
-		$this->urlGenerator = $urlGenerator;
58
-		$this->logger = $logger;
59
-		parent::__construct();
60
-	}
48
+    /**
49
+     * @param IConfig $config
50
+     * @param IDBConnection $connection
51
+     * @param IURLGenerator $urlGenerator
52
+     * @param ILogger $logger
53
+     */
54
+    public function __construct(IConfig $config, IDBConnection $connection, IURLGenerator $urlGenerator, ILogger $logger) {
55
+        $this->config = $config;
56
+        $this->connection = $connection;
57
+        $this->urlGenerator = $urlGenerator;
58
+        $this->logger = $logger;
59
+        parent::__construct();
60
+    }
61 61
 
62
-	protected function configure() {
63
-		$this
64
-			->setName('db:convert-mysql-charset')
65
-			->setDescription('Convert charset of MySQL/MariaDB to use utf8mb4');
66
-	}
62
+    protected function configure() {
63
+        $this
64
+            ->setName('db:convert-mysql-charset')
65
+            ->setDescription('Convert charset of MySQL/MariaDB to use utf8mb4');
66
+    }
67 67
 
68
-	protected function execute(InputInterface $input, OutputInterface $output) {
69
-		if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
70
-			$output->writeln("This command is only valid for MySQL/MariaDB databases.");
71
-			return 1;
72
-		}
68
+    protected function execute(InputInterface $input, OutputInterface $output) {
69
+        if (!$this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
70
+            $output->writeln("This command is only valid for MySQL/MariaDB databases.");
71
+            return 1;
72
+        }
73 73
 
74
-		$oldValue = $this->config->getSystemValue('mysql.utf8mb4', false);
75
-		// enable charset
76
-		$this->config->setSystemValue('mysql.utf8mb4', true);
74
+        $oldValue = $this->config->getSystemValue('mysql.utf8mb4', false);
75
+        // enable charset
76
+        $this->config->setSystemValue('mysql.utf8mb4', true);
77 77
 
78
-		if (!$this->connection->supports4ByteText()) {
79
-			$url = $this->urlGenerator->linkToDocs('admin-mysql-utf8mb4');
80
-			$output->writeln("The database is not properly setup to use the charset utf8mb4.");
81
-			$output->writeln("For more information please read the documentation at $url");
82
-			$this->config->setSystemValue('mysql.utf8mb4', $oldValue);
83
-			return 1;
84
-		}
78
+        if (!$this->connection->supports4ByteText()) {
79
+            $url = $this->urlGenerator->linkToDocs('admin-mysql-utf8mb4');
80
+            $output->writeln("The database is not properly setup to use the charset utf8mb4.");
81
+            $output->writeln("For more information please read the documentation at $url");
82
+            $this->config->setSystemValue('mysql.utf8mb4', $oldValue);
83
+            return 1;
84
+        }
85 85
 
86
-		// run conversion
87
-		$coll = new Collation($this->config, $this->logger, $this->connection, false);
88
-		$coll->run(new ConsoleOutput($output));
86
+        // run conversion
87
+        $coll = new Collation($this->config, $this->logger, $this->connection, false);
88
+        $coll->run(new ConsoleOutput($output));
89 89
 
90
-		return 0;
91
-	}
90
+        return 0;
91
+    }
92 92
 }
Please login to merge, or discard this patch.