1
0

ConnectionFactory.php 8.6 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 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 = isset($additionalConnectionParams['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 'sqlite3':
  145. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  146. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  147. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  148. break;
  149. }
  150. /** @var Connection $connection */
  151. $connection = DriverManager::getConnection(
  152. array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
  153. new Configuration(),
  154. $eventManager
  155. );
  156. return $connection;
  157. }
  158. /**
  159. * @brief Normalize DBMS type
  160. * @param string $type DBMS type
  161. * @return string Normalized DBMS type
  162. */
  163. public function normalizeType($type) {
  164. return $type === 'sqlite' ? 'sqlite3' : $type;
  165. }
  166. /**
  167. * Checks whether the specified DBMS type is valid.
  168. *
  169. * @param string $type
  170. * @return bool
  171. */
  172. public function isValidType($type) {
  173. $normalizedType = $this->normalizeType($type);
  174. return isset($this->defaultConnectionParams[$normalizedType]);
  175. }
  176. /**
  177. * Create the connection parameters for the config
  178. *
  179. * @param string $configPrefix
  180. * @return array
  181. */
  182. public function createConnectionParams(string $configPrefix = '') {
  183. $type = $this->config->getValue('dbtype', 'sqlite');
  184. $connectionParams = [
  185. 'user' => $this->config->getValue($configPrefix . 'dbuser', $this->config->getValue('dbuser', '')),
  186. 'password' => $this->config->getValue($configPrefix . 'dbpassword', $this->config->getValue('dbpassword', '')),
  187. ];
  188. $name = $this->config->getValue($configPrefix . 'dbname', $this->config->getValue('dbname', self::DEFAULT_DBNAME));
  189. if ($this->normalizeType($type) === 'sqlite3') {
  190. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  191. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  192. } else {
  193. $host = $this->config->getValue($configPrefix . 'dbhost', $this->config->getValue('dbhost', ''));
  194. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  195. $connectionParams['dbname'] = $name;
  196. }
  197. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  198. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  199. //additional driver options, eg. for mysql ssl
  200. $driverOptions = $this->config->getValue($configPrefix . 'dbdriveroptions', $this->config->getValue('dbdriveroptions', null));
  201. if ($driverOptions) {
  202. $connectionParams['driverOptions'] = $driverOptions;
  203. }
  204. // set default table creation options
  205. $connectionParams['defaultTableOptions'] = [
  206. 'collate' => 'utf8_bin',
  207. 'tablePrefix' => $connectionParams['tablePrefix']
  208. ];
  209. if ($this->config->getValue('mysql.utf8mb4', false)) {
  210. $connectionParams['defaultTableOptions'] = [
  211. 'collate' => 'utf8mb4_bin',
  212. 'charset' => 'utf8mb4',
  213. 'tablePrefix' => $connectionParams['tablePrefix']
  214. ];
  215. }
  216. if ($this->config->getValue('dbpersistent', false)) {
  217. $connectionParams['persistent'] = true;
  218. }
  219. return $connectionParams;
  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. }