Schema.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\db\oci;
  8. use Yii;
  9. use yii\base\InvalidCallException;
  10. use yii\base\NotSupportedException;
  11. use yii\db\CheckConstraint;
  12. use yii\db\ColumnSchema;
  13. use yii\db\Connection;
  14. use yii\db\Constraint;
  15. use yii\db\ConstraintFinderInterface;
  16. use yii\db\ConstraintFinderTrait;
  17. use yii\db\Expression;
  18. use yii\db\ForeignKeyConstraint;
  19. use yii\db\IndexConstraint;
  20. use yii\db\TableSchema;
  21. use yii\helpers\ArrayHelper;
  22. /**
  23. * Schema is the class for retrieving metadata from an Oracle database.
  24. *
  25. * @property-read string $lastInsertID The row ID of the last row inserted, or the last value retrieved from
  26. * the sequence object.
  27. *
  28. * @author Qiang Xue <qiang.xue@gmail.com>
  29. * @since 2.0
  30. */
  31. class Schema extends \yii\db\Schema implements ConstraintFinderInterface
  32. {
  33. use ConstraintFinderTrait;
  34. /**
  35. * @var array map of DB errors and corresponding exceptions
  36. * If left part is found in DB error message exception class from the right part is used.
  37. */
  38. public $exceptionMap = [
  39. 'ORA-00001: unique constraint' => 'yii\db\IntegrityException',
  40. ];
  41. /**
  42. * {@inheritdoc}
  43. */
  44. protected $tableQuoteCharacter = '"';
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function init()
  49. {
  50. parent::init();
  51. if ($this->defaultSchema === null) {
  52. $username = $this->db->username;
  53. if (empty($username)) {
  54. $username = isset($this->db->masters[0]['username']) ? $this->db->masters[0]['username'] : '';
  55. }
  56. $this->defaultSchema = strtoupper($username);
  57. }
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. protected function resolveTableName($name)
  63. {
  64. $resolvedName = new TableSchema();
  65. $parts = explode('.', str_replace('"', '', $name));
  66. if (isset($parts[1])) {
  67. $resolvedName->schemaName = $parts[0];
  68. $resolvedName->name = $parts[1];
  69. } else {
  70. $resolvedName->schemaName = $this->defaultSchema;
  71. $resolvedName->name = $name;
  72. }
  73. $resolvedName->fullName = ($resolvedName->schemaName !== $this->defaultSchema ? $resolvedName->schemaName . '.' : '') . $resolvedName->name;
  74. return $resolvedName;
  75. }
  76. /**
  77. * {@inheritdoc}
  78. * @see https://docs.oracle.com/cd/B28359_01/server.111/b28337/tdpsg_user_accounts.htm
  79. */
  80. protected function findSchemaNames()
  81. {
  82. static $sql = <<<'SQL'
  83. SELECT "u"."USERNAME"
  84. FROM "DBA_USERS" "u"
  85. WHERE "u"."DEFAULT_TABLESPACE" NOT IN ('SYSTEM', 'SYSAUX')
  86. ORDER BY "u"."USERNAME" ASC
  87. SQL;
  88. return $this->db->createCommand($sql)->queryColumn();
  89. }
  90. /**
  91. * {@inheritdoc}
  92. */
  93. protected function findTableNames($schema = '')
  94. {
  95. if ($schema === '') {
  96. $sql = <<<'SQL'
  97. SELECT
  98. TABLE_NAME
  99. FROM USER_TABLES
  100. UNION ALL
  101. SELECT
  102. VIEW_NAME AS TABLE_NAME
  103. FROM USER_VIEWS
  104. UNION ALL
  105. SELECT
  106. MVIEW_NAME AS TABLE_NAME
  107. FROM USER_MVIEWS
  108. ORDER BY TABLE_NAME
  109. SQL;
  110. $command = $this->db->createCommand($sql);
  111. } else {
  112. $sql = <<<'SQL'
  113. SELECT
  114. OBJECT_NAME AS TABLE_NAME
  115. FROM ALL_OBJECTS
  116. WHERE
  117. OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
  118. AND OWNER = :schema
  119. ORDER BY OBJECT_NAME
  120. SQL;
  121. $command = $this->db->createCommand($sql, [':schema' => $schema]);
  122. }
  123. $rows = $command->queryAll();
  124. $names = [];
  125. foreach ($rows as $row) {
  126. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  127. $row = array_change_key_case($row, CASE_UPPER);
  128. }
  129. $names[] = $row['TABLE_NAME'];
  130. }
  131. return $names;
  132. }
  133. /**
  134. * {@inheritdoc}
  135. */
  136. protected function loadTableSchema($name)
  137. {
  138. $table = new TableSchema();
  139. $this->resolveTableNames($table, $name);
  140. if ($this->findColumns($table)) {
  141. $this->findConstraints($table);
  142. return $table;
  143. }
  144. return null;
  145. }
  146. /**
  147. * {@inheritdoc}
  148. */
  149. protected function loadTablePrimaryKey($tableName)
  150. {
  151. return $this->loadTableConstraints($tableName, 'primaryKey');
  152. }
  153. /**
  154. * {@inheritdoc}
  155. */
  156. protected function loadTableForeignKeys($tableName)
  157. {
  158. return $this->loadTableConstraints($tableName, 'foreignKeys');
  159. }
  160. /**
  161. * {@inheritdoc}
  162. */
  163. protected function loadTableIndexes($tableName)
  164. {
  165. static $sql = <<<'SQL'
  166. SELECT
  167. /*+ PUSH_PRED("ui") PUSH_PRED("uicol") PUSH_PRED("uc") */
  168. "ui"."INDEX_NAME" AS "name",
  169. "uicol"."COLUMN_NAME" AS "column_name",
  170. CASE "ui"."UNIQUENESS" WHEN 'UNIQUE' THEN 1 ELSE 0 END AS "index_is_unique",
  171. CASE WHEN "uc"."CONSTRAINT_NAME" IS NOT NULL THEN 1 ELSE 0 END AS "index_is_primary"
  172. FROM "SYS"."USER_INDEXES" "ui"
  173. LEFT JOIN "SYS"."USER_IND_COLUMNS" "uicol"
  174. ON "uicol"."INDEX_NAME" = "ui"."INDEX_NAME"
  175. LEFT JOIN "SYS"."USER_CONSTRAINTS" "uc"
  176. ON "uc"."OWNER" = "ui"."TABLE_OWNER" AND "uc"."CONSTRAINT_NAME" = "ui"."INDEX_NAME" AND "uc"."CONSTRAINT_TYPE" = 'P'
  177. WHERE "ui"."TABLE_OWNER" = :schemaName AND "ui"."TABLE_NAME" = :tableName
  178. ORDER BY "uicol"."COLUMN_POSITION" ASC
  179. SQL;
  180. $resolvedName = $this->resolveTableName($tableName);
  181. $indexes = $this->db->createCommand($sql, [
  182. ':schemaName' => $resolvedName->schemaName,
  183. ':tableName' => $resolvedName->name,
  184. ])->queryAll();
  185. $indexes = $this->normalizePdoRowKeyCase($indexes, true);
  186. $indexes = ArrayHelper::index($indexes, null, 'name');
  187. $result = [];
  188. foreach ($indexes as $name => $index) {
  189. $result[] = new IndexConstraint([
  190. 'isPrimary' => (bool) $index[0]['index_is_primary'],
  191. 'isUnique' => (bool) $index[0]['index_is_unique'],
  192. 'name' => $name,
  193. 'columnNames' => ArrayHelper::getColumn($index, 'column_name'),
  194. ]);
  195. }
  196. return $result;
  197. }
  198. /**
  199. * {@inheritdoc}
  200. */
  201. protected function loadTableUniques($tableName)
  202. {
  203. return $this->loadTableConstraints($tableName, 'uniques');
  204. }
  205. /**
  206. * {@inheritdoc}
  207. */
  208. protected function loadTableChecks($tableName)
  209. {
  210. return $this->loadTableConstraints($tableName, 'checks');
  211. }
  212. /**
  213. * {@inheritdoc}
  214. * @throws NotSupportedException if this method is called.
  215. */
  216. protected function loadTableDefaultValues($tableName)
  217. {
  218. throw new NotSupportedException('Oracle does not support default value constraints.');
  219. }
  220. /**
  221. * {@inheritdoc}
  222. */
  223. public function releaseSavepoint($name)
  224. {
  225. // does nothing as Oracle does not support this
  226. }
  227. /**
  228. * {@inheritdoc}
  229. */
  230. public function quoteSimpleTableName($name)
  231. {
  232. return strpos($name, '"') !== false ? $name : '"' . $name . '"';
  233. }
  234. /**
  235. * {@inheritdoc}
  236. */
  237. public function createQueryBuilder()
  238. {
  239. return Yii::createObject(QueryBuilder::className(), [$this->db]);
  240. }
  241. /**
  242. * {@inheritdoc}
  243. */
  244. public function createColumnSchemaBuilder($type, $length = null)
  245. {
  246. return Yii::createObject(ColumnSchemaBuilder::className(), [$type, $length]);
  247. }
  248. /**
  249. * Resolves the table name and schema name (if any).
  250. *
  251. * @param TableSchema $table the table metadata object
  252. * @param string $name the table name
  253. */
  254. protected function resolveTableNames($table, $name)
  255. {
  256. $parts = explode('.', str_replace('"', '', $name));
  257. if (isset($parts[1])) {
  258. $table->schemaName = $parts[0];
  259. $table->name = $parts[1];
  260. } else {
  261. $table->schemaName = $this->defaultSchema;
  262. $table->name = $name;
  263. }
  264. $table->fullName = $table->schemaName !== $this->defaultSchema ? $table->schemaName . '.' . $table->name : $table->name;
  265. }
  266. /**
  267. * Collects the table column metadata.
  268. * @param TableSchema $table the table schema
  269. * @return bool whether the table exists
  270. */
  271. protected function findColumns($table)
  272. {
  273. $sql = <<<'SQL'
  274. SELECT
  275. A.COLUMN_NAME,
  276. A.DATA_TYPE,
  277. A.DATA_PRECISION,
  278. A.DATA_SCALE,
  279. (
  280. CASE A.CHAR_USED WHEN 'C' THEN A.CHAR_LENGTH
  281. ELSE A.DATA_LENGTH
  282. END
  283. ) AS DATA_LENGTH,
  284. A.NULLABLE,
  285. A.DATA_DEFAULT,
  286. COM.COMMENTS AS COLUMN_COMMENT
  287. FROM ALL_TAB_COLUMNS A
  288. INNER JOIN ALL_OBJECTS B ON B.OWNER = A.OWNER AND LTRIM(B.OBJECT_NAME) = LTRIM(A.TABLE_NAME)
  289. 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)
  290. WHERE
  291. A.OWNER = :schemaName
  292. AND B.OBJECT_TYPE IN ('TABLE', 'VIEW', 'MATERIALIZED VIEW')
  293. AND B.OBJECT_NAME = :tableName
  294. ORDER BY A.COLUMN_ID
  295. SQL;
  296. try {
  297. $columns = $this->db->createCommand($sql, [
  298. ':tableName' => $table->name,
  299. ':schemaName' => $table->schemaName,
  300. ])->queryAll();
  301. } catch (\Exception $e) {
  302. return false;
  303. }
  304. if (empty($columns)) {
  305. return false;
  306. }
  307. foreach ($columns as $column) {
  308. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  309. $column = array_change_key_case($column, CASE_UPPER);
  310. }
  311. $c = $this->createColumn($column);
  312. $table->columns[$c->name] = $c;
  313. }
  314. return true;
  315. }
  316. /**
  317. * Sequence name of table.
  318. *
  319. * @param string $tableName
  320. * @internal param \yii\db\TableSchema $table->name the table schema
  321. * @return string|null whether the sequence exists
  322. */
  323. protected function getTableSequenceName($tableName)
  324. {
  325. $sequenceNameSql = <<<'SQL'
  326. SELECT
  327. UD.REFERENCED_NAME AS SEQUENCE_NAME
  328. FROM USER_DEPENDENCIES UD
  329. JOIN USER_TRIGGERS UT ON (UT.TRIGGER_NAME = UD.NAME)
  330. WHERE
  331. UT.TABLE_NAME = :tableName
  332. AND UD.TYPE = 'TRIGGER'
  333. AND UD.REFERENCED_TYPE = 'SEQUENCE'
  334. SQL;
  335. $sequenceName = $this->db->createCommand($sequenceNameSql, [':tableName' => $tableName])->queryScalar();
  336. return $sequenceName === false ? null : $sequenceName;
  337. }
  338. /**
  339. * @Overrides method in class 'Schema'
  340. * @see https://www.php.net/manual/en/function.PDO-lastInsertId.php -> Oracle does not support this
  341. *
  342. * Returns the ID of the last inserted row or sequence value.
  343. * @param string $sequenceName name of the sequence object (required by some DBMS)
  344. * @return string the row ID of the last row inserted, or the last value retrieved from the sequence object
  345. * @throws InvalidCallException if the DB connection is not active
  346. */
  347. public function getLastInsertID($sequenceName = '')
  348. {
  349. if ($this->db->isActive) {
  350. // get the last insert id from the master connection
  351. $sequenceName = $this->quoteSimpleTableName($sequenceName);
  352. return $this->db->useMaster(function (Connection $db) use ($sequenceName) {
  353. return $db->createCommand("SELECT {$sequenceName}.CURRVAL FROM DUAL")->queryScalar();
  354. });
  355. } else {
  356. throw new InvalidCallException('DB Connection is not active.');
  357. }
  358. }
  359. /**
  360. * Creates ColumnSchema instance.
  361. *
  362. * @param array $column
  363. * @return ColumnSchema
  364. */
  365. protected function createColumn($column)
  366. {
  367. $c = $this->createColumnSchema();
  368. $c->name = $column['COLUMN_NAME'];
  369. $c->allowNull = $column['NULLABLE'] === 'Y';
  370. $c->comment = $column['COLUMN_COMMENT'] === null ? '' : $column['COLUMN_COMMENT'];
  371. $c->isPrimaryKey = false;
  372. $this->extractColumnType($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
  373. $this->extractColumnSize($c, $column['DATA_TYPE'], $column['DATA_PRECISION'], $column['DATA_SCALE'], $column['DATA_LENGTH']);
  374. $c->phpType = $this->getColumnPhpType($c);
  375. if (!$c->isPrimaryKey) {
  376. if (stripos((string) $column['DATA_DEFAULT'], 'timestamp') !== false) {
  377. $c->defaultValue = null;
  378. } else {
  379. $defaultValue = (string) $column['DATA_DEFAULT'];
  380. if ($c->type === 'timestamp' && $defaultValue === 'CURRENT_TIMESTAMP') {
  381. $c->defaultValue = new Expression('CURRENT_TIMESTAMP');
  382. } else {
  383. if ($defaultValue !== null) {
  384. if (
  385. strlen($defaultValue) > 2
  386. && strncmp($defaultValue, "'", 1) === 0
  387. && substr($defaultValue, -1) === "'"
  388. ) {
  389. $defaultValue = substr($defaultValue, 1, -1);
  390. } else {
  391. $defaultValue = trim($defaultValue);
  392. }
  393. }
  394. $c->defaultValue = $c->phpTypecast($defaultValue);
  395. }
  396. }
  397. }
  398. return $c;
  399. }
  400. /**
  401. * Finds constraints and fills them into TableSchema object passed.
  402. * @param TableSchema $table
  403. */
  404. protected function findConstraints($table)
  405. {
  406. $sql = <<<'SQL'
  407. SELECT
  408. /*+ PUSH_PRED(C) PUSH_PRED(D) PUSH_PRED(E) */
  409. D.CONSTRAINT_NAME,
  410. D.CONSTRAINT_TYPE,
  411. C.COLUMN_NAME,
  412. C.POSITION,
  413. D.R_CONSTRAINT_NAME,
  414. E.TABLE_NAME AS TABLE_REF,
  415. F.COLUMN_NAME AS COLUMN_REF,
  416. C.TABLE_NAME
  417. FROM ALL_CONS_COLUMNS C
  418. INNER JOIN ALL_CONSTRAINTS D ON D.OWNER = C.OWNER AND D.CONSTRAINT_NAME = C.CONSTRAINT_NAME
  419. LEFT JOIN ALL_CONSTRAINTS E ON E.OWNER = D.R_OWNER AND E.CONSTRAINT_NAME = D.R_CONSTRAINT_NAME
  420. LEFT JOIN ALL_CONS_COLUMNS F ON F.OWNER = E.OWNER AND F.CONSTRAINT_NAME = E.CONSTRAINT_NAME AND F.POSITION = C.POSITION
  421. WHERE
  422. C.OWNER = :schemaName
  423. AND C.TABLE_NAME = :tableName
  424. ORDER BY D.CONSTRAINT_NAME, C.POSITION
  425. SQL;
  426. $command = $this->db->createCommand($sql, [
  427. ':tableName' => $table->name,
  428. ':schemaName' => $table->schemaName,
  429. ]);
  430. $constraints = [];
  431. foreach ($command->queryAll() as $row) {
  432. if ($this->db->slavePdo->getAttribute(\PDO::ATTR_CASE) === \PDO::CASE_LOWER) {
  433. $row = array_change_key_case($row, CASE_UPPER);
  434. }
  435. if ($row['CONSTRAINT_TYPE'] === 'P') {
  436. $table->columns[$row['COLUMN_NAME']]->isPrimaryKey = true;
  437. $table->primaryKey[] = $row['COLUMN_NAME'];
  438. if (empty($table->sequenceName)) {
  439. $table->sequenceName = $this->getTableSequenceName($table->name);
  440. }
  441. }
  442. if ($row['CONSTRAINT_TYPE'] !== 'R') {
  443. // this condition is not checked in SQL WHERE because of an Oracle Bug:
  444. // see https://github.com/yiisoft/yii2/pull/8844
  445. continue;
  446. }
  447. $name = $row['CONSTRAINT_NAME'];
  448. if (!isset($constraints[$name])) {
  449. $constraints[$name] = [
  450. 'tableName' => $row['TABLE_REF'],
  451. 'columns' => [],
  452. ];
  453. }
  454. $constraints[$name]['columns'][$row['COLUMN_NAME']] = $row['COLUMN_REF'];
  455. }
  456. foreach ($constraints as $constraint) {
  457. $name = current(array_keys($constraint));
  458. $table->foreignKeys[$name] = array_merge([$constraint['tableName']], $constraint['columns']);
  459. }
  460. }
  461. /**
  462. * Returns all unique indexes for the given table.
  463. * Each array element is of the following structure:.
  464. *
  465. * ```php
  466. * [
  467. * 'IndexName1' => ['col1' [, ...]],
  468. * 'IndexName2' => ['col2' [, ...]],
  469. * ]
  470. * ```
  471. *
  472. * @param TableSchema $table the table metadata
  473. * @return array all unique indexes for the given table.
  474. * @since 2.0.4
  475. */
  476. public function findUniqueIndexes($table)
  477. {
  478. $query = <<<'SQL'
  479. SELECT
  480. DIC.INDEX_NAME,
  481. DIC.COLUMN_NAME
  482. FROM ALL_INDEXES DI
  483. INNER JOIN ALL_IND_COLUMNS DIC ON DI.TABLE_NAME = DIC.TABLE_NAME AND DI.INDEX_NAME = DIC.INDEX_NAME
  484. WHERE
  485. DI.UNIQUENESS = 'UNIQUE'
  486. AND DIC.TABLE_OWNER = :schemaName
  487. AND DIC.TABLE_NAME = :tableName
  488. ORDER BY DIC.TABLE_NAME, DIC.INDEX_NAME, DIC.COLUMN_POSITION
  489. SQL;
  490. $result = [];
  491. $command = $this->db->createCommand($query, [
  492. ':tableName' => $table->name,
  493. ':schemaName' => $table->schemaName,
  494. ]);
  495. foreach ($command->queryAll() as $row) {
  496. $result[$row['INDEX_NAME']][] = $row['COLUMN_NAME'];
  497. }
  498. return $result;
  499. }
  500. /**
  501. * Extracts the data types for the given column.
  502. * @param ColumnSchema $column
  503. * @param string $dbType DB type
  504. * @param string $precision total number of digits.
  505. * This parameter is available since version 2.0.4.
  506. * @param string $scale number of digits on the right of the decimal separator.
  507. * This parameter is available since version 2.0.4.
  508. * @param string $length length for character types.
  509. * This parameter is available since version 2.0.4.
  510. */
  511. protected function extractColumnType($column, $dbType, $precision, $scale, $length)
  512. {
  513. $column->dbType = $dbType;
  514. if (strpos($dbType, 'FLOAT') !== false || strpos($dbType, 'DOUBLE') !== false) {
  515. $column->type = 'double';
  516. } elseif (strpos($dbType, 'NUMBER') !== false) {
  517. if ($scale === null || $scale > 0) {
  518. $column->type = 'decimal';
  519. } else {
  520. $column->type = 'integer';
  521. }
  522. } elseif (strpos($dbType, 'INTEGER') !== false) {
  523. $column->type = 'integer';
  524. } elseif (strpos($dbType, 'BLOB') !== false) {
  525. $column->type = 'binary';
  526. } elseif (strpos($dbType, 'CLOB') !== false) {
  527. $column->type = 'text';
  528. } elseif (strpos($dbType, 'TIMESTAMP') !== false) {
  529. $column->type = 'timestamp';
  530. } else {
  531. $column->type = 'string';
  532. }
  533. }
  534. /**
  535. * Extracts size, precision and scale information from column's DB type.
  536. * @param ColumnSchema $column
  537. * @param string $dbType the column's DB type
  538. * @param string $precision total number of digits.
  539. * This parameter is available since version 2.0.4.
  540. * @param string $scale number of digits on the right of the decimal separator.
  541. * This parameter is available since version 2.0.4.
  542. * @param string $length length for character types.
  543. * This parameter is available since version 2.0.4.
  544. */
  545. protected function extractColumnSize($column, $dbType, $precision, $scale, $length)
  546. {
  547. $column->size = trim((string) $length) === '' ? null : (int) $length;
  548. $column->precision = trim((string) $precision) === '' ? null : (int) $precision;
  549. $column->scale = trim((string) $scale) === '' ? null : (int) $scale;
  550. }
  551. /**
  552. * {@inheritdoc}
  553. */
  554. public function insert($table, $columns)
  555. {
  556. $params = [];
  557. $returnParams = [];
  558. $sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
  559. $tableSchema = $this->getTableSchema($table);
  560. $returnColumns = $tableSchema->primaryKey;
  561. if (!empty($returnColumns)) {
  562. $columnSchemas = $tableSchema->columns;
  563. $returning = [];
  564. foreach ((array) $returnColumns as $name) {
  565. $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams));
  566. $returnParams[$phName] = [
  567. 'column' => $name,
  568. 'value' => '',
  569. ];
  570. if (!isset($columnSchemas[$name]) || $columnSchemas[$name]->phpType !== 'integer') {
  571. $returnParams[$phName]['dataType'] = \PDO::PARAM_STR;
  572. } else {
  573. $returnParams[$phName]['dataType'] = \PDO::PARAM_INT;
  574. }
  575. $returnParams[$phName]['size'] = isset($columnSchemas[$name]->size) ? $columnSchemas[$name]->size : -1;
  576. $returning[] = $this->quoteColumnName($name);
  577. }
  578. $sql .= ' RETURNING ' . implode(', ', $returning) . ' INTO ' . implode(', ', array_keys($returnParams));
  579. }
  580. $command = $this->db->createCommand($sql, $params);
  581. $command->prepare(false);
  582. foreach ($returnParams as $name => &$value) {
  583. $command->pdoStatement->bindParam($name, $value['value'], $value['dataType'], $value['size']);
  584. }
  585. if (!$command->execute()) {
  586. return false;
  587. }
  588. $result = [];
  589. foreach ($returnParams as $value) {
  590. $result[$value['column']] = $value['value'];
  591. }
  592. return $result;
  593. }
  594. /**
  595. * Loads multiple types of constraints and returns the specified ones.
  596. * @param string $tableName table name.
  597. * @param string $returnType return type:
  598. * - primaryKey
  599. * - foreignKeys
  600. * - uniques
  601. * - checks
  602. * @return mixed constraints.
  603. */
  604. private function loadTableConstraints($tableName, $returnType)
  605. {
  606. static $sql = <<<'SQL'
  607. SELECT
  608. /*+ PUSH_PRED("uc") PUSH_PRED("uccol") PUSH_PRED("fuc") */
  609. "uc"."CONSTRAINT_NAME" AS "name",
  610. "uccol"."COLUMN_NAME" AS "column_name",
  611. "uc"."CONSTRAINT_TYPE" AS "type",
  612. "fuc"."OWNER" AS "foreign_table_schema",
  613. "fuc"."TABLE_NAME" AS "foreign_table_name",
  614. "fuccol"."COLUMN_NAME" AS "foreign_column_name",
  615. "uc"."DELETE_RULE" AS "on_delete",
  616. "uc"."SEARCH_CONDITION" AS "check_expr"
  617. FROM "USER_CONSTRAINTS" "uc"
  618. INNER JOIN "USER_CONS_COLUMNS" "uccol"
  619. ON "uccol"."OWNER" = "uc"."OWNER" AND "uccol"."CONSTRAINT_NAME" = "uc"."CONSTRAINT_NAME"
  620. LEFT JOIN "USER_CONSTRAINTS" "fuc"
  621. ON "fuc"."OWNER" = "uc"."R_OWNER" AND "fuc"."CONSTRAINT_NAME" = "uc"."R_CONSTRAINT_NAME"
  622. LEFT JOIN "USER_CONS_COLUMNS" "fuccol"
  623. ON "fuccol"."OWNER" = "fuc"."OWNER" AND "fuccol"."CONSTRAINT_NAME" = "fuc"."CONSTRAINT_NAME" AND "fuccol"."POSITION" = "uccol"."POSITION"
  624. WHERE "uc"."OWNER" = :schemaName AND "uc"."TABLE_NAME" = :tableName
  625. ORDER BY "uccol"."POSITION" ASC
  626. SQL;
  627. $resolvedName = $this->resolveTableName($tableName);
  628. $constraints = $this->db->createCommand($sql, [
  629. ':schemaName' => $resolvedName->schemaName,
  630. ':tableName' => $resolvedName->name,
  631. ])->queryAll();
  632. $constraints = $this->normalizePdoRowKeyCase($constraints, true);
  633. $constraints = ArrayHelper::index($constraints, null, ['type', 'name']);
  634. $result = [
  635. 'primaryKey' => null,
  636. 'foreignKeys' => [],
  637. 'uniques' => [],
  638. 'checks' => [],
  639. ];
  640. foreach ($constraints as $type => $names) {
  641. foreach ($names as $name => $constraint) {
  642. switch ($type) {
  643. case 'P':
  644. $result['primaryKey'] = new Constraint([
  645. 'name' => $name,
  646. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  647. ]);
  648. break;
  649. case 'R':
  650. $result['foreignKeys'][] = new ForeignKeyConstraint([
  651. 'name' => $name,
  652. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  653. 'foreignSchemaName' => $constraint[0]['foreign_table_schema'],
  654. 'foreignTableName' => $constraint[0]['foreign_table_name'],
  655. 'foreignColumnNames' => ArrayHelper::getColumn($constraint, 'foreign_column_name'),
  656. 'onDelete' => $constraint[0]['on_delete'],
  657. 'onUpdate' => null,
  658. ]);
  659. break;
  660. case 'U':
  661. $result['uniques'][] = new Constraint([
  662. 'name' => $name,
  663. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  664. ]);
  665. break;
  666. case 'C':
  667. $result['checks'][] = new CheckConstraint([
  668. 'name' => $name,
  669. 'columnNames' => ArrayHelper::getColumn($constraint, 'column_name'),
  670. 'expression' => $constraint[0]['check_expr'],
  671. ]);
  672. break;
  673. }
  674. }
  675. }
  676. foreach ($result as $type => $data) {
  677. $this->setTableMetadata($tableName, $type, $data);
  678. }
  679. return $result[$returnType];
  680. }
  681. }