Blame view

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