1
0

ConnectionFactory.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\DB;
  8. use Doctrine\Common\EventManager;
  9. use Doctrine\DBAL\Configuration;
  10. use Doctrine\DBAL\DriverManager;
  11. use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
  12. use OC\DB\QueryBuilder\Sharded\AutoIncrementHandler;
  13. use OC\DB\QueryBuilder\Sharded\ShardConnectionManager;
  14. use OC\SystemConfig;
  15. use OCP\ICacheFactory;
  16. use OCP\Server;
  17. /**
  18. * Takes care of creating and configuring Doctrine connections.
  19. */
  20. class ConnectionFactory {
  21. /** @var string default database name */
  22. public const DEFAULT_DBNAME = 'owncloud';
  23. /** @var string default database table prefix */
  24. public const DEFAULT_DBTABLEPREFIX = 'oc_';
  25. /**
  26. * @var array
  27. *
  28. * Array mapping DBMS type to default connection parameters passed to
  29. * \Doctrine\DBAL\DriverManager::getConnection().
  30. */
  31. protected $defaultConnectionParams = [
  32. 'mysql' => [
  33. 'adapter' => AdapterMySQL::class,
  34. 'charset' => 'UTF8',
  35. 'driver' => 'pdo_mysql',
  36. 'wrapperClass' => Connection::class,
  37. ],
  38. 'oci' => [
  39. 'adapter' => AdapterOCI8::class,
  40. 'charset' => 'AL32UTF8',
  41. 'driver' => 'oci8',
  42. 'wrapperClass' => OracleConnection::class,
  43. ],
  44. 'pgsql' => [
  45. 'adapter' => AdapterPgSql::class,
  46. 'driver' => 'pdo_pgsql',
  47. 'wrapperClass' => Connection::class,
  48. ],
  49. 'sqlite3' => [
  50. 'adapter' => AdapterSqlite::class,
  51. 'driver' => 'pdo_sqlite',
  52. 'wrapperClass' => Connection::class,
  53. ],
  54. ];
  55. private ShardConnectionManager $shardConnectionManager;
  56. private ICacheFactory $cacheFactory;
  57. public function __construct(
  58. private SystemConfig $config,
  59. ?ICacheFactory $cacheFactory = null,
  60. ) {
  61. if ($this->config->getValue('mysql.utf8mb4', false)) {
  62. $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
  63. }
  64. $collationOverride = $this->config->getValue('mysql.collation', null);
  65. if ($collationOverride) {
  66. $this->defaultConnectionParams['mysql']['collation'] = $collationOverride;
  67. }
  68. $this->shardConnectionManager = new ShardConnectionManager($this->config, $this);
  69. $this->cacheFactory = $cacheFactory ?? Server::get(ICacheFactory::class);
  70. }
  71. /**
  72. * @brief Get default connection parameters for a given DBMS.
  73. * @param string $type DBMS type
  74. * @throws \InvalidArgumentException If $type is invalid
  75. * @return array Default connection parameters.
  76. */
  77. public function getDefaultConnectionParams($type) {
  78. $normalizedType = $this->normalizeType($type);
  79. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  80. throw new \InvalidArgumentException("Unsupported type: $type");
  81. }
  82. $result = $this->defaultConnectionParams[$normalizedType];
  83. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  84. // driver is missing. In this case, we won't be able to connect anyway.
  85. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  86. $result['driverOptions'] = [
  87. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  88. ];
  89. }
  90. return $result;
  91. }
  92. /**
  93. * @brief Get default connection parameters for a given DBMS.
  94. * @param string $type DBMS type
  95. * @param array $additionalConnectionParams Additional connection parameters
  96. * @return \OC\DB\Connection
  97. */
  98. public function getConnection(string $type, array $additionalConnectionParams): Connection {
  99. $normalizedType = $this->normalizeType($type);
  100. $eventManager = new EventManager();
  101. $eventManager->addEventSubscriber(new SetTransactionIsolationLevel());
  102. $connectionParams = $this->createConnectionParams('', $additionalConnectionParams);
  103. switch ($normalizedType) {
  104. case 'pgsql':
  105. // pg_connect used by Doctrine DBAL does not support URI notation (enclosed in brackets)
  106. $matches = [];
  107. if (preg_match('/^\[([^\]]+)\]$/', $connectionParams['host'], $matches)) {
  108. // Host variable carries a port or socket.
  109. $connectionParams['host'] = $matches[1];
  110. }
  111. break;
  112. case 'oci':
  113. $eventManager->addEventSubscriber(new OracleSessionInit);
  114. // the driverOptions are unused in dbal and need to be mapped to the parameters
  115. if (isset($connectionParams['driverOptions'])) {
  116. $connectionParams = array_merge($connectionParams, $connectionParams['driverOptions']);
  117. }
  118. $host = $connectionParams['host'];
  119. $port = $connectionParams['port'] ?? null;
  120. $dbName = $connectionParams['dbname'];
  121. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  122. if ($host === '') {
  123. $connectionParams['dbname'] = $dbName; // use dbname as easy connect name
  124. } else {
  125. $connectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : '') . '/' . $dbName;
  126. }
  127. unset($connectionParams['host']);
  128. break;
  129. case 'sqlite3':
  130. $journalMode = $connectionParams['sqlite.journal_mode'];
  131. $connectionParams['platform'] = new OCSqlitePlatform();
  132. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  133. break;
  134. }
  135. /** @var Connection $connection */
  136. $connection = DriverManager::getConnection(
  137. $connectionParams,
  138. new Configuration(),
  139. $eventManager
  140. );
  141. return $connection;
  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. * Checks whether the specified DBMS type is valid.
  153. *
  154. * @param string $type
  155. * @return bool
  156. */
  157. public function isValidType($type) {
  158. $normalizedType = $this->normalizeType($type);
  159. return isset($this->defaultConnectionParams[$normalizedType]);
  160. }
  161. /**
  162. * Create the connection parameters for the config
  163. *
  164. * @param string $configPrefix
  165. * @return array
  166. */
  167. public function createConnectionParams(string $configPrefix = '', array $additionalConnectionParams = []) {
  168. $type = $this->config->getValue('dbtype', 'sqlite');
  169. $connectionParams = array_merge($this->getDefaultConnectionParams($type), [
  170. 'user' => $this->config->getValue($configPrefix . 'dbuser', $this->config->getValue('dbuser', '')),
  171. 'password' => $this->config->getValue($configPrefix . 'dbpassword', $this->config->getValue('dbpassword', '')),
  172. ]);
  173. $name = $this->config->getValue($configPrefix . 'dbname', $this->config->getValue('dbname', self::DEFAULT_DBNAME));
  174. if ($this->normalizeType($type) === 'sqlite3') {
  175. $dataDir = $this->config->getValue('datadirectory', \OC::$SERVERROOT . '/data');
  176. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  177. } else {
  178. $host = $this->config->getValue($configPrefix . 'dbhost', $this->config->getValue('dbhost', ''));
  179. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  180. $connectionParams['dbname'] = $name;
  181. }
  182. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  183. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  184. //additional driver options, eg. for mysql ssl
  185. $driverOptions = $this->config->getValue($configPrefix . 'dbdriveroptions', $this->config->getValue('dbdriveroptions', null));
  186. if ($driverOptions) {
  187. $connectionParams['driverOptions'] = $driverOptions;
  188. }
  189. // set default table creation options
  190. $connectionParams['defaultTableOptions'] = [
  191. 'collate' => 'utf8_bin',
  192. 'tablePrefix' => $connectionParams['tablePrefix']
  193. ];
  194. if ($this->config->getValue('mysql.utf8mb4', false)) {
  195. $connectionParams['defaultTableOptions'] = [
  196. 'collate' => 'utf8mb4_bin',
  197. 'charset' => 'utf8mb4',
  198. 'tablePrefix' => $connectionParams['tablePrefix']
  199. ];
  200. }
  201. if ($this->config->getValue('dbpersistent', false)) {
  202. $connectionParams['persistent'] = true;
  203. }
  204. $connectionParams['sharding'] = $this->config->getValue('dbsharding', []);
  205. if (!empty($connectionParams['sharding'])) {
  206. $connectionParams['shard_connection_manager'] = $this->shardConnectionManager;
  207. $connectionParams['auto_increment_handler'] = new AutoIncrementHandler(
  208. $this->cacheFactory,
  209. $this->shardConnectionManager,
  210. );
  211. } else {
  212. // just in case only the presence could lead to funny behaviour
  213. unset($connectionParams['sharding']);
  214. }
  215. $connectionParams = array_merge($connectionParams, $additionalConnectionParams);
  216. $replica = $this->config->getValue($configPrefix . 'dbreplica', $this->config->getValue('dbreplica', [])) ?: [$connectionParams];
  217. return array_merge($connectionParams, [
  218. 'primary' => $connectionParams,
  219. 'replica' => $replica,
  220. ]);
  221. }
  222. /**
  223. * @param string $host
  224. * @return array
  225. */
  226. protected function splitHostFromPortAndSocket($host): array {
  227. $params = [
  228. 'host' => $host,
  229. ];
  230. $matches = [];
  231. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  232. // Host variable carries a port or socket.
  233. $params['host'] = $matches[1];
  234. if (is_numeric($matches[2])) {
  235. $params['port'] = (int)$matches[2];
  236. } else {
  237. $params['unix_socket'] = $matches[2];
  238. }
  239. }
  240. return $params;
  241. }
  242. }