ConnectionFactory.php 8.9 KB

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