OracleSchemaManager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. <?php
  2. namespace Doctrine\DBAL\Schema;
  3. use Doctrine\DBAL\DBALException;
  4. use Doctrine\DBAL\Driver\Exception;
  5. use Doctrine\DBAL\Platforms\OraclePlatform;
  6. use Doctrine\DBAL\Types\Type;
  7. use Throwable;
  8. use function array_change_key_case;
  9. use function array_values;
  10. use function assert;
  11. use function preg_match;
  12. use function sprintf;
  13. use function str_replace;
  14. use function strpos;
  15. use function strtolower;
  16. use function strtoupper;
  17. use function trim;
  18. use const CASE_LOWER;
  19. /**
  20. * Oracle Schema Manager.
  21. */
  22. class OracleSchemaManager extends AbstractSchemaManager
  23. {
  24. /**
  25. * {@inheritdoc}
  26. */
  27. public function dropDatabase($database)
  28. {
  29. try {
  30. parent::dropDatabase($database);
  31. } catch (DBALException $exception) {
  32. $exception = $exception->getPrevious();
  33. assert($exception instanceof Throwable);
  34. if (! $exception instanceof Exception) {
  35. throw $exception;
  36. }
  37. // If we have a error code 1940 (ORA-01940), the drop database operation failed
  38. // because of active connections on the database.
  39. // To force dropping the database, we first have to close all active connections
  40. // on that database and issue the drop database operation again.
  41. if ($exception->getErrorCode() !== 1940) {
  42. throw $exception;
  43. }
  44. $this->killUserSessions($database);
  45. parent::dropDatabase($database);
  46. }
  47. }
  48. /**
  49. * {@inheritdoc}
  50. */
  51. protected function _getPortableViewDefinition($view)
  52. {
  53. $view = array_change_key_case($view, CASE_LOWER);
  54. return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. protected function _getPortableUserDefinition($user)
  60. {
  61. $user = array_change_key_case($user, CASE_LOWER);
  62. return [
  63. 'user' => $user['username'],
  64. ];
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. protected function _getPortableTableDefinition($table)
  70. {
  71. $table = array_change_key_case($table, CASE_LOWER);
  72. return $this->getQuotedIdentifierName($table['table_name']);
  73. }
  74. /**
  75. * {@inheritdoc}
  76. *
  77. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  78. */
  79. protected function _getPortableTableIndexesList($tableIndexes, $tableName = null)
  80. {
  81. $indexBuffer = [];
  82. foreach ($tableIndexes as $tableIndex) {
  83. $tableIndex = array_change_key_case($tableIndex, CASE_LOWER);
  84. $keyName = strtolower($tableIndex['name']);
  85. $buffer = [];
  86. if (strtolower($tableIndex['is_primary']) === 'p') {
  87. $keyName = 'primary';
  88. $buffer['primary'] = true;
  89. $buffer['non_unique'] = false;
  90. } else {
  91. $buffer['primary'] = false;
  92. $buffer['non_unique'] = ! $tableIndex['is_unique'];
  93. }
  94. $buffer['key_name'] = $keyName;
  95. $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
  96. $indexBuffer[] = $buffer;
  97. }
  98. return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
  99. }
  100. /**
  101. * {@inheritdoc}
  102. */
  103. protected function _getPortableTableColumnDefinition($tableColumn)
  104. {
  105. $tableColumn = array_change_key_case($tableColumn, CASE_LOWER);
  106. $dbType = strtolower($tableColumn['data_type']);
  107. if (strpos($dbType, 'timestamp(') === 0) {
  108. if (strpos($dbType, 'with time zone')) {
  109. $dbType = 'timestamptz';
  110. } else {
  111. $dbType = 'timestamp';
  112. }
  113. }
  114. $unsigned = $fixed = $precision = $scale = $length = null;
  115. if (! isset($tableColumn['column_name'])) {
  116. $tableColumn['column_name'] = '';
  117. }
  118. // Default values returned from database sometimes have trailing spaces.
  119. $tableColumn['data_default'] = trim($tableColumn['data_default']);
  120. if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
  121. $tableColumn['data_default'] = null;
  122. }
  123. if ($tableColumn['data_default'] !== null) {
  124. // Default values returned from database are represented as literal expressions
  125. if (preg_match('/^\'(.*)\'$/s', $tableColumn['data_default'], $matches)) {
  126. $tableColumn['data_default'] = str_replace("''", "'", $matches[1]);
  127. }
  128. }
  129. if ($tableColumn['data_precision'] !== null) {
  130. $precision = (int) $tableColumn['data_precision'];
  131. }
  132. if ($tableColumn['data_scale'] !== null) {
  133. $scale = (int) $tableColumn['data_scale'];
  134. }
  135. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  136. $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
  137. $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);
  138. switch ($dbType) {
  139. case 'number':
  140. if ($precision === 20 && $scale === 0) {
  141. $type = 'bigint';
  142. } elseif ($precision === 5 && $scale === 0) {
  143. $type = 'smallint';
  144. } elseif ($precision === 1 && $scale === 0) {
  145. $type = 'boolean';
  146. } elseif ($scale > 0) {
  147. $type = 'decimal';
  148. }
  149. break;
  150. case 'varchar':
  151. case 'varchar2':
  152. case 'nvarchar2':
  153. $length = $tableColumn['char_length'];
  154. $fixed = false;
  155. break;
  156. case 'char':
  157. case 'nchar':
  158. $length = $tableColumn['char_length'];
  159. $fixed = true;
  160. break;
  161. }
  162. $options = [
  163. 'notnull' => $tableColumn['nullable'] === 'N',
  164. 'fixed' => (bool) $fixed,
  165. 'unsigned' => (bool) $unsigned,
  166. 'default' => $tableColumn['data_default'],
  167. 'length' => $length,
  168. 'precision' => $precision,
  169. 'scale' => $scale,
  170. 'comment' => isset($tableColumn['comments']) && $tableColumn['comments'] !== ''
  171. ? $tableColumn['comments']
  172. : null,
  173. ];
  174. return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
  175. }
  176. /**
  177. * {@inheritdoc}
  178. */
  179. protected function _getPortableTableForeignKeysList($tableForeignKeys)
  180. {
  181. $list = [];
  182. foreach ($tableForeignKeys as $value) {
  183. $value = array_change_key_case($value, CASE_LOWER);
  184. if (! isset($list[$value['constraint_name']])) {
  185. if ($value['delete_rule'] === 'NO ACTION') {
  186. $value['delete_rule'] = null;
  187. }
  188. $list[$value['constraint_name']] = [
  189. 'name' => $this->getQuotedIdentifierName($value['constraint_name']),
  190. 'local' => [],
  191. 'foreign' => [],
  192. 'foreignTable' => $value['references_table'],
  193. 'onDelete' => $value['delete_rule'],
  194. ];
  195. }
  196. $localColumn = $this->getQuotedIdentifierName($value['local_column']);
  197. $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);
  198. $list[$value['constraint_name']]['local'][$value['position']] = $localColumn;
  199. $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
  200. }
  201. $result = [];
  202. foreach ($list as $constraint) {
  203. $result[] = new ForeignKeyConstraint(
  204. array_values($constraint['local']),
  205. $this->getQuotedIdentifierName($constraint['foreignTable']),
  206. array_values($constraint['foreign']),
  207. $this->getQuotedIdentifierName($constraint['name']),
  208. ['onDelete' => $constraint['onDelete']]
  209. );
  210. }
  211. return $result;
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. protected function _getPortableSequenceDefinition($sequence)
  217. {
  218. $sequence = array_change_key_case($sequence, CASE_LOWER);
  219. return new Sequence(
  220. $this->getQuotedIdentifierName($sequence['sequence_name']),
  221. (int) $sequence['increment_by'],
  222. (int) $sequence['min_value']
  223. );
  224. }
  225. /**
  226. * {@inheritdoc}
  227. *
  228. * @deprecated
  229. */
  230. protected function _getPortableFunctionDefinition($function)
  231. {
  232. $function = array_change_key_case($function, CASE_LOWER);
  233. return $function['name'];
  234. }
  235. /**
  236. * {@inheritdoc}
  237. */
  238. protected function _getPortableDatabaseDefinition($database)
  239. {
  240. $database = array_change_key_case($database, CASE_LOWER);
  241. return $database['username'];
  242. }
  243. /**
  244. * {@inheritdoc}
  245. *
  246. * @param string|null $database
  247. *
  248. * Calling this method without an argument or by passing NULL is deprecated.
  249. */
  250. public function createDatabase($database = null)
  251. {
  252. if ($database === null) {
  253. $database = $this->_conn->getDatabase();
  254. }
  255. $statement = 'CREATE USER ' . $database;
  256. $params = $this->_conn->getParams();
  257. if (isset($params['password'])) {
  258. $statement .= ' IDENTIFIED BY ' . $params['password'];
  259. }
  260. $this->_conn->executeStatement($statement);
  261. $statement = 'GRANT DBA TO ' . $database;
  262. $this->_conn->executeStatement($statement);
  263. }
  264. /**
  265. * @param string $table
  266. *
  267. * @return bool
  268. */
  269. public function dropAutoincrement($table)
  270. {
  271. assert($this->_platform instanceof OraclePlatform);
  272. $sql = $this->_platform->getDropAutoincrementSql($table);
  273. foreach ($sql as $query) {
  274. $this->_conn->executeStatement($query);
  275. }
  276. return true;
  277. }
  278. /**
  279. * {@inheritdoc}
  280. */
  281. public function dropTable($name)
  282. {
  283. $this->tryMethod('dropAutoincrement', $name);
  284. parent::dropTable($name);
  285. }
  286. /**
  287. * Returns the quoted representation of the given identifier name.
  288. *
  289. * Quotes non-uppercase identifiers explicitly to preserve case
  290. * and thus make references to the particular identifier work.
  291. *
  292. * @param string $identifier The identifier to quote.
  293. *
  294. * @return string The quoted identifier.
  295. */
  296. private function getQuotedIdentifierName($identifier)
  297. {
  298. if (preg_match('/[a-z]/', $identifier)) {
  299. return $this->_platform->quoteIdentifier($identifier);
  300. }
  301. return $identifier;
  302. }
  303. /**
  304. * Kills sessions connected with the given user.
  305. *
  306. * This is useful to force DROP USER operations which could fail because of active user sessions.
  307. *
  308. * @param string $user The name of the user to kill sessions for.
  309. *
  310. * @return void
  311. */
  312. private function killUserSessions($user)
  313. {
  314. $sql = <<<SQL
  315. SELECT
  316. s.sid,
  317. s.serial#
  318. FROM
  319. gv\$session s,
  320. gv\$process p
  321. WHERE
  322. s.username = ?
  323. AND p.addr(+) = s.paddr
  324. SQL;
  325. $activeUserSessions = $this->_conn->fetchAllAssociative($sql, [strtoupper($user)]);
  326. foreach ($activeUserSessions as $activeUserSession) {
  327. $activeUserSession = array_change_key_case($activeUserSession, CASE_LOWER);
  328. $this->_execSql(
  329. sprintf(
  330. "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
  331. $activeUserSession['sid'],
  332. $activeUserSession['serial#']
  333. )
  334. );
  335. }
  336. }
  337. /**
  338. * {@inheritdoc}
  339. */
  340. public function listTableDetails($name): Table
  341. {
  342. $table = parent::listTableDetails($name);
  343. $platform = $this->_platform;
  344. assert($platform instanceof OraclePlatform);
  345. $sql = $platform->getListTableCommentsSQL($name);
  346. $tableOptions = $this->_conn->fetchAssociative($sql);
  347. if ($tableOptions !== false) {
  348. $table->addOption('comment', $tableOptions['COMMENTS']);
  349. }
  350. return $table;
  351. }
  352. }