OracleSchemaManager.php 12 KB

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