Schema.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\oci;
  8. use yii\base\InvalidCallException;
  9. use yii\db\ColumnSchema;
  10. use yii\db\Connection;
  11. use yii\db\Expression;
  12. use yii\db\TableSchema;
  13. /**
  14. * Schema is the class for retrieving metadata from an Oracle database
  15. *
  16. * @property string $lastInsertID The row ID of the last row inserted, or the last value retrieved from the
  17. * sequence object. This property is read-only.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class Schema extends \yii\db\Schema
  23. {
  24. /**
  25. * @var array map of DB errors and corresponding exceptions
  26. * If left part is found in DB error message exception class from the right part is used.
  27. */
  28. public $exceptionMap = [
  29. 'ORA-00001: unique constraint' => 'yii\db\IntegrityException',
  30. ];
  31. /**
  32. * @inheritdoc
  33. */
  34. public function init()
  35. {
  36. parent::init();
  37. if ($this->defaultSchema === null) {
  38. $this->defaultSchema = strtoupper($this->db->username);
  39. }
  40. }
  41. /**
  42. * @inheritdoc
  43. */
  44. public function releaseSavepoint($name)
  45. {
  46. // does nothing as Oracle does not support this
  47. }
  48. /**
  49. * @inheritdoc
  50. */
  51. public function quoteSimpleTableName($name)
  52. {
  53. return strpos($name, '"') !== false ? $name : '"' . $name . '"';
  54. }
  55. /**
  56. * @inheritdoc
  57. */
  58. public function createQueryBuilder()
  59. {
  60. return new QueryBuilder($this->db);
  61. }
  62. /**
  63. * @inheritdoc
  64. */
  65. public function createColumnSchemaBuilder($type, $length = null)
  66. {
  67. return new ColumnSchemaBuilder($type, $length, $this->db);
  68. }
  69. /**
  70. * @inheritdoc
  71. */
  72. public function loadTableSchema($name)
  73. {
  74. $table = new TableSchema();
  75. $this->resolveTableNames($table, $name);
  76. if ($this->findColumns($table)) {
  77. $this->findConstraints($table);
  78. return $table;
  79. } else {
  80. return null;
  81. }
  82. }
  83. /**
  84. * Resolves the table name and schema name (if any).
  85. *
  86. * @param TableSchema $table the table metadata object
  87. * @param string $name the table name
  88. */
  89. protected function resolveTableNames($table, $name)
  90. {
  91. $parts = explode('.', str_replace('"', '', $name));
  92. if (isset($parts[1])) {
  93. $table->schemaName = $parts[0];
  94. $table->name = $parts[1];
  95. } else {
  96. $table->schemaName = $this->defaultSchema;
  97. $table->name = $name;
  98. }
  99. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  100. }
  101. /**
  102. * Collects the table column metadata.
  103. * @param TableSchema $table the table schema
  104. * @return bool whether the table exists
  105. */
  106. protected function findColumns($table)
  107. {
  108. $sql = <<<SQL
  109. SELECT
  110. A.COLUMN_NAME,
  111. A.DATA_TYPE,
  112. A.DATA_PRECISION,
  113. A.DATA_SCALE,
  114. A.DATA_LENGTH,
  115. A.NULLABLE,
  116. A.DATA_DEFAULT,
  117. COM.COMMENTS AS COLUMN_COMMENT
  118. FROM ALL_TAB_COLUMNS A
  119. INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
  120. LEFT JOIN ALL_COL_COMMENTS COM ON (A.OWNER = COM.OWNER AND A.TABLE_NAME = COM.TABLE_NAME AND A.COLUMN_NAME = COM.COLUMN_NAME)
  121. WHERE
  122. A.OWNER = :schemaName
  123. AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
  124. AND B.OBJECT_NAME = :tableName
  125. ORDER BY A.COLUMN_ID
  126. SQL;
  127. try {
  128. $columns = $this->db->createCommand($sql, [
  129. ':tableName' => $table->name,
  130. ':schemaName' => $table->schemaName,
  131. ])->queryAll();
  132. } catch (\Exception $e) {
  133. return false;
  134. }
  135. if (empty($columns)) {
  136. return false;
  137. }
  138. foreach ($columns as $column) {
  139. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  140. $column = array_change_key_case($column, CASE_UPPER);
  141. }
  142. $c = $this->createColumn($column);
  143. $table->columns[$c->name] = $c;
  144. }
  145. return true;
  146. }
  147. /**
  148. * Sequence name of table
  149. *
  150. * @param string $tableName
  151. * @internal param \yii\db\TableSchema $table->name the table schema
  152. * @return string|null whether the sequence exists
  153. */
  154. protected function getTableSequenceName($tableName)
  155. {
  156. $sequenceNameSql = <<<SQL
  157. SELECT
  158. UD.REFERENCED_NAME AS SEQUENCE_NAME
  159. FROM USER_DEPENDENCIES UD
  160. JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
  161. WHERE
  162. UT.TABLE_NAME = :tableName
  163. AND UD.TYPE = 'TRIGGER'
  164. AND UD.REFERENCED_TYPE = 'SEQUENCE'
  165. SQL;
  166. $sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
  167. return $sequenceName === false ? null : $sequenceName;
  168. }
  169. /**
  170. * @Overrides method in class 'Schema'
  171. * @see http://www.php.net/manual/en/function.PDO-lastInsertId.php -> Oracle does not support this
  172. *
  173. * Returns the ID of the last inserted row or sequence value.
  174. * @param string $sequenceName name of the sequence object (required by some DBMS)
  175. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  176. * @throws InvalidCallException if the DB connection is not active
  177. */
  178. public function getLastInsertID($sequenceName = '')
  179. {
  180. if ($this->db->isActive) {
  181. // get the last insert id from the master connection
  182. $sequenceName = $this->quoteSimpleTableName($sequenceName);
  183. return $this->db->useMaster(function (Connection $db) use ($sequenceName) {
  184. return $db->createCommand("SELECT {$sequenceName}.CURRVAL FROM DUAL")->queryScalar();
  185. });
  186. } else {
  187. throw new InvalidCallException('DB Connection is not active.');
  188. }
  189. }
  190. /**
  191. * Creates ColumnSchema instance
  192. *
  193. * @param array $column
  194. * @return ColumnSchema
  195. */
  196. protected function createColumn($column)
  197. {
  198. $c = $this->createColumnSchema();
  199. $c->name = $column['COLUMN_NAME'];
  200. $c->allowNull = $column['NULLABLE'] === 'Y';
  201. $c->comment = $column['COLUMN_COMMENT'] === null ? '' : $column['COLUMN_COMMENT'];
  202. $c->isPrimaryKey = false;
  203. $this->extractColumnType($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
  204. $this->extractColumnSize($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
  205. $c->phpType = $this->getColumnPhpType($c);
  206. if (!$c->isPrimaryKey) {
  207. if (stripos($column['DATA_DEFAULT'], 'timestamp') !== false) {
  208. $c->defaultValue = null;
  209. } else {
  210. $defaultValue = $column['DATA_DEFAULT'];
  211. if ($c->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
  212. $c->defaultValue = new Expression('CURRENT_TIMESTAMP');
  213. } else {
  214. if ($defaultValue !== null) {
  215. if (($len = strlen($defaultValue)) > 2 && $defaultValue[0] === "'"
  216. && $defaultValue[$len - 1] === "'"
  217. ) {
  218. $defaultValue = substr($column['DATA_DEFAULT'], 1, -1);
  219. } else {
  220. $defaultValue = trim($defaultValue);
  221. }
  222. }
  223. $c->defaultValue = $c->phpTypecast($defaultValue);
  224. }
  225. }
  226. }
  227. return $c;
  228. }
  229. /**
  230. * Finds constraints and fills them into TableSchema object passed
  231. * @param TableSchema $table
  232. */
  233. protected function findConstraints($table)
  234. {
  235. $sql = <<<SQL
  236. SELECT
  237. /*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
  238. D.CONSTRAINT_NAME,
  239. D.CONSTRAINT_TYPE,
  240. C.COLUMN_NAME,
  241. C.POSITION,
  242. D.R_CONSTRAINT_NAME,
  243. E.TABLE_NAME AS TABLE_REF,
  244. F.COLUMN_NAME AS COLUMN_REF,
  245. C.TABLE_NAME
  246. FROM ALL_CONS_COLUMNS C
  247. INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
  248. LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
  249. LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
  250. WHERE
  251. C.OWNER = :schemaName
  252. AND C.TABLE_NAME = :tableName
  253. ORDER BY D.CONSTRAINT_NAME, C.POSITION
  254. SQL;
  255. $command = $this->db->createCommand($sql, [
  256. ':tableName' => $table->name,
  257. ':schemaName' => $table->schemaName,
  258. ]);
  259. $constraints = [];
  260. foreach ($command->queryAll() as $row) {
  261. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  262. $row = array_change_key_case($row, CASE_UPPER);
  263. }
  264. if ($row['CONSTRAINT_TYPE'] === 'P') {
  265. $table->columns[$row['COLUMN_NAME']]->isPrimaryKey = true;
  266. $table->primaryKey[] = $row['COLUMN_NAME'];
  267. if (empty($table->sequenceName)) {
  268. $table->sequenceName = $this->getTableSequenceName($table->name);
  269. }
  270. }
  271. if ($row['CONSTRAINT_TYPE'] !== 'R') {
  272. // this condition is not checked in SQL WHERE because of an Oracle Bug:
  273. // see https://github.com/yiisoft/yii2/pull/8844
  274. continue;
  275. }
  276. $name = $row['CONSTRAINT_NAME'];
  277. if (!isset($constraints[$name])) {
  278. $constraints[$name] = [
  279. 'tableName' => $row['TABLE_REF'],
  280. 'columns' => [],
  281. ];
  282. }
  283. $constraints[$name]['columns'][$row['COLUMN_NAME']] = $row['COLUMN_REF'];
  284. }
  285. foreach ($constraints as $constraint) {
  286. $name = array_keys($constraint);
  287. $name = current($name);
  288. $table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
  289. }
  290. }
  291. /**
  292. * @inheritdoc
  293. */
  294. protected function findSchemaNames()
  295. {
  296. $sql = <<<SQL
  297. SELECT
  298. USERNAME
  299. FROM DBA_USERS U
  300. WHERE
  301. EXISTS (SELECT 1 FROM DBA_OBJECTS O WHERE O.OWNER = U.USERNAME)
  302. AND DEFAULT_TABLESPACE NOT IN ('SYSTEM','SYSAUX')
  303. SQL;
  304. return $this->db->createCommand($sql)->queryColumn();
  305. }
  306. /**
  307. * @inheritdoc
  308. */
  309. protected function findTableNames($schema = '')
  310. {
  311. if ($schema === '') {
  312. $sql = <<<SQL
  313. SELECT
  314. TABLE_NAME
  315. FROM USER_TABLES
  316. UNION ALL
  317. SELECT
  318. VIEW_NAME AS TABLE_NAME
  319. FROM USER_VIEWS
  320. UNION ALL
  321. SELECT
  322. MVIEW_NAME AS TABLE_NAME
  323. FROM USER_MVIEWS
  324. ORDER BY TABLE_NAME
  325. SQL;
  326. $command = $this->db->createCommand($sql);
  327. } else {
  328. $sql = <<<SQL
  329. SELECT
  330. OBJECT_NAME AS TABLE_NAME
  331. FROM ALL_OBJECTS
  332. WHERE
  333. OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
  334. AND OWNER = :schema
  335. ORDER BY OBJECT_NAME
  336. SQL;
  337. $command = $this->db->createCommand($sql, [':schema' => $schema]);
  338. }
  339. $rows = $command->queryAll();
  340. $names = [];
  341. foreach ($rows as $row) {
  342. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  343. $row = array_change_key_case($row, CASE_UPPER);
  344. }
  345. $names[] = $row['TABLE_NAME'];
  346. }
  347. return $names;
  348. }
  349. /**
  350. * Returns all unique indexes for the given table.
  351. * Each array element is of the following structure:
  352. *
  353. * ```php
  354. * [
  355. * 'IndexName1' => ['col1' [, ...]],
  356. * 'IndexName2' => ['col2' [, ...]],
  357. * ]
  358. * ```
  359. *
  360. * @param TableSchema $table the table metadata
  361. * @return array all unique indexes for the given table.
  362. * @since 2.0.4
  363. */
  364. public function findUniqueIndexes($table)
  365. {
  366. $query = <<<SQL
  367. SELECT
  368. DIC.INDEX_NAME,
  369. DIC.COLUMN_NAME
  370. FROM ALL_INDEXES DI
  371. INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
  372. WHERE
  373. DI.UNIQUENESS = 'UNIQUE'
  374. AND DIC.TABLE_OWNER = :schemaName
  375. AND DIC.TABLE_NAME = :tableName
  376. ORDER BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
  377. SQL;
  378. $result = [];
  379. $command = $this->db->createCommand($query, [
  380. ':tableName' => $table->name,
  381. ':schemaName' => $table->schemaName,
  382. ]);
  383. foreach ($command->queryAll() as $row) {
  384. $result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
  385. }
  386. return $result;
  387. }
  388. /**
  389. * Extracts the data types for the given column
  390. * @param ColumnSchema $column
  391. * @param string $dbType DB type
  392. * @param string $precision total number of digits.
  393. * This parameter is available since version 2.0.4.
  394. * @param string $scale number of digits on the right of the decimal separator.
  395. * This parameter is available since version 2.0.4.
  396. * @param string $length length for character types.
  397. * This parameter is available since version 2.0.4.
  398. */
  399. protected function extractColumnType($column, $dbType, $precision, $scale, $length)
  400. {
  401. $column->dbType = $dbType;
  402. if (strpos($dbType, 'FLOAT') !== false || strpos($dbType, 'DOUBLE') !== false) {
  403. $column->type = 'double';
  404. } elseif (strpos($dbType, 'NUMBER') !== false) {
  405. if ($scale === null || $scale > 0) {
  406. $column->type = 'decimal';
  407. } else {
  408. $column->type = 'integer';
  409. }
  410. } elseif (strpos($dbType, 'INTEGER') !== false) {
  411. $column->type = 'integer';
  412. } elseif (strpos($dbType, 'BLOB') !== false) {
  413. $column->type = 'binary';
  414. } elseif (strpos($dbType, 'CLOB') !== false) {
  415. $column->type = 'text';
  416. } elseif (strpos($dbType, 'TIMESTAMP') !== false) {
  417. $column->type = 'timestamp';
  418. } else {
  419. $column->type = 'string';
  420. }
  421. }
  422. /**
  423. * Extracts size, precision and scale information from column's DB type.
  424. * @param ColumnSchema $column
  425. * @param string $dbType the column's DB type
  426. * @param string $precision total number of digits.
  427. * This parameter is available since version 2.0.4.
  428. * @param string $scale number of digits on the right of the decimal separator.
  429. * This parameter is available since version 2.0.4.
  430. * @param string $length length for character types.
  431. * This parameter is available since version 2.0.4.
  432. */
  433. protected function extractColumnSize($column, $dbType, $precision, $scale, $length)
  434. {
  435. $column->size = trim($length) === '' ? null : (int)$length;
  436. $column->precision = trim($precision) === '' ? null : (int)$precision;
  437. $column->scale = trim($scale) === '' ? null : (int)$scale;
  438. }
  439. /**
  440. * @inheritdoc
  441. */
  442. public function insert($table, $columns)
  443. {
  444. $params = [];
  445. $returnParams = [];
  446. $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
  447. $tableSchema = $this->getTableSchema($table);
  448. $returnColumns = $tableSchema->primaryKey;
  449. if (!empty($returnColumns)) {
  450. $columnSchemas = $tableSchema->columns;
  451. $returning = [];
  452. foreach ((array)$returnColumns as $name) {
  453. $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams));
  454. $returnParams[$phName] = [
  455. 'column' => $name,
  456. 'value' => null,
  457. ];
  458. if (!isset($columnSchemas[$name]) || $columnSchemas[$name]->phpType !== 'integer') {
  459. $returnParams[$phName]['dataType'] = \PDO::PARAM_STR;
  460. } else {
  461. $returnParams[$phName]['dataType'] = \PDO::PARAM_INT;
  462. }
  463. $returnParams[$phName]['size'] = isset($columnSchemas[$name]) && isset($columnSchemas[$name]->size) ? $columnSchemas[$name]->size : -1;
  464. $returning[] = $this->quoteColumnName($name);
  465. }
  466. $sql .= ' RETURNING ' . implode(', ', $returning) . ' INTO ' . implode(', ', array_keys($returnParams));
  467. }
  468. $command = $this->db->createCommand($sql, $params);
  469. $command->prepare(false);
  470. foreach ($returnParams as $name => &$value) {
  471. $command->pdoStatement->bindParam($name, $value['value'], $value['dataType'], $value['size']);
  472. }
  473. if (!$command->execute()) {
  474. return false;
  475. }
  476. $result = [];
  477. foreach ($returnParams as $value) {
  478. $result[$value['column']] = $value['value'];
  479. }
  480. return $result;
  481. }
  482. }