Schema.php 24 KB

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