Completed
Pull Request — master (#6563)
by Joas
14:47
created
lib/public/Migration/BigIntMigration.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -29,38 +29,38 @@
 block discarded – undo
29 29
  */
30 30
 abstract class BigIntMigration extends SimpleMigrationStep {
31 31
 
32
-	/**
33
-	 * @return array Returns an array with the following structure
34
-	 * ['table1' => ['column1', 'column2'], ...]
35
-	 * @since 13.0.0
36
-	 */
37
-	abstract protected function getColumnsByTable();
32
+    /**
33
+     * @return array Returns an array with the following structure
34
+     * ['table1' => ['column1', 'column2'], ...]
35
+     * @since 13.0.0
36
+     */
37
+    abstract protected function getColumnsByTable();
38 38
 
39
-	/**
40
-	 * @param IOutput $output
41
-	 * @param \Closure $schemaClosure The `\Closure` returns a `Schema`
42
-	 * @param array $options
43
-	 * @return null|Schema
44
-	 * @since 13.0.0
45
-	 */
46
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
47
-		/** @var Schema $schema */
48
-		$schema = $schemaClosure();
39
+    /**
40
+     * @param IOutput $output
41
+     * @param \Closure $schemaClosure The `\Closure` returns a `Schema`
42
+     * @param array $options
43
+     * @return null|Schema
44
+     * @since 13.0.0
45
+     */
46
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
47
+        /** @var Schema $schema */
48
+        $schema = $schemaClosure();
49 49
 
50
-		$tables = $this->getColumnsByTable();
50
+        $tables = $this->getColumnsByTable();
51 51
 
52
-		foreach ($tables as $tableName => $columns) {
53
-			$table = $schema->getTable($tableName);
52
+        foreach ($tables as $tableName => $columns) {
53
+            $table = $schema->getTable($tableName);
54 54
 
55
-			foreach ($columns as $columnName) {
56
-				$column = $table->getColumn($columnName);
57
-				if ($column->getType()->getName() !== Type::BIGINT) {
58
-					$column->setType(Type::getType(Type::BIGINT));
59
-					$column->setOptions(['length' => 20]);
60
-				}
61
-			}
62
-		}
55
+            foreach ($columns as $columnName) {
56
+                $column = $table->getColumn($columnName);
57
+                if ($column->getType()->getName() !== Type::BIGINT) {
58
+                    $column->setType(Type::getType(Type::BIGINT));
59
+                    $column->setOptions(['length' => 20]);
60
+                }
61
+            }
62
+        }
63 63
 
64
-		return $schema;
65
-	}
64
+        return $schema;
65
+    }
66 66
 }
Please login to merge, or discard this patch.
core/Migrations/Version13000Date20170926101637.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -11,32 +11,32 @@
 block discarded – undo
11 11
  */
12 12
 class Version13000Date20170926101637 extends BigIntMigration {
13 13
 
14
-	/**
15
-	 * @return array Returns an array with the following structure
16
-	 * ['table1' => ['column1', 'column2'], ...]
17
-	 * @since 13.0.0
18
-	 */
19
-	protected function getColumnsByTable() {
20
-		return [
21
-			'admin_settings' => ['id'],
22
-			'authtoken' => ['id'],
23
-			'bruteforce_attempts' => ['id'],
24
-			'comments' => ['id', 'parent_id', 'topmost_parent_id'],
25
-			'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart'],
26
-			'file_locks' => ['id'],
27
-			'jobs' => ['id'],
28
-			'mimetypes' => ['id'],
29
-			'mounts' => ['id'],
30
-			'personal_settings' => ['id'],
31
-			'properties' => ['id'],
32
-			'share' => ['id', 'parent', 'file_source'],
33
-			'storages' => ['numeric_id'],
34
-			'systemtag' => ['id'],
35
-			'systemtag_group' => ['systemtagid'],
36
-			'systemtag_object_mapping' => ['systemtagid'],
37
-			'vcategory' => ['id'],
38
-			'vcategory_to_object' => ['objid', 'categoryid'],
39
-		];
40
-	}
14
+    /**
15
+     * @return array Returns an array with the following structure
16
+     * ['table1' => ['column1', 'column2'], ...]
17
+     * @since 13.0.0
18
+     */
19
+    protected function getColumnsByTable() {
20
+        return [
21
+            'admin_settings' => ['id'],
22
+            'authtoken' => ['id'],
23
+            'bruteforce_attempts' => ['id'],
24
+            'comments' => ['id', 'parent_id', 'topmost_parent_id'],
25
+            'filecache' => ['fileid', 'storage', 'parent', 'mimetype', 'mimepart'],
26
+            'file_locks' => ['id'],
27
+            'jobs' => ['id'],
28
+            'mimetypes' => ['id'],
29
+            'mounts' => ['id'],
30
+            'personal_settings' => ['id'],
31
+            'properties' => ['id'],
32
+            'share' => ['id', 'parent', 'file_source'],
33
+            'storages' => ['numeric_id'],
34
+            'systemtag' => ['id'],
35
+            'systemtag_group' => ['systemtagid'],
36
+            'systemtag_object_mapping' => ['systemtagid'],
37
+            'vcategory' => ['id'],
38
+            'vcategory_to_object' => ['objid', 'categoryid'],
39
+        ];
40
+    }
41 41
 
42 42
 }
Please login to merge, or discard this patch.
apps/twofactor_backupcodes/lib/Migration/Version1002Date20170926101419.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -11,15 +11,15 @@
 block discarded – undo
11 11
  */
12 12
 class Version1002Date20170926101419 extends BigIntMigration {
13 13
 
14
-	/**
15
-	 * @return array Returns an array with the following structure
16
-	 * ['table1' => ['column1', 'column2'], ...]
17
-	 * @since 13.0.0
18
-	 */
19
-	protected function getColumnsByTable() {
20
-		return [
21
-			'twofactor_backupcodes' => ['id'],
22
-		];
23
-	}
14
+    /**
15
+     * @return array Returns an array with the following structure
16
+     * ['table1' => ['column1', 'column2'], ...]
17
+     * @since 13.0.0
18
+     */
19
+    protected function getColumnsByTable() {
20
+        return [
21
+            'twofactor_backupcodes' => ['id'],
22
+        ];
23
+    }
24 24
 
25 25
 }
Please login to merge, or discard this patch.
apps/dav/lib/Migration/Version1004Date20170926103422.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -11,25 +11,25 @@
 block discarded – undo
11 11
  */
12 12
 class Version1004Date20170926103422 extends BigIntMigration {
13 13
 
14
-	/**
15
-	 * @return array Returns an array with the following structure
16
-	 * ['table1' => ['column1', 'column2'], ...]
17
-	 * @since 13.0.0
18
-	 */
19
-	protected function getColumnsByTable() {
20
-		return [
21
-			'addressbooks' => ['id'],
22
-			'addressbookchanges' => ['id', 'addressbookid'],
23
-			'calendars' => ['id'],
24
-			'calendarchanges' => ['id', 'calendarid'],
25
-			'calendarobjects' => ['id', 'calendarid'],
26
-			'calendarobjects_props' => ['id', 'calendarid', 'objectid'],
27
-			'calendarsubscriptions' => ['id'],
28
-			'cards' => ['id', 'addressbookid'],
29
-			'cards_properties' => ['id', 'addressbookid', 'cardid'],
30
-			'dav_shares' => ['id', 'resourceid'],
31
-			'schedulingobjects' => ['id'],
32
-		];
33
-	}
14
+    /**
15
+     * @return array Returns an array with the following structure
16
+     * ['table1' => ['column1', 'column2'], ...]
17
+     * @since 13.0.0
18
+     */
19
+    protected function getColumnsByTable() {
20
+        return [
21
+            'addressbooks' => ['id'],
22
+            'addressbookchanges' => ['id', 'addressbookid'],
23
+            'calendars' => ['id'],
24
+            'calendarchanges' => ['id', 'calendarid'],
25
+            'calendarobjects' => ['id', 'calendarid'],
26
+            'calendarobjects_props' => ['id', 'calendarid', 'objectid'],
27
+            'calendarsubscriptions' => ['id'],
28
+            'cards' => ['id', 'addressbookid'],
29
+            'cards_properties' => ['id', 'addressbookid', 'cardid'],
30
+            'dav_shares' => ['id', 'resourceid'],
31
+            'schedulingobjects' => ['id'],
32
+        ];
33
+    }
34 34
 
35 35
 }
Please login to merge, or discard this patch.
lib/private/DB/OCPostgreSqlPlatform.php 2 patches
Indentation   +59 added lines, -59 removed lines patch added patch discarded remove patch
@@ -28,67 +28,67 @@
 block discarded – undo
28 28
 
29 29
 class OCPostgreSqlPlatform extends PostgreSqlPlatform {
30 30
 
31
-	/**
32
-	 * {@inheritDoc}
33
-	 */
34
-	public function getAlterTableSQL(TableDiff $diff){
35
-		$queries = parent::getAlterTableSQL($diff);
36
-		foreach ($queries as $index => $sql){
37
-			// BIGSERIAL could not be used in statements altering column type
38
-			// That's why we replace it with BIGINT 
39
-			// see https://github.com/owncloud/core/pull/28364#issuecomment-315006853
40
-			if (preg_match('|(ALTER TABLE\s+\S+\s+ALTER\s+\S+\s+TYPE\s+)(BIGSERIAL)|i', $sql, $matches)) {
41
-				$alterTable = $matches[1];
42
-				$queries[$index] = $alterTable . 'BIGINT';
43
-			}
31
+    /**
32
+     * {@inheritDoc}
33
+     */
34
+    public function getAlterTableSQL(TableDiff $diff){
35
+        $queries = parent::getAlterTableSQL($diff);
36
+        foreach ($queries as $index => $sql){
37
+            // BIGSERIAL could not be used in statements altering column type
38
+            // That's why we replace it with BIGINT 
39
+            // see https://github.com/owncloud/core/pull/28364#issuecomment-315006853
40
+            if (preg_match('|(ALTER TABLE\s+\S+\s+ALTER\s+\S+\s+TYPE\s+)(BIGSERIAL)|i', $sql, $matches)) {
41
+                $alterTable = $matches[1];
42
+                $queries[$index] = $alterTable . 'BIGINT';
43
+            }
44 44
 
45
-			// Changing integer to bigint kills next autoincrement value
46
-			// see https://github.com/owncloud/core/pull/28364#issuecomment-315006853
47
-			if (preg_match('|ALTER TABLE\s+(\S+)\s+ALTER\s+(\S+)\s+DROP DEFAULT|i', $sql, $matches)) {
48
-				$queryColumnName = $matches[2];
49
-				$columnDiff = $this->findColumnDiffByName($diff, $queryColumnName);
50
-				if ($columnDiff && $this->shouldSkipDropDefault($columnDiff)) {
51
-					unset($queries[$index]);
52
-					continue;
53
-				}
54
-			}
55
-		}
45
+            // Changing integer to bigint kills next autoincrement value
46
+            // see https://github.com/owncloud/core/pull/28364#issuecomment-315006853
47
+            if (preg_match('|ALTER TABLE\s+(\S+)\s+ALTER\s+(\S+)\s+DROP DEFAULT|i', $sql, $matches)) {
48
+                $queryColumnName = $matches[2];
49
+                $columnDiff = $this->findColumnDiffByName($diff, $queryColumnName);
50
+                if ($columnDiff && $this->shouldSkipDropDefault($columnDiff)) {
51
+                    unset($queries[$index]);
52
+                    continue;
53
+                }
54
+            }
55
+        }
56 56
 		
57
-		return $queries;
58
-	}
57
+        return $queries;
58
+    }
59 59
 
60
-	/**
61
-	 * We should NOT drop next sequence value if
62
-	 * - type was changed from INTEGER to BIGINT
63
-	 * - column keeps an autoincrement
64
-	 * - default value is kept NULL
65
-	 *
66
-	 * @param ColumnDiff $columnDiff
67
-	 * @return bool
68
-	 */
69
-	private function shouldSkipDropDefault(ColumnDiff $columnDiff) {
70
-		$column = $columnDiff->column;
71
-		$fromColumn = $columnDiff->fromColumn;
72
-		return $fromColumn->getType()->getName() === Type::INTEGER
73
-				&& $column->getType()->getName() === Type::BIGINT
74
-				&& $fromColumn->getDefault() === null
75
-				&& $column->getDefault() === null
76
-				&& $fromColumn->getAutoincrement()
77
-				&& $column->getAutoincrement();
78
-	}
60
+    /**
61
+     * We should NOT drop next sequence value if
62
+     * - type was changed from INTEGER to BIGINT
63
+     * - column keeps an autoincrement
64
+     * - default value is kept NULL
65
+     *
66
+     * @param ColumnDiff $columnDiff
67
+     * @return bool
68
+     */
69
+    private function shouldSkipDropDefault(ColumnDiff $columnDiff) {
70
+        $column = $columnDiff->column;
71
+        $fromColumn = $columnDiff->fromColumn;
72
+        return $fromColumn->getType()->getName() === Type::INTEGER
73
+                && $column->getType()->getName() === Type::BIGINT
74
+                && $fromColumn->getDefault() === null
75
+                && $column->getDefault() === null
76
+                && $fromColumn->getAutoincrement()
77
+                && $column->getAutoincrement();
78
+    }
79 79
 
80
-	/**
81
-	 * @param TableDiff $diff
82
-	 * @param string $name
83
-	 * @return  ColumnDiff | false
84
-	 */
85
-	private function findColumnDiffByName(TableDiff $diff, $name) {
86
-		foreach ($diff->changedColumns as $columnDiff) {
87
-			$oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
88
-			if ($oldColumnName === $name) {
89
-				return $columnDiff;
90
-			}
91
-		}
92
-		return false;
93
-	}
80
+    /**
81
+     * @param TableDiff $diff
82
+     * @param string $name
83
+     * @return  ColumnDiff | false
84
+     */
85
+    private function findColumnDiffByName(TableDiff $diff, $name) {
86
+        foreach ($diff->changedColumns as $columnDiff) {
87
+            $oldColumnName = $columnDiff->getOldColumnName()->getQuotedName($this);
88
+            if ($oldColumnName === $name) {
89
+                return $columnDiff;
90
+            }
91
+        }
92
+        return false;
93
+    }
94 94
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -31,15 +31,15 @@
 block discarded – undo
31 31
 	/**
32 32
 	 * {@inheritDoc}
33 33
 	 */
34
-	public function getAlterTableSQL(TableDiff $diff){
34
+	public function getAlterTableSQL(TableDiff $diff) {
35 35
 		$queries = parent::getAlterTableSQL($diff);
36
-		foreach ($queries as $index => $sql){
36
+		foreach ($queries as $index => $sql) {
37 37
 			// BIGSERIAL could not be used in statements altering column type
38 38
 			// That's why we replace it with BIGINT 
39 39
 			// see https://github.com/owncloud/core/pull/28364#issuecomment-315006853
40 40
 			if (preg_match('|(ALTER TABLE\s+\S+\s+ALTER\s+\S+\s+TYPE\s+)(BIGSERIAL)|i', $sql, $matches)) {
41 41
 				$alterTable = $matches[1];
42
-				$queries[$index] = $alterTable . 'BIGINT';
42
+				$queries[$index] = $alterTable.'BIGINT';
43 43
 			}
44 44
 
45 45
 			// Changing integer to bigint kills next autoincrement value
Please login to merge, or discard this patch.
lib/private/DB/ConnectionFactory.php 1 patch
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -37,201 +37,201 @@
 block discarded – undo
37 37
  * Takes care of creating and configuring Doctrine connections.
38 38
  */
39 39
 class ConnectionFactory {
40
-	/**
41
-	 * @var array
42
-	 *
43
-	 * Array mapping DBMS type to default connection parameters passed to
44
-	 * \Doctrine\DBAL\DriverManager::getConnection().
45
-	 */
46
-	protected $defaultConnectionParams = [
47
-		'mysql' => [
48
-			'adapter' => '\OC\DB\AdapterMySQL',
49
-			'charset' => 'UTF8',
50
-			'driver' => 'pdo_mysql',
51
-			'wrapperClass' => 'OC\DB\Connection',
52
-		],
53
-		'oci' => [
54
-			'adapter' => '\OC\DB\AdapterOCI8',
55
-			'charset' => 'AL32UTF8',
56
-			'driver' => 'oci8',
57
-			'wrapperClass' => 'OC\DB\OracleConnection',
58
-		],
59
-		'pgsql' => [
60
-			'adapter' => '\OC\DB\AdapterPgSql',
61
-			'driver' => 'pdo_pgsql',
62
-			'wrapperClass' => 'OC\DB\Connection',
63
-		],
64
-		'sqlite3' => [
65
-			'adapter' => '\OC\DB\AdapterSqlite',
66
-			'driver' => 'pdo_sqlite',
67
-			'wrapperClass' => 'OC\DB\Connection',
68
-		],
69
-	];
70
-
71
-	/** @var SystemConfig */
72
-	private $config;
73
-
74
-	/**
75
-	 * ConnectionFactory constructor.
76
-	 *
77
-	 * @param SystemConfig $systemConfig
78
-	 */
79
-	public function __construct(SystemConfig $systemConfig) {
80
-		$this->config = $systemConfig;
81
-		if ($this->config->getValue('mysql.utf8mb4', false)) {
82
-			$this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
83
-		}
84
-	}
85
-
86
-	/**
87
-	 * @brief Get default connection parameters for a given DBMS.
88
-	 * @param string $type DBMS type
89
-	 * @throws \InvalidArgumentException If $type is invalid
90
-	 * @return array Default connection parameters.
91
-	 */
92
-	public function getDefaultConnectionParams($type) {
93
-		$normalizedType = $this->normalizeType($type);
94
-		if (!isset($this->defaultConnectionParams[$normalizedType])) {
95
-			throw new \InvalidArgumentException("Unsupported type: $type");
96
-		}
97
-		$result = $this->defaultConnectionParams[$normalizedType];
98
-		// \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
99
-		// driver is missing. In this case, we won't be able to connect anyway.
100
-		if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
101
-			$result['driverOptions'] = array(
102
-				\PDO::MYSQL_ATTR_FOUND_ROWS => true,
103
-			);
104
-		}
105
-		return $result;
106
-	}
107
-
108
-	/**
109
-	 * @brief Get default connection parameters for a given DBMS.
110
-	 * @param string $type DBMS type
111
-	 * @param array $additionalConnectionParams Additional connection parameters
112
-	 * @return \OC\DB\Connection
113
-	 */
114
-	public function getConnection($type, $additionalConnectionParams) {
115
-		$normalizedType = $this->normalizeType($type);
116
-		$eventManager = new EventManager();
117
-		switch ($normalizedType) {
118
-			case 'mysql':
119
-				$eventManager->addEventSubscriber(
120
-					new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
121
-				break;
122
-			case 'oci':
123
-				$eventManager->addEventSubscriber(new OracleSessionInit);
124
-				// the driverOptions are unused in dbal and need to be mapped to the parameters
125
-				if (isset($additionalConnectionParams['driverOptions'])) {
126
-					$additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
127
-				}
128
-				$host = $additionalConnectionParams['host'];
129
-				$port = isset($additionalConnectionParams['port']) ? $additionalConnectionParams['port'] : null;
130
-				$dbName = $additionalConnectionParams['dbname'];
131
-
132
-				// we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
133
-				if ($host === '') {
134
-					$additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
135
-				} else {
136
-					$additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
137
-				}
138
-				unset($additionalConnectionParams['host']);
139
-				break;
140
-
141
-			case 'pgsql':
142
-				$additionalConnectionParams['platform'] = new OCPostgreSqlPlatform();
143
-				break;
144
-			case 'sqlite3':
145
-				$journalMode = $additionalConnectionParams['sqlite.journal_mode'];
146
-				$additionalConnectionParams['platform'] = new OCSqlitePlatform();
147
-				$eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
148
-				break;
149
-		}
150
-		/** @var Connection $connection */
151
-		$connection = DriverManager::getConnection(
152
-			array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
153
-			new Configuration(),
154
-			$eventManager
155
-		);
156
-		return $connection;
157
-	}
158
-
159
-	/**
160
-	 * @brief Normalize DBMS type
161
-	 * @param string $type DBMS type
162
-	 * @return string Normalized DBMS type
163
-	 */
164
-	public function normalizeType($type) {
165
-		return $type === 'sqlite' ? 'sqlite3' : $type;
166
-	}
167
-
168
-	/**
169
-	 * Checks whether the specified DBMS type is valid.
170
-	 *
171
-	 * @param string $type
172
-	 * @return bool
173
-	 */
174
-	public function isValidType($type) {
175
-		$normalizedType = $this->normalizeType($type);
176
-		return isset($this->defaultConnectionParams[$normalizedType]);
177
-	}
178
-
179
-	/**
180
-	 * Create the connection parameters for the config
181
-	 *
182
-	 * @return array
183
-	 */
184
-	public function createConnectionParams() {
185
-		$type = $this->config->getValue('dbtype', 'sqlite');
186
-
187
-		$connectionParams = [
188
-			'user' => $this->config->getValue('dbuser', ''),
189
-			'password' => $this->config->getValue('dbpassword', ''),
190
-		];
191
-		$name = $this->config->getValue('dbname', 'owncloud');
192
-
193
-		if ($this->normalizeType($type) === 'sqlite3') {
194
-			$dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
195
-			$connectionParams['path'] = $dataDir . '/' . $name . '.db';
196
-		} else {
197
-			$host = $this->config->getValue('dbhost', '');
198
-			if (strpos($host, ':')) {
199
-				// Host variable may carry a port or socket.
200
-				list($host, $portOrSocket) = explode(':', $host, 2);
201
-				if (ctype_digit($portOrSocket)) {
202
-					$connectionParams['port'] = $portOrSocket;
203
-				} else {
204
-					$connectionParams['unix_socket'] = $portOrSocket;
205
-				}
206
-			}
207
-			$connectionParams['host'] = $host;
208
-			$connectionParams['dbname'] = $name;
209
-		}
210
-
211
-		$connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', 'oc_');
212
-		$connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
213
-
214
-		//additional driver options, eg. for mysql ssl
215
-		$driverOptions = $this->config->getValue('dbdriveroptions', null);
216
-		if ($driverOptions) {
217
-			$connectionParams['driverOptions'] = $driverOptions;
218
-		}
219
-
220
-		// set default table creation options
221
-		$connectionParams['defaultTableOptions'] = [
222
-			'collate' => 'utf8_bin',
223
-			'tablePrefix' => $connectionParams['tablePrefix']
224
-		];
225
-
226
-		if ($this->config->getValue('mysql.utf8mb4', false)) {
227
-			$connectionParams['defaultTableOptions'] = [
228
-				'collate' => 'utf8mb4_bin',
229
-				'charset' => 'utf8mb4',
230
-				'row_format' => 'compressed',
231
-				'tablePrefix' => $connectionParams['tablePrefix']
232
-			];
233
-		}
234
-
235
-		return $connectionParams;
236
-	}
40
+    /**
41
+     * @var array
42
+     *
43
+     * Array mapping DBMS type to default connection parameters passed to
44
+     * \Doctrine\DBAL\DriverManager::getConnection().
45
+     */
46
+    protected $defaultConnectionParams = [
47
+        'mysql' => [
48
+            'adapter' => '\OC\DB\AdapterMySQL',
49
+            'charset' => 'UTF8',
50
+            'driver' => 'pdo_mysql',
51
+            'wrapperClass' => 'OC\DB\Connection',
52
+        ],
53
+        'oci' => [
54
+            'adapter' => '\OC\DB\AdapterOCI8',
55
+            'charset' => 'AL32UTF8',
56
+            'driver' => 'oci8',
57
+            'wrapperClass' => 'OC\DB\OracleConnection',
58
+        ],
59
+        'pgsql' => [
60
+            'adapter' => '\OC\DB\AdapterPgSql',
61
+            'driver' => 'pdo_pgsql',
62
+            'wrapperClass' => 'OC\DB\Connection',
63
+        ],
64
+        'sqlite3' => [
65
+            'adapter' => '\OC\DB\AdapterSqlite',
66
+            'driver' => 'pdo_sqlite',
67
+            'wrapperClass' => 'OC\DB\Connection',
68
+        ],
69
+    ];
70
+
71
+    /** @var SystemConfig */
72
+    private $config;
73
+
74
+    /**
75
+     * ConnectionFactory constructor.
76
+     *
77
+     * @param SystemConfig $systemConfig
78
+     */
79
+    public function __construct(SystemConfig $systemConfig) {
80
+        $this->config = $systemConfig;
81
+        if ($this->config->getValue('mysql.utf8mb4', false)) {
82
+            $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
83
+        }
84
+    }
85
+
86
+    /**
87
+     * @brief Get default connection parameters for a given DBMS.
88
+     * @param string $type DBMS type
89
+     * @throws \InvalidArgumentException If $type is invalid
90
+     * @return array Default connection parameters.
91
+     */
92
+    public function getDefaultConnectionParams($type) {
93
+        $normalizedType = $this->normalizeType($type);
94
+        if (!isset($this->defaultConnectionParams[$normalizedType])) {
95
+            throw new \InvalidArgumentException("Unsupported type: $type");
96
+        }
97
+        $result = $this->defaultConnectionParams[$normalizedType];
98
+        // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
99
+        // driver is missing. In this case, we won't be able to connect anyway.
100
+        if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
101
+            $result['driverOptions'] = array(
102
+                \PDO::MYSQL_ATTR_FOUND_ROWS => true,
103
+            );
104
+        }
105
+        return $result;
106
+    }
107
+
108
+    /**
109
+     * @brief Get default connection parameters for a given DBMS.
110
+     * @param string $type DBMS type
111
+     * @param array $additionalConnectionParams Additional connection parameters
112
+     * @return \OC\DB\Connection
113
+     */
114
+    public function getConnection($type, $additionalConnectionParams) {
115
+        $normalizedType = $this->normalizeType($type);
116
+        $eventManager = new EventManager();
117
+        switch ($normalizedType) {
118
+            case 'mysql':
119
+                $eventManager->addEventSubscriber(
120
+                    new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
121
+                break;
122
+            case 'oci':
123
+                $eventManager->addEventSubscriber(new OracleSessionInit);
124
+                // the driverOptions are unused in dbal and need to be mapped to the parameters
125
+                if (isset($additionalConnectionParams['driverOptions'])) {
126
+                    $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
127
+                }
128
+                $host = $additionalConnectionParams['host'];
129
+                $port = isset($additionalConnectionParams['port']) ? $additionalConnectionParams['port'] : null;
130
+                $dbName = $additionalConnectionParams['dbname'];
131
+
132
+                // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
133
+                if ($host === '') {
134
+                    $additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
135
+                } else {
136
+                    $additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
137
+                }
138
+                unset($additionalConnectionParams['host']);
139
+                break;
140
+
141
+            case 'pgsql':
142
+                $additionalConnectionParams['platform'] = new OCPostgreSqlPlatform();
143
+                break;
144
+            case 'sqlite3':
145
+                $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
146
+                $additionalConnectionParams['platform'] = new OCSqlitePlatform();
147
+                $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
148
+                break;
149
+        }
150
+        /** @var Connection $connection */
151
+        $connection = DriverManager::getConnection(
152
+            array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
153
+            new Configuration(),
154
+            $eventManager
155
+        );
156
+        return $connection;
157
+    }
158
+
159
+    /**
160
+     * @brief Normalize DBMS type
161
+     * @param string $type DBMS type
162
+     * @return string Normalized DBMS type
163
+     */
164
+    public function normalizeType($type) {
165
+        return $type === 'sqlite' ? 'sqlite3' : $type;
166
+    }
167
+
168
+    /**
169
+     * Checks whether the specified DBMS type is valid.
170
+     *
171
+     * @param string $type
172
+     * @return bool
173
+     */
174
+    public function isValidType($type) {
175
+        $normalizedType = $this->normalizeType($type);
176
+        return isset($this->defaultConnectionParams[$normalizedType]);
177
+    }
178
+
179
+    /**
180
+     * Create the connection parameters for the config
181
+     *
182
+     * @return array
183
+     */
184
+    public function createConnectionParams() {
185
+        $type = $this->config->getValue('dbtype', 'sqlite');
186
+
187
+        $connectionParams = [
188
+            'user' => $this->config->getValue('dbuser', ''),
189
+            'password' => $this->config->getValue('dbpassword', ''),
190
+        ];
191
+        $name = $this->config->getValue('dbname', 'owncloud');
192
+
193
+        if ($this->normalizeType($type) === 'sqlite3') {
194
+            $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
195
+            $connectionParams['path'] = $dataDir . '/' . $name . '.db';
196
+        } else {
197
+            $host = $this->config->getValue('dbhost', '');
198
+            if (strpos($host, ':')) {
199
+                // Host variable may carry a port or socket.
200
+                list($host, $portOrSocket) = explode(':', $host, 2);
201
+                if (ctype_digit($portOrSocket)) {
202
+                    $connectionParams['port'] = $portOrSocket;
203
+                } else {
204
+                    $connectionParams['unix_socket'] = $portOrSocket;
205
+                }
206
+            }
207
+            $connectionParams['host'] = $host;
208
+            $connectionParams['dbname'] = $name;
209
+        }
210
+
211
+        $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', 'oc_');
212
+        $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
213
+
214
+        //additional driver options, eg. for mysql ssl
215
+        $driverOptions = $this->config->getValue('dbdriveroptions', null);
216
+        if ($driverOptions) {
217
+            $connectionParams['driverOptions'] = $driverOptions;
218
+        }
219
+
220
+        // set default table creation options
221
+        $connectionParams['defaultTableOptions'] = [
222
+            'collate' => 'utf8_bin',
223
+            'tablePrefix' => $connectionParams['tablePrefix']
224
+        ];
225
+
226
+        if ($this->config->getValue('mysql.utf8mb4', false)) {
227
+            $connectionParams['defaultTableOptions'] = [
228
+                'collate' => 'utf8mb4_bin',
229
+                'charset' => 'utf8mb4',
230
+                'row_format' => 'compressed',
231
+                'tablePrefix' => $connectionParams['tablePrefix']
232
+            ];
233
+        }
234
+
235
+        return $connectionParams;
236
+    }
237 237
 }
Please login to merge, or discard this patch.