ConnectionFactory.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. /** @var SystemConfig */
  74. private $config;
  75. /**
  76. * ConnectionFactory constructor.
  77. *
  78. * @param SystemConfig $systemConfig
  79. */
  80. public function __construct(SystemConfig $systemConfig) {
  81. $this->config = $systemConfig;
  82. if ($this->config->getValue('mysql.utf8mb4', false)) {
  83. $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
  84. }
  85. $collationOverride = $this->config->getValue('mysql.collation', null);
  86. if ($collationOverride) {
  87. $this->defaultConnectionParams['mysql']['collation'] = $collationOverride;
  88. }
  89. }
  90. /**
  91. * @brief Get default connection parameters for a given DBMS.
  92. * @param string $type DBMS type
  93. * @throws \InvalidArgumentException If $type is invalid
  94. * @return array Default connection parameters.
  95. */
  96. public function getDefaultConnectionParams($type) {
  97. $normalizedType = $this->normalizeType($type);
  98. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  99. throw new \InvalidArgumentException("Unsupported type: $type");
  100. }
  101. $result = $this->defaultConnectionParams[$normalizedType];
  102. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  103. // driver is missing. In this case, we won't be able to connect anyway.
  104. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  105. $result['driverOptions'] = [
  106. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  107. ];
  108. }
  109. return $result;
  110. }
  111. /**
  112. * @brief Get default connection parameters for a given DBMS.
  113. * @param string $type DBMS type
  114. * @param array $additionalConnectionParams Additional connection parameters
  115. * @return \OC\DB\Connection
  116. */
  117. public function getConnection($type, $additionalConnectionParams) {
  118. $normalizedType = $this->normalizeType($type);
  119. $eventManager = new EventManager();
  120. $eventManager->addEventSubscriber(new SetTransactionIsolationLevel());
  121. $additionalConnectionParams = array_merge($this->createConnectionParams(), $additionalConnectionParams);
  122. switch ($normalizedType) {
  123. case 'pgsql':
  124. // pg_connect used by Doctrine DBAL does not support URI notation (enclosed in brackets)
  125. $matches = [];
  126. if (preg_match('/^\[([^\]]+)\]$/', $additionalConnectionParams['host'], $matches)) {
  127. // Host variable carries a port or socket.
  128. $additionalConnectionParams['host'] = $matches[1];
  129. }
  130. break;
  131. case 'oci':
  132. $eventManager->addEventSubscriber(new OracleSessionInit);
  133. // the driverOptions are unused in dbal and need to be mapped to the parameters
  134. if (isset($additionalConnectionParams['driverOptions'])) {
  135. $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
  136. }
  137. $host = $additionalConnectionParams['host'];
  138. $port = $additionalConnectionParams['port'] ?? null;
  139. $dbName = $additionalConnectionParams['dbname'];
  140. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  141. if ($host === '') {
  142. $additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
  143. } else {
  144. $additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
  145. }
  146. unset($additionalConnectionParams['host']);
  147. break;
  148. case 'sqlite3':
  149. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  150. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  151. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  152. break;
  153. }
  154. /** @var Connection $connection */
  155. $connection = DriverManager::getConnection(
  156. $additionalConnectionParams,
  157. new Configuration(),
  158. $eventManager
  159. );
  160. return $connection;
  161. }
  162. /**
  163. * @brief Normalize DBMS type
  164. * @param string $type DBMS type
  165. * @return string Normalized DBMS type
  166. */
  167. public function normalizeType($type) {
  168. return $type === 'sqlite' ? 'sqlite3' : $type;
  169. }
  170. /**
  171. * Checks whether the specified DBMS type is valid.
  172. *
  173. * @param string $type
  174. * @return bool
  175. */
  176. public function isValidType($type) {
  177. $normalizedType = $this->normalizeType($type);
  178. return isset($this->defaultConnectionParams[$normalizedType]);
  179. }
  180. /**
  181. * Create the connection parameters for the config
  182. *
  183. * @param string $configPrefix
  184. * @return array
  185. */
  186. public function createConnectionParams(string $configPrefix = '') {
  187. $type = $this->config->getValue('dbtype', 'sqlite');
  188. $connectionParams = array_merge($this->getDefaultConnectionParams($type), [
  189. 'user' => $this->config->getValue($configPrefix . 'dbuser', $this->config->getValue('dbuser', '')),
  190. 'password' => $this->config->getValue($configPrefix . 'dbpassword', $this->config->getValue('dbpassword', '')),
  191. ]);
  192. $name = $this->config->getValue($configPrefix . 'dbname', $this->config->getValue('dbname', self::DEFAULT_DBNAME));
  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($configPrefix . 'dbhost', $this->config->getValue('dbhost', ''));
  198. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  199. $connectionParams['dbname'] = $name;
  200. }
  201. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  202. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  203. //additional driver options, eg. for mysql ssl
  204. $driverOptions = $this->config->getValue($configPrefix . 'dbdriveroptions', $this->config->getValue('dbdriveroptions', null));
  205. if ($driverOptions) {
  206. $connectionParams['driverOptions'] = $driverOptions;
  207. }
  208. // set default table creation options
  209. $connectionParams['defaultTableOptions'] = [
  210. 'collate' => 'utf8_bin',
  211. 'tablePrefix' => $connectionParams['tablePrefix']
  212. ];
  213. if ($this->config->getValue('mysql.utf8mb4', false)) {
  214. $connectionParams['defaultTableOptions'] = [
  215. 'collate' => 'utf8mb4_bin',
  216. 'charset' => 'utf8mb4',
  217. 'tablePrefix' => $connectionParams['tablePrefix']
  218. ];
  219. }
  220. if ($this->config->getValue('dbpersistent', false)) {
  221. $connectionParams['persistent'] = true;
  222. }
  223. $replica = $this->config->getValue($configPrefix . 'dbreplica', $this->config->getValue('dbreplica', [])) ?: [$connectionParams];
  224. return array_merge($connectionParams, [
  225. 'primary' => $connectionParams,
  226. 'replica' => $replica,
  227. ]);
  228. }
  229. /**
  230. * @param string $host
  231. * @return array
  232. */
  233. protected function splitHostFromPortAndSocket($host): array {
  234. $params = [
  235. 'host' => $host,
  236. ];
  237. $matches = [];
  238. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  239. // Host variable carries a port or socket.
  240. $params['host'] = $matches[1];
  241. if (is_numeric($matches[2])) {
  242. $params['port'] = (int) $matches[2];
  243. } else {
  244. $params['unix_socket'] = $matches[2];
  245. }
  246. }
  247. return $params;
  248. }
  249. }