1
0

ConnectionFactory.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\DB;
  29. use Doctrine\Common\EventManager;
  30. use Doctrine\DBAL\Configuration;
  31. use Doctrine\DBAL\DriverManager;
  32. use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
  33. use Doctrine\DBAL\Event\Listeners\SQLSessionInit;
  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. const DEFAULT_DBNAME = 'owncloud';
  41. /** @var string default database table prefix */
  42. 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. }
  86. /**
  87. * @brief Get default connection parameters for a given DBMS.
  88. * @param string $type DBMS type
  89. * @throws \InvalidArgumentException If $type is invalid
  90. * @return array Default connection parameters.
  91. */
  92. public function getDefaultConnectionParams($type) {
  93. $normalizedType = $this->normalizeType($type);
  94. if (!isset($this->defaultConnectionParams[$normalizedType])) {
  95. throw new \InvalidArgumentException("Unsupported type: $type");
  96. }
  97. $result = $this->defaultConnectionParams[$normalizedType];
  98. // \PDO::MYSQL_ATTR_FOUND_ROWS may not be defined, e.g. when the MySQL
  99. // driver is missing. In this case, we won't be able to connect anyway.
  100. if ($normalizedType === 'mysql' && defined('\PDO::MYSQL_ATTR_FOUND_ROWS')) {
  101. $result['driverOptions'] = array(
  102. \PDO::MYSQL_ATTR_FOUND_ROWS => true,
  103. );
  104. }
  105. return $result;
  106. }
  107. /**
  108. * @brief Get default connection parameters for a given DBMS.
  109. * @param string $type DBMS type
  110. * @param array $additionalConnectionParams Additional connection parameters
  111. * @return \OC\DB\Connection
  112. */
  113. public function getConnection($type, $additionalConnectionParams) {
  114. $normalizedType = $this->normalizeType($type);
  115. $eventManager = new EventManager();
  116. switch ($normalizedType) {
  117. case 'mysql':
  118. $eventManager->addEventSubscriber(
  119. new SQLSessionInit("SET SESSION AUTOCOMMIT=1"));
  120. break;
  121. case 'oci':
  122. $eventManager->addEventSubscriber(new OracleSessionInit);
  123. // the driverOptions are unused in dbal and need to be mapped to the parameters
  124. if (isset($additionalConnectionParams['driverOptions'])) {
  125. $additionalConnectionParams = array_merge($additionalConnectionParams, $additionalConnectionParams['driverOptions']);
  126. }
  127. $host = $additionalConnectionParams['host'];
  128. $port = isset($additionalConnectionParams['port']) ? $additionalConnectionParams['port'] : null;
  129. $dbName = $additionalConnectionParams['dbname'];
  130. // we set the connect string as dbname and unset the host to coerce doctrine into using it as connect string
  131. if ($host === '') {
  132. $additionalConnectionParams['dbname'] = $dbName; // use dbname as easy connect name
  133. } else {
  134. $additionalConnectionParams['dbname'] = '//' . $host . (!empty($port) ? ":{$port}" : "") . '/' . $dbName;
  135. }
  136. unset($additionalConnectionParams['host']);
  137. break;
  138. case 'sqlite3':
  139. $journalMode = $additionalConnectionParams['sqlite.journal_mode'];
  140. $additionalConnectionParams['platform'] = new OCSqlitePlatform();
  141. $eventManager->addEventSubscriber(new SQLiteSessionInit(true, $journalMode));
  142. break;
  143. }
  144. /** @var Connection $connection */
  145. $connection = DriverManager::getConnection(
  146. array_merge($this->getDefaultConnectionParams($type), $additionalConnectionParams),
  147. new Configuration(),
  148. $eventManager
  149. );
  150. return $connection;
  151. }
  152. /**
  153. * @brief Normalize DBMS type
  154. * @param string $type DBMS type
  155. * @return string Normalized DBMS type
  156. */
  157. public function normalizeType($type) {
  158. return $type === 'sqlite' ? 'sqlite3' : $type;
  159. }
  160. /**
  161. * Checks whether the specified DBMS type is valid.
  162. *
  163. * @param string $type
  164. * @return bool
  165. */
  166. public function isValidType($type) {
  167. $normalizedType = $this->normalizeType($type);
  168. return isset($this->defaultConnectionParams[$normalizedType]);
  169. }
  170. /**
  171. * Create the connection parameters for the config
  172. *
  173. * @return array
  174. */
  175. public function createConnectionParams() {
  176. $type = $this->config->getValue('dbtype', 'sqlite');
  177. $connectionParams = [
  178. 'user' => $this->config->getValue('dbuser', ''),
  179. 'password' => $this->config->getValue('dbpassword', ''),
  180. ];
  181. $name = $this->config->getValue('dbname', self::DEFAULT_DBNAME);
  182. if ($this->normalizeType($type) === 'sqlite3') {
  183. $dataDir = $this->config->getValue("datadirectory", \OC::$SERVERROOT . '/data');
  184. $connectionParams['path'] = $dataDir . '/' . $name . '.db';
  185. } else {
  186. $host = $this->config->getValue('dbhost', '');
  187. $connectionParams = array_merge($connectionParams, $this->splitHostFromPortAndSocket($host));
  188. $connectionParams['dbname'] = $name;
  189. }
  190. $connectionParams['tablePrefix'] = $this->config->getValue('dbtableprefix', self::DEFAULT_DBTABLEPREFIX);
  191. $connectionParams['sqlite.journal_mode'] = $this->config->getValue('sqlite.journal_mode', 'WAL');
  192. //additional driver options, eg. for mysql ssl
  193. $driverOptions = $this->config->getValue('dbdriveroptions', null);
  194. if ($driverOptions) {
  195. $connectionParams['driverOptions'] = $driverOptions;
  196. }
  197. // set default table creation options
  198. $connectionParams['defaultTableOptions'] = [
  199. 'collate' => 'utf8_bin',
  200. 'tablePrefix' => $connectionParams['tablePrefix']
  201. ];
  202. if ($this->config->getValue('mysql.utf8mb4', false)) {
  203. $connectionParams['defaultTableOptions'] = [
  204. 'collate' => 'utf8mb4_bin',
  205. 'charset' => 'utf8mb4',
  206. 'row_format' => 'compressed',
  207. 'tablePrefix' => $connectionParams['tablePrefix']
  208. ];
  209. }
  210. return $connectionParams;
  211. }
  212. /**
  213. * @param string $host
  214. * @return array
  215. */
  216. protected function splitHostFromPortAndSocket($host): array {
  217. $params = [
  218. 'host' => $host,
  219. ];
  220. $matches = [];
  221. if (preg_match('/^(.*):([^\]:]+)$/', $host, $matches)) {
  222. // Host variable carries a port or socket.
  223. $params['host'] = $matches[1];
  224. if (is_numeric($matches[2])) {
  225. $params['port'] = (int) $matches[2];
  226. } else {
  227. $params['unix_socket'] = $matches[2];
  228. }
  229. }
  230. return $params;
  231. }
  232. }