OracleSchemaManager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the MIT license. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Schema;
  20. use Doctrine\DBAL\DBALException;
  21. use Doctrine\DBAL\Driver\DriverException;
  22. use Doctrine\DBAL\Types\Type;
  23. /**
  24. * Oracle Schema Manager.
  25. *
  26. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
  27. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
  28. * @author Benjamin Eberlei <kontakt@beberlei.de>
  29. * @since 2.0
  30. */
  31. class OracleSchemaManager extends AbstractSchemaManager
  32. {
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function dropDatabase($database)
  37. {
  38. try {
  39. parent::dropDatabase($database);
  40. } catch (DBALException $exception) {
  41. $exception = $exception->getPrevious();
  42. if (! $exception instanceof DriverException) {
  43. throw $exception;
  44. }
  45. // If we have a error code 1940 (ORA-01940), the drop database operation failed
  46. // because of active connections on the database.
  47. // To force dropping the database, we first have to close all active connections
  48. // on that database and issue the drop database operation again.
  49. if ($exception->getErrorCode() !== 1940) {
  50. throw $exception;
  51. }
  52. $this->killUserSessions($database);
  53. parent::dropDatabase($database);
  54. }
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. protected function _getPortableViewDefinition($view)
  60. {
  61. $view = \array_change_key_case($view, CASE_LOWER);
  62. return new View($this->getQuotedIdentifierName($view['view_name']), $view['text']);
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. protected function _getPortableUserDefinition($user)
  68. {
  69. $user = \array_change_key_case($user, CASE_LOWER);
  70. return array(
  71. 'user' => $user['username'],
  72. );
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. protected function _getPortableTableDefinition($table)
  78. {
  79. $table = \array_change_key_case($table, CASE_LOWER);
  80. return $this->getQuotedIdentifierName($table['table_name']);
  81. }
  82. /**
  83. * {@inheritdoc}
  84. *
  85. * @license New BSD License
  86. * @link http://ezcomponents.org/docs/api/trunk/DatabaseSchema/ezcDbSchemaPgsqlReader.html
  87. */
  88. protected function _getPortableTableIndexesList($tableIndexes, $tableName=null)
  89. {
  90. $indexBuffer = array();
  91. foreach ($tableIndexes as $tableIndex) {
  92. $tableIndex = \array_change_key_case($tableIndex, CASE_LOWER);
  93. $keyName = strtolower($tableIndex['name']);
  94. if (strtolower($tableIndex['is_primary']) == "p") {
  95. $keyName = 'primary';
  96. $buffer['primary'] = true;
  97. $buffer['non_unique'] = false;
  98. } else {
  99. $buffer['primary'] = false;
  100. $buffer['non_unique'] = ($tableIndex['is_unique'] == 0) ? true : false;
  101. }
  102. $buffer['key_name'] = $keyName;
  103. $buffer['column_name'] = $this->getQuotedIdentifierName($tableIndex['column_name']);
  104. $indexBuffer[] = $buffer;
  105. }
  106. return parent::_getPortableTableIndexesList($indexBuffer, $tableName);
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. protected function _getPortableTableColumnDefinition($tableColumn)
  112. {
  113. $tableColumn = \array_change_key_case($tableColumn, CASE_LOWER);
  114. $dbType = strtolower($tableColumn['data_type']);
  115. if (strpos($dbType, "timestamp(") === 0) {
  116. if (strpos($dbType, "with time zone")) {
  117. $dbType = "timestamptz";
  118. } else {
  119. $dbType = "timestamp";
  120. }
  121. }
  122. $unsigned = $fixed = null;
  123. if ( ! isset($tableColumn['column_name'])) {
  124. $tableColumn['column_name'] = '';
  125. }
  126. // Default values returned from database sometimes have trailing spaces.
  127. $tableColumn['data_default'] = trim($tableColumn['data_default']);
  128. if ($tableColumn['data_default'] === '' || $tableColumn['data_default'] === 'NULL') {
  129. $tableColumn['data_default'] = null;
  130. }
  131. if (null !== $tableColumn['data_default']) {
  132. // Default values returned from database are enclosed in single quotes.
  133. $tableColumn['data_default'] = trim($tableColumn['data_default'], "'");
  134. }
  135. $precision = null;
  136. $scale = null;
  137. $type = $this->_platform->getDoctrineTypeMapping($dbType);
  138. $type = $this->extractDoctrineTypeFromComment($tableColumn['comments'], $type);
  139. $tableColumn['comments'] = $this->removeDoctrineTypeFromComment($tableColumn['comments'], $type);
  140. switch ($dbType) {
  141. case 'number':
  142. if ($tableColumn['data_precision'] == 20 && $tableColumn['data_scale'] == 0) {
  143. $precision = 20;
  144. $scale = 0;
  145. $type = 'bigint';
  146. } elseif ($tableColumn['data_precision'] == 5 && $tableColumn['data_scale'] == 0) {
  147. $type = 'smallint';
  148. $precision = 5;
  149. $scale = 0;
  150. } elseif ($tableColumn['data_precision'] == 1 && $tableColumn['data_scale'] == 0) {
  151. $precision = 1;
  152. $scale = 0;
  153. $type = 'boolean';
  154. } elseif ($tableColumn['data_scale'] > 0) {
  155. $precision = $tableColumn['data_precision'];
  156. $scale = $tableColumn['data_scale'];
  157. $type = 'decimal';
  158. }
  159. $length = null;
  160. break;
  161. case 'pls_integer':
  162. case 'binary_integer':
  163. $length = null;
  164. break;
  165. case 'varchar':
  166. case 'varchar2':
  167. case 'nvarchar2':
  168. $length = $tableColumn['char_length'];
  169. $fixed = false;
  170. break;
  171. case 'char':
  172. case 'nchar':
  173. $length = $tableColumn['char_length'];
  174. $fixed = true;
  175. break;
  176. case 'date':
  177. case 'timestamp':
  178. $length = null;
  179. break;
  180. case 'float':
  181. case 'binary_float':
  182. case 'binary_double':
  183. $precision = $tableColumn['data_precision'];
  184. $scale = $tableColumn['data_scale'];
  185. $length = null;
  186. break;
  187. case 'clob':
  188. case 'nclob':
  189. $length = null;
  190. break;
  191. case 'blob':
  192. case 'raw':
  193. case 'long raw':
  194. case 'bfile':
  195. $length = null;
  196. break;
  197. case 'rowid':
  198. case 'urowid':
  199. default:
  200. $length = null;
  201. }
  202. $options = array(
  203. 'notnull' => (bool) ($tableColumn['nullable'] === 'N'),
  204. 'fixed' => (bool) $fixed,
  205. 'unsigned' => (bool) $unsigned,
  206. 'default' => $tableColumn['data_default'],
  207. 'length' => $length,
  208. 'precision' => $precision,
  209. 'scale' => $scale,
  210. 'comment' => isset($tableColumn['comments']) && '' !== $tableColumn['comments']
  211. ? $tableColumn['comments']
  212. : null,
  213. 'platformDetails' => array(),
  214. );
  215. return new Column($this->getQuotedIdentifierName($tableColumn['column_name']), Type::getType($type), $options);
  216. }
  217. /**
  218. * {@inheritdoc}
  219. */
  220. protected function _getPortableTableForeignKeysList($tableForeignKeys)
  221. {
  222. $list = array();
  223. foreach ($tableForeignKeys as $value) {
  224. $value = \array_change_key_case($value, CASE_LOWER);
  225. if (!isset($list[$value['constraint_name']])) {
  226. if ($value['delete_rule'] == "NO ACTION") {
  227. $value['delete_rule'] = null;
  228. }
  229. $list[$value['constraint_name']] = array(
  230. 'name' => $this->getQuotedIdentifierName($value['constraint_name']),
  231. 'local' => array(),
  232. 'foreign' => array(),
  233. 'foreignTable' => $value['references_table'],
  234. 'onDelete' => $value['delete_rule'],
  235. );
  236. }
  237. $localColumn = $this->getQuotedIdentifierName($value['local_column']);
  238. $foreignColumn = $this->getQuotedIdentifierName($value['foreign_column']);
  239. $list[$value['constraint_name']]['local'][$value['position']] = $localColumn;
  240. $list[$value['constraint_name']]['foreign'][$value['position']] = $foreignColumn;
  241. }
  242. $result = array();
  243. foreach ($list as $constraint) {
  244. $result[] = new ForeignKeyConstraint(
  245. array_values($constraint['local']), $this->getQuotedIdentifierName($constraint['foreignTable']),
  246. array_values($constraint['foreign']), $this->getQuotedIdentifierName($constraint['name']),
  247. array('onDelete' => $constraint['onDelete'])
  248. );
  249. }
  250. return $result;
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. protected function _getPortableSequenceDefinition($sequence)
  256. {
  257. $sequence = \array_change_key_case($sequence, CASE_LOWER);
  258. return new Sequence(
  259. $this->getQuotedIdentifierName($sequence['sequence_name']),
  260. $sequence['increment_by'],
  261. $sequence['min_value']
  262. );
  263. }
  264. /**
  265. * {@inheritdoc}
  266. */
  267. protected function _getPortableFunctionDefinition($function)
  268. {
  269. $function = \array_change_key_case($function, CASE_LOWER);
  270. return $function['name'];
  271. }
  272. /**
  273. * {@inheritdoc}
  274. */
  275. protected function _getPortableDatabaseDefinition($database)
  276. {
  277. $database = \array_change_key_case($database, CASE_LOWER);
  278. return $database['username'];
  279. }
  280. /**
  281. * {@inheritdoc}
  282. */
  283. public function createDatabase($database = null)
  284. {
  285. if (is_null($database)) {
  286. $database = $this->_conn->getDatabase();
  287. }
  288. $params = $this->_conn->getParams();
  289. $username = $database;
  290. $password = $params['password'];
  291. $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password;
  292. $this->_conn->executeUpdate($query);
  293. $query = 'GRANT DBA TO ' . $username;
  294. $this->_conn->executeUpdate($query);
  295. return true;
  296. }
  297. /**
  298. * @param string $table
  299. *
  300. * @return boolean
  301. */
  302. public function dropAutoincrement($table)
  303. {
  304. $sql = $this->_platform->getDropAutoincrementSql($table);
  305. foreach ($sql as $query) {
  306. $this->_conn->executeUpdate($query);
  307. }
  308. return true;
  309. }
  310. /**
  311. * {@inheritdoc}
  312. */
  313. public function dropTable($name)
  314. {
  315. $this->tryMethod('dropAutoincrement', $name);
  316. parent::dropTable($name);
  317. }
  318. /**
  319. * Returns the quoted representation of the given identifier name.
  320. *
  321. * Quotes non-uppercase identifiers explicitly to preserve case
  322. * and thus make references to the particular identifier work.
  323. *
  324. * @param string $identifier The identifier to quote.
  325. *
  326. * @return string The quoted identifier.
  327. */
  328. private function getQuotedIdentifierName($identifier)
  329. {
  330. if (preg_match('/[a-z]/', $identifier)) {
  331. return $this->_platform->quoteIdentifier($identifier);
  332. }
  333. return $identifier;
  334. }
  335. /**
  336. * Kills sessions connected with the given user.
  337. *
  338. * This is useful to force DROP USER operations which could fail because of active user sessions.
  339. *
  340. * @param string $user The name of the user to kill sessions for.
  341. *
  342. * @return void
  343. */
  344. private function killUserSessions($user)
  345. {
  346. $sql = <<<SQL
  347. SELECT
  348. s.sid,
  349. s.serial#
  350. FROM
  351. gv\$session s,
  352. gv\$process p
  353. WHERE
  354. s.username = ?
  355. AND p.addr(+) = s.paddr
  356. SQL;
  357. $activeUserSessions = $this->_conn->fetchAll($sql, array(strtoupper($user)));
  358. foreach ($activeUserSessions as $activeUserSession) {
  359. $activeUserSession = array_change_key_case($activeUserSession, \CASE_LOWER);
  360. $this->_execSql(
  361. sprintf(
  362. "ALTER SYSTEM KILL SESSION '%s, %s' IMMEDIATE",
  363. $activeUserSession['sid'],
  364. $activeUserSession['serial#']
  365. )
  366. );
  367. }
  368. }
  369. }