ConnectionFactory.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\DB;
  30. use Doctrine\Common\EventManager;
  31. use Doctrine\DBAL\Configuration;
  32. use Doctrine\DBAL\DriverManager;
  33. use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
  34. use OC\SystemConfig;
  35. /**
  36. * Takes care of creating and configuring Doctrine connections.
  37. */
  38. class ConnectionFactory {
  39. /** @var string default database name */
  40. public const DEFAULT_DBNAME = 'owncloud';
  41. /** @var string default database table prefix */
  42. public const DEFAULT_DBTABLEPREFIX = 'oc_';
  43. /**
  44. * @var array
  45. *
  46. * Array mapping DBMS type to default connection parameters passed to
  47. * \Doctrine\DBAL\DriverManager::getConnection().
  48. */
  49. protected $defaultConnectionParams = [
  50. 'mysql' => [
  51. 'adapter' => AdapterMySQL::class,
  52. 'charset' => 'UTF8',
  53. 'driver' => 'pdo_mysql',
  54. 'wrapperClass' => Connection::class,
  55. ],
  56. 'oci' => [
  57. 'adapter' => AdapterOCI8::class,
  58. 'charset' => 'AL32UTF8',
  59. 'driver' => 'oci8',
  60. 'wrapperClass' => OracleConnection::class,
  61. ],
  62. 'pgsql' => [
  63. 'adapter' => AdapterPgSql::class,
  64. 'driver' => 'pdo_pgsql',
  65. 'wrapperClass' => Connection::class,
  66. ],
  67. 'sqlite3' => [
  68. 'adapter' => AdapterSqlite::class,
  69. 'driver' => 'pdo_sqlite',
  70. 'wrapperClass' => Connection::class,
  71. ],
  72. ];
  73. public function __construct(
  74. private SystemConfig $config
  75. ) {
  76. if ($this->config->getValue('mysql.utf8mb4', false)) {
  77. $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
  78. }
  79. $collationOverride = $this->config->getValue('mysql.collation', null);
  80. if ($collationOverride) {
  81. $this->defaultConnectionParams['mysql']['collation'] = $collationOverride;
  82. }
  83. }
  84. /**
  85. * @brief Get default connection parameters for a given DBMS.
  86. * @param string $type DBMS type
  87. * @throws \InvalidArgumentException If $type is invalid
  88. * @return array Default connection parameters.
  89. */
  90. public function getDefaultConnectionParams($type) {
  91. $normalizedType = $this->normalizeType($type);
  92. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  93. throw new \InvalidArgumentException("Unsupported type: $type");
  94. }
  95. $result = $this->defaultConnectionParams[$normalizedType];
  96. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  97. // driver is missing. In this case, we won't be able to connect anyway.
  98. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  99. $result['driverOptions'] = [
  100. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  101. ];
  102. }
  103. return $result;
  104. }
  105. /**
  106. * @brief Get default connection parameters for a given DBMS.
  107. * @param string $type DBMS type
  108. * @param array $additionalConnectionParams Additional connection parameters
  109. * @return \OC\DB\Connection
  110. */
  111. public function getConnection(string $type, array $additionalConnectionParams): Connection {
  112. $normalizedType = $this->normalizeType($type);
  113. $eventManager = new EventManager();
  114. $eventManager->addEventSubscriber(new SetTransactionIsolationLevel());
  115. $connectionParams = $this->createConnectionParams('', $additionalConnectionParams);
  116. switch ($normalizedType) {
  117. case 'pgsql':
  118. // pg_connect used by Doctrine DBAL does not support URI notation (enclosed in brackets)
  119. $matches = [];
  120. if (preg_match('/^\[([^\]]+)\]$/', $connectionParams['host'], $matches)) {
  121. // Host variable carries a port or socket.
  122. $connectionParams['host'] = $matches[1];
  123. }
  124. break;
  125. case 'oci':
  126. $eventManager->addEventSubscriber(new OracleSessionInit);
  127. // the driverOptions are unused in dbal and need to be mapped to the parameters
  128. if (isset($connectionParams['driverOptions'])) {
  129. $connectionParams = array_merge($connectionParams, $connectionParams['driverOptions']);
  130. }
  131. $host = $connectionParams['host'];
  132. $port = $connectionParams['port'] ?? null;
  133. $dbName = $connectionParams['dbname'];
  134. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  135. if ($host === '') {
  136. $connectionParams['dbname'] = $dbName; // use dbname as easy connect name
  137. } else {
  138. $connectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
  139. }
  140. unset($connectionParams['host']);
  141. break;
  142. case 'sqlite3':
  143. $journalMode = $connectionParams['sqlite.journal_mode'];
  144. $connectionParams['platform'] = new OCSqlitePlatform();
  145. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  146. break;
  147. }
  148. /** @var Connection $connection */
  149. $connection = DriverManager::getConnection(
  150. $connectionParams,
  151. new Configuration(),
  152. $eventManager
  153. );
  154. return $connection;
  155. }
  156. /**
  157. * @brief Normalize DBMS type
  158. * @param string $type DBMS type
  159. * @return string Normalized DBMS type
  160. */
  161. public function normalizeType($type) {
  162. return $type === 'sqlite' ? 'sqlite3' : $type;
  163. }
  164. /**
  165. * Checks whether the specified DBMS type is valid.
  166. *
  167. * @param string $type
  168. * @return bool
  169. */
  170. public function isValidType($type) {
  171. $normalizedType = $this->normalizeType($type);
  172. return isset($this->defaultConnectionParams[$normalizedType]);
  173. }
  174. /**
  175. * Create the connection parameters for the config
  176. *
  177. * @param string $configPrefix
  178. * @return array
  179. */
  180. public function createConnectionParams(string $configPrefix = '', array $additionalConnectionParams = []) {
  181. $type = $this->config->getValue('dbtype', 'sqlite');
  182. $connectionParams = array_merge($this->getDefaultConnectionParams($type), [
  183. 'user' => $this->config->getValue($configPrefix . 'dbuser', $this->config->getValue('dbuser', '')),
  184. 'password' => $this->config->getValue($configPrefix . 'dbpassword', $this->config->getValue('dbpassword', '')),
  185. ]);
  186. $name = $this->config->getValue($configPrefix . 'dbname', $this->config->getValue('dbname', self::DEFAULT_DBNAME));
  187. if ($this->normalizeType($type) === 'sqlite3') {
  188. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  189. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  190. } else {
  191. $host = $this->config->getValue($configPrefix . 'dbhost', $this->config->getValue('dbhost', ''));
  192. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  193. $connectionParams['dbname'] = $name;
  194. }
  195. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  196. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  197. //additional driver options, eg. for mysql ssl
  198. $driverOptions = $this->config->getValue($configPrefix . 'dbdriveroptions', $this->config->getValue('dbdriveroptions', null));
  199. if ($driverOptions) {
  200. $connectionParams['driverOptions'] = $driverOptions;
  201. }
  202. // set default table creation options
  203. $connectionParams['defaultTableOptions'] = [
  204. 'collate' => 'utf8_bin',
  205. 'tablePrefix' => $connectionParams['tablePrefix']
  206. ];
  207. if ($this->config->getValue('mysql.utf8mb4', false)) {
  208. $connectionParams['defaultTableOptions'] = [
  209. 'collate' => 'utf8mb4_bin',
  210. 'charset' => 'utf8mb4',
  211. 'tablePrefix' => $connectionParams['tablePrefix']
  212. ];
  213. }
  214. if ($this->config->getValue('dbpersistent', false)) {
  215. $connectionParams['persistent'] = true;
  216. }
  217. $connectionParams = array_merge($connectionParams, $additionalConnectionParams);
  218. $replica = $this->config->getValue($configPrefix . 'dbreplica', $this->config->getValue('dbreplica', [])) ?: [$connectionParams];
  219. return array_merge($connectionParams, [
  220. 'primary' => $connectionParams,
  221. 'replica' => $replica,
  222. ]);
  223. }
  224. /**
  225. * @param string $host
  226. * @return array
  227. */
  228. protected function splitHostFromPortAndSocket($host): array {
  229. $params = [
  230. 'host' => $host,
  231. ];
  232. $matches = [];
  233. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  234. // Host variable carries a port or socket.
  235. $params['host'] = $matches[1];
  236. if (is_numeric($matches[2])) {
  237. $params['port'] = (int) $matches[2];
  238. } else {
  239. $params['unix_socket'] = $matches[2];
  240. }
  241. }
  242. return $params;
  243. }
  244. }