ConnectionFactory.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 'oci':
  124. $eventManager->addEventSubscriber(new OracleSessionInit);
  125. // the driverOptions are unused in dbal and need to be mapped to the parameters
  126. if (isset($additionalConnectionParams['driverOptions'])) {
  127. $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
  128. }
  129. $host = $additionalConnectionParams['host'];
  130. $port = $additionalConnectionParams['port'] ?? null;
  131. $dbName = $additionalConnectionParams['dbname'];
  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. case 'sqlite3':
  141. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  142. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  143. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  144. break;
  145. }
  146. /** @var Connection $connection */
  147. $connection = DriverManager::getConnection(
  148. $additionalConnectionParams,
  149. new Configuration(),
  150. $eventManager
  151. );
  152. return $connection;
  153. }
  154. /**
  155. * @brief Normalize DBMS type
  156. * @param string $type DBMS type
  157. * @return string Normalized DBMS type
  158. */
  159. public function normalizeType($type) {
  160. return $type === 'sqlite' ? 'sqlite3' : $type;
  161. }
  162. /**
  163. * Checks whether the specified DBMS type is valid.
  164. *
  165. * @param string $type
  166. * @return bool
  167. */
  168. public function isValidType($type) {
  169. $normalizedType = $this->normalizeType($type);
  170. return isset($this->defaultConnectionParams[$normalizedType]);
  171. }
  172. /**
  173. * Create the connection parameters for the config
  174. *
  175. * @param string $configPrefix
  176. * @return array
  177. */
  178. public function createConnectionParams(string $configPrefix = '') {
  179. $type = $this->config->getValue('dbtype', 'sqlite');
  180. $connectionParams = array_merge($this->getDefaultConnectionParams($type), [
  181. 'user' => $this->config->getValue($configPrefix . 'dbuser', $this->config->getValue('dbuser', '')),
  182. 'password' => $this->config->getValue($configPrefix . 'dbpassword', $this->config->getValue('dbpassword', '')),
  183. ]);
  184. $name = $this->config->getValue($configPrefix . 'dbname', $this->config->getValue('dbname', self::DEFAULT_DBNAME));
  185. if ($this->normalizeType($type) === 'sqlite3') {
  186. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  187. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  188. } else {
  189. $host = $this->config->getValue($configPrefix . 'dbhost', $this->config->getValue('dbhost', ''));
  190. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  191. $connectionParams['dbname'] = $name;
  192. }
  193. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  194. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  195. //additional driver options, eg. for mysql ssl
  196. $driverOptions = $this->config->getValue($configPrefix . 'dbdriveroptions', $this->config->getValue('dbdriveroptions', null));
  197. if ($driverOptions) {
  198. $connectionParams['driverOptions'] = $driverOptions;
  199. }
  200. // set default table creation options
  201. $connectionParams['defaultTableOptions'] = [
  202. 'collate' => 'utf8_bin',
  203. 'tablePrefix' => $connectionParams['tablePrefix']
  204. ];
  205. if ($this->config->getValue('mysql.utf8mb4', false)) {
  206. $connectionParams['defaultTableOptions'] = [
  207. 'collate' => 'utf8mb4_bin',
  208. 'charset' => 'utf8mb4',
  209. 'tablePrefix' => $connectionParams['tablePrefix']
  210. ];
  211. }
  212. if ($this->config->getValue('dbpersistent', false)) {
  213. $connectionParams['persistent'] = true;
  214. }
  215. $replica = $this->config->getValue('dbreplica', []) ?: [$connectionParams];
  216. return array_merge($connectionParams, [
  217. 'primary' => $connectionParams,
  218. 'replica' => $replica,
  219. ]);
  220. }
  221. /**
  222. * @param string $host
  223. * @return array
  224. */
  225. protected function splitHostFromPortAndSocket($host): array {
  226. $params = [
  227. 'host' => $host,
  228. ];
  229. $matches = [];
  230. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  231. // Host variable carries a port or socket.
  232. $params['host'] = $matches[1];
  233. if (is_numeric($matches[2])) {
  234. $params['port'] = (int) $matches[2];
  235. } else {
  236. $params['unix_socket'] = $matches[2];
  237. }
  238. }
  239. return $params;
  240. }
  241. }