ConnectionFactory.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\DB;
  28. use Doctrine\Common\EventManager;
  29. use Doctrine\DBAL\Configuration;
  30. use Doctrine\DBAL\DriverManager;
  31. use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
  32. use Doctrine\DBAL\Event\Listeners\SQLSessionInit;
  33. use OC\SystemConfig;
  34. /**
  35. * Takes care of creating and configuring Doctrine connections.
  36. */
  37. class ConnectionFactory {
  38. /**
  39. * @var array
  40. *
  41. * Array mapping DBMS type to default connection parameters passed to
  42. * \Doctrine\DBAL\DriverManager::getConnection().
  43. */
  44. protected $defaultConnectionParams = [
  45. 'mysql' => [
  46. 'adapter' => AdapterMySQL::class,
  47. 'charset' => 'UTF8',
  48. 'driver' => 'pdo_mysql',
  49. 'wrapperClass' => Connection::class,
  50. ],
  51. 'oci' => [
  52. 'adapter' => AdapterOCI8::class,
  53. 'charset' => 'AL32UTF8',
  54. 'driver' => 'oci8',
  55. 'wrapperClass' => OracleConnection::class,
  56. ],
  57. 'pgsql' => [
  58. 'adapter' => AdapterPgSql::class,
  59. 'driver' => 'pdo_pgsql',
  60. 'wrapperClass' => Connection::class,
  61. ],
  62. 'sqlite3' => [
  63. 'adapter' => AdapterSqlite::class,
  64. 'driver' => 'pdo_sqlite',
  65. 'wrapperClass' => Connection::class,
  66. ],
  67. ];
  68. /** @var SystemConfig */
  69. private $config;
  70. /**
  71. * ConnectionFactory constructor.
  72. *
  73. * @param SystemConfig $systemConfig
  74. */
  75. public function __construct(SystemConfig $systemConfig) {
  76. $this->config = $systemConfig;
  77. if ($this->config->getValue('mysql.utf8mb4', false)) {
  78. $this->defaultConnectionParams['mysql']['charset'] = 'utf8mb4';
  79. }
  80. }
  81. /**
  82. * @brief Get default connection parameters for a given DBMS.
  83. * @param string $type DBMS type
  84. * @throws \InvalidArgumentException If $type is invalid
  85. * @return array Default connection parameters.
  86. */
  87. public function getDefaultConnectionParams($type) {
  88. $normalizedType = $this->normalizeType($type);
  89. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  90. throw new \InvalidArgumentException("Unsupported type: $type");
  91. }
  92. $result = $this->defaultConnectionParams[$normalizedType];
  93. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  94. // driver is missing. In this case, we won't be able to connect anyway.
  95. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  96. $result['driverOptions'] = array(
  97. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  98. );
  99. }
  100. return $result;
  101. }
  102. /**
  103. * @brief Get default connection parameters for a given DBMS.
  104. * @param string $type DBMS type
  105. * @param array $additionalConnectionParams Additional connection parameters
  106. * @return \OC\DB\Connection
  107. */
  108. public function getConnection($type, $additionalConnectionParams) {
  109. $normalizedType = $this->normalizeType($type);
  110. $eventManager = new EventManager();
  111. switch ($normalizedType) {
  112. case 'mysql':
  113. $eventManager->addEventSubscriber(
  114. new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
  115. break;
  116. case 'oci':
  117. $eventManager->addEventSubscriber(new OracleSessionInit);
  118. // the driverOptions are unused in dbal and need to be mapped to the parameters
  119. if (isset($additionalConnectionParams['driverOptions'])) {
  120. $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
  121. }
  122. $host = $additionalConnectionParams['host'];
  123. $port = isset($additionalConnectionParams['port']) ? $additionalConnectionParams['port'] : null;
  124. $dbName = $additionalConnectionParams['dbname'];
  125. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  126. if ($host === '') {
  127. $additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
  128. } else {
  129. $additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
  130. }
  131. unset($additionalConnectionParams['host']);
  132. break;
  133. case 'sqlite3':
  134. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  135. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  136. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  137. break;
  138. }
  139. /** @var Connection $connection */
  140. $connection = DriverManager::getConnection(
  141. array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
  142. new Configuration(),
  143. $eventManager
  144. );
  145. return $connection;
  146. }
  147. /**
  148. * @brief Normalize DBMS type
  149. * @param string $type DBMS type
  150. * @return string Normalized DBMS type
  151. */
  152. public function normalizeType($type) {
  153. return $type === 'sqlite' ? 'sqlite3' : $type;
  154. }
  155. /**
  156. * Checks whether the specified DBMS type is valid.
  157. *
  158. * @param string $type
  159. * @return bool
  160. */
  161. public function isValidType($type) {
  162. $normalizedType = $this->normalizeType($type);
  163. return isset($this->defaultConnectionParams[$normalizedType]);
  164. }
  165. /**
  166. * Create the connection parameters for the config
  167. *
  168. * @return array
  169. */
  170. public function createConnectionParams() {
  171. $type = $this->config->getValue('dbtype', 'sqlite');
  172. $connectionParams = [
  173. 'user' => $this->config->getValue('dbuser', ''),
  174. 'password' => $this->config->getValue('dbpassword', ''),
  175. ];
  176. $name = $this->config->getValue('dbname', 'owncloud');
  177. if ($this->normalizeType($type) === 'sqlite3') {
  178. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  179. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  180. } else {
  181. $host = $this->config->getValue('dbhost', '');
  182. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  183. $connectionParams['dbname'] = $name;
  184. }
  185. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', 'oc_');
  186. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  187. //additional driver options, eg. for mysql ssl
  188. $driverOptions = $this->config->getValue('dbdriveroptions', null);
  189. if ($driverOptions) {
  190. $connectionParams['driverOptions'] = $driverOptions;
  191. }
  192. // set default table creation options
  193. $connectionParams['defaultTableOptions'] = [
  194. 'collate' => 'utf8_bin',
  195. 'tablePrefix' => $connectionParams['tablePrefix']
  196. ];
  197. if ($this->config->getValue('mysql.utf8mb4', false)) {
  198. $connectionParams['defaultTableOptions'] = [
  199. 'collate' => 'utf8mb4_bin',
  200. 'charset' => 'utf8mb4',
  201. 'row_format' => 'compressed',
  202. 'tablePrefix' => $connectionParams['tablePrefix']
  203. ];
  204. }
  205. return $connectionParams;
  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. }