ConnectionFactory.php 8.2 KB

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