ConnectionFactory.php 7.4 KB

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