COciSchema.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. <?php
  2. /**
  3. * COciSchema class file.
  4. *
  5. * @author Ricardo Grana <rickgrana@yahoo.com.br>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * COciSchema is the class for retrieving metadata information from an Oracle database.
  12. *
  13. * @property string $defaultSchema Default schema.
  14. *
  15. * @author Ricardo Grana <rickgrana@yahoo.com.br>
  16. * @package system.db.schema.oci
  17. */
  18. class COciSchema extends CDbSchema
  19. {
  20. private $_defaultSchema = '';
  21. /**
  22. * @var array the abstract column types mapped to physical column types.
  23. * @since 1.1.6
  24. */
  25. public $columnTypes=array(
  26. 'pk' => 'NUMBER(10) NOT NULL PRIMARY KEY',
  27. 'bigpk' => 'NUMBER(20) NOT NULL PRIMARY KEY',
  28. 'string' => 'VARCHAR2(255)',
  29. 'text' => 'CLOB',
  30. 'integer' => 'NUMBER(10)',
  31. 'bigint' => 'NUMBER(20)',
  32. 'float' => 'NUMBER',
  33. 'decimal' => 'NUMBER',
  34. 'datetime' => 'TIMESTAMP',
  35. 'timestamp' => 'TIMESTAMP',
  36. 'time' => 'TIMESTAMP',
  37. 'date' => 'DATE',
  38. 'binary' => 'BLOB',
  39. 'boolean' => 'NUMBER(1)',
  40. 'money' => 'NUMBER(19,4)',
  41. );
  42. /**
  43. * Quotes a table name for use in a query.
  44. * A simple table name does not schema prefix.
  45. * @param string $name table name
  46. * @return string the properly quoted table name
  47. * @since 1.1.6
  48. */
  49. public function quoteSimpleTableName($name)
  50. {
  51. return '"'.$name.'"';
  52. }
  53. /**
  54. * Quotes a column name for use in a query.
  55. * A simple column name does not contain prefix.
  56. * @param string $name column name
  57. * @return string the properly quoted column name
  58. * @since 1.1.6
  59. */
  60. public function quoteSimpleColumnName($name)
  61. {
  62. return '"'.$name.'"';
  63. }
  64. /**
  65. * Creates a command builder for the database.
  66. * This method may be overridden by child classes to create a DBMS-specific command builder.
  67. * @return CDbCommandBuilder command builder instance
  68. */
  69. protected function createCommandBuilder()
  70. {
  71. return new COciCommandBuilder($this);
  72. }
  73. /**
  74. * @param string $schema default schema.
  75. */
  76. public function setDefaultSchema($schema)
  77. {
  78. $this->_defaultSchema=$schema;
  79. }
  80. /**
  81. * @return string default schema.
  82. */
  83. public function getDefaultSchema()
  84. {
  85. if (!strlen($this->_defaultSchema))
  86. {
  87. $this->setDefaultSchema(strtoupper($this->getDbConnection()->username));
  88. }
  89. return $this->_defaultSchema;
  90. }
  91. /**
  92. * @param string $table table name with optional schema name prefix, uses default schema name prefix is not provided.
  93. * @return array tuple as ($schemaName,$tableName)
  94. */
  95. protected function getSchemaTableName($table)
  96. {
  97. $table = strtoupper($table);
  98. if(count($parts= explode('.', str_replace('"','',$table))) > 1)
  99. return array($parts[0], $parts[1]);
  100. else
  101. return array($this->getDefaultSchema(),$parts[0]);
  102. }
  103. /**
  104. * Loads the metadata for the specified table.
  105. * @param string $name table name
  106. * @return CDbTableSchema driver dependent table metadata.
  107. */
  108. protected function loadTable($name)
  109. {
  110. $table=new COciTableSchema;
  111. $this->resolveTableNames($table,$name);
  112. if(!$this->findColumns($table))
  113. return null;
  114. $this->findConstraints($table);
  115. return $table;
  116. }
  117. /**
  118. * Generates various kinds of table names.
  119. * @param COciTableSchema $table the table instance
  120. * @param string $name the unquoted table name
  121. */
  122. protected function resolveTableNames($table,$name)
  123. {
  124. $parts=explode('.',str_replace('"','',$name));
  125. if(isset($parts[1]))
  126. {
  127. $schemaName=$parts[0];
  128. $tableName=$parts[1];
  129. }
  130. else
  131. {
  132. $schemaName=$this->getDefaultSchema();
  133. $tableName=$parts[0];
  134. }
  135. $table->name=$tableName;
  136. $table->schemaName=$schemaName;
  137. if($schemaName===$this->getDefaultSchema())
  138. $table->rawName=$this->quoteTableName($tableName);
  139. else
  140. $table->rawName=$this->quoteTableName($schemaName).'.'.$this->quoteTableName($tableName);
  141. }
  142. /**
  143. * Collects the table column metadata.
  144. * @param COciTableSchema $table the table metadata
  145. * @return boolean whether the table exists in the database
  146. */
  147. protected function findColumns($table)
  148. {
  149. $schemaName=$table->schemaName;
  150. $tableName=$table->name;
  151. $sql=<<<EOD
  152. SELECT a.column_name, a.data_type ||
  153. case
  154. when data_precision is not null
  155. then '(' || a.data_precision ||
  156. case when a.data_scale > 0 then ',' || a.data_scale else '' end
  157. || ')'
  158. when data_type = 'DATE' then ''
  159. when data_type = 'NUMBER' then ''
  160. else '(' || to_char(a.data_length) || ')'
  161. end as data_type,
  162. a.nullable, a.data_default,
  163. ( SELECT D.constraint_type
  164. FROM ALL_CONS_COLUMNS C
  165. inner join ALL_constraints D on D.OWNER = C.OWNER and D.constraint_name = C.constraint_name
  166. WHERE C.OWNER = B.OWNER
  167. and C.table_name = B.object_name
  168. and C.column_name = A.column_name
  169. and D.constraint_type = 'P') as Key,
  170. com.comments as column_comment
  171. FROM ALL_TAB_COLUMNS A
  172. inner join ALL_OBJECTS B ON b.owner = a.owner and ltrim(B.OBJECT_NAME) = ltrim(A.TABLE_NAME)
  173. 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)
  174. WHERE
  175. a.owner = '{$schemaName}'
  176. and (b.object_type = 'TABLE' or b.object_type = 'VIEW')
  177. and b.object_name = '{$tableName}'
  178. ORDER by a.column_id
  179. EOD;
  180. $command=$this->getDbConnection()->createCommand($sql);
  181. if(($columns=$command->queryAll())===array()){
  182. return false;
  183. }
  184. foreach($columns as $column)
  185. {
  186. $c=$this->createColumn($column);
  187. $table->columns[$c->name]=$c;
  188. if($c->isPrimaryKey)
  189. {
  190. if($table->primaryKey===null)
  191. $table->primaryKey=$c->name;
  192. elseif(is_string($table->primaryKey))
  193. $table->primaryKey=array($table->primaryKey,$c->name);
  194. else
  195. $table->primaryKey[]=$c->name;
  196. $table->sequenceName='';
  197. $c->autoIncrement=true;
  198. }
  199. }
  200. return true;
  201. }
  202. /**
  203. * Creates a table column.
  204. * @param array $column column metadata
  205. * @return CDbColumnSchema normalized column metadata
  206. */
  207. protected function createColumn($column)
  208. {
  209. $c=new COciColumnSchema;
  210. $c->name=$column['COLUMN_NAME'];
  211. $c->rawName=$this->quoteColumnName($c->name);
  212. $c->allowNull=$column['NULLABLE']==='Y';
  213. $c->isPrimaryKey=strpos($column['KEY'],'P')!==false;
  214. $c->isForeignKey=false;
  215. $c->init($column['DATA_TYPE'],$column['DATA_DEFAULT']);
  216. $c->comment=$column['COLUMN_COMMENT']===null ? '' : $column['COLUMN_COMMENT'];
  217. return $c;
  218. }
  219. /**
  220. * Collects the primary and foreign key column details for the given table.
  221. * @param COciTableSchema $table the table metadata
  222. */
  223. protected function findConstraints($table)
  224. {
  225. $sql=<<<EOD
  226. SELECT D.constraint_type as CONSTRAINT_TYPE, C.COLUMN_NAME, C.position, D.r_constraint_name,
  227. E.table_name as table_ref, f.column_name as column_ref,
  228. C.table_name
  229. FROM ALL_CONS_COLUMNS C
  230. inner join ALL_constraints D on D.OWNER = C.OWNER and D.constraint_name = C.constraint_name
  231. left join ALL_constraints E on E.OWNER = D.r_OWNER and E.constraint_name = D.r_constraint_name
  232. left join ALL_cons_columns F on F.OWNER = E.OWNER and F.constraint_name = E.constraint_name and F.position = c.position
  233. WHERE C.OWNER = '{$table->schemaName}'
  234. and C.table_name = '{$table->name}'
  235. and D.constraint_type <> 'P'
  236. order by d.constraint_name, c.position
  237. EOD;
  238. $command=$this->getDbConnection()->createCommand($sql);
  239. foreach($command->queryAll() as $row)
  240. {
  241. if($row['CONSTRAINT_TYPE']==='R') // foreign key
  242. {
  243. $name = $row["COLUMN_NAME"];
  244. $table->foreignKeys[$name]=array($row["TABLE_REF"], $row["COLUMN_REF"]);
  245. if(isset($table->columns[$name]))
  246. $table->columns[$name]->isForeignKey=true;
  247. }
  248. }
  249. }
  250. /**
  251. * Returns all table names in the database.
  252. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  253. * If not empty, the returned table names will be prefixed with the schema name.
  254. * @return array all table names in the database.
  255. */
  256. protected function findTableNames($schema='')
  257. {
  258. if($schema==='')
  259. {
  260. $sql=<<<EOD
  261. SELECT table_name, '{$schema}' as table_schema FROM user_tables
  262. EOD;
  263. $command=$this->getDbConnection()->createCommand($sql);
  264. }
  265. else
  266. {
  267. $sql=<<<EOD
  268. SELECT object_name as table_name, owner as table_schema FROM all_objects
  269. WHERE object_type = 'TABLE' AND owner=:schema
  270. EOD;
  271. $command=$this->getDbConnection()->createCommand($sql);
  272. $command->bindParam(':schema',$schema);
  273. }
  274. $rows=$command->queryAll();
  275. $names=array();
  276. foreach($rows as $row)
  277. {
  278. if($schema===$this->getDefaultSchema() || $schema==='')
  279. $names[]=$row['TABLE_NAME'];
  280. else
  281. $names[]=$row['TABLE_SCHEMA'].'.'.$row['TABLE_NAME'];
  282. }
  283. return $names;
  284. }
  285. /**
  286. * Builds a SQL statement for renaming a DB table.
  287. * @param string $table the table to be renamed. The name will be properly quoted by the method.
  288. * @param string $newName the new table name. The name will be properly quoted by the method.
  289. * @return string the SQL statement for renaming a DB table.
  290. * @since 1.1.6
  291. */
  292. public function renameTable($table, $newName)
  293. {
  294. return 'ALTER TABLE ' . $this->quoteTableName($table) . ' RENAME TO ' . $this->quoteTableName($newName);
  295. }
  296. /**
  297. * Builds a SQL statement for changing the definition of a column.
  298. * @param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
  299. * @param string $column the name of the column to be changed. The name will be properly quoted by the method.
  300. * @param string $type the new column type. The {@link getColumnType} method will be invoked to convert abstract column type (if any)
  301. * into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
  302. * For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
  303. * @return string the SQL statement for changing the definition of a column.
  304. * @since 1.1.6
  305. */
  306. public function alterColumn($table, $column, $type)
  307. {
  308. $type=$this->getColumnType($type);
  309. $sql='ALTER TABLE ' . $this->quoteTableName($table) . ' MODIFY '
  310. . $this->quoteColumnName($column) . ' '
  311. . $this->getColumnType($type);
  312. return $sql;
  313. }
  314. /**
  315. * Builds a SQL statement for dropping an index.
  316. * @param string $name the name of the index to be dropped. The name will be properly quoted by the method.
  317. * @param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
  318. * @return string the SQL statement for dropping an index.
  319. * @since 1.1.6
  320. */
  321. public function dropIndex($name, $table)
  322. {
  323. return 'DROP INDEX '.$this->quoteTableName($name);
  324. }
  325. /**
  326. * Resets the sequence value of a table's primary key.
  327. * The sequence will be reset such that the primary key of the next new row inserted
  328. * will have the specified value or max value of a primary key plus one (i.e. sequence trimming).
  329. *
  330. * Note, behavior of this method has changed since 1.1.14 release. Please refer to the following
  331. * issue for more details: {@link https://github.com/yiisoft/yii/issues/2241}
  332. *
  333. * @param CDbTableSchema $table the table schema whose primary key sequence will be reset
  334. * @param integer|null $value the value for the primary key of the next new row inserted.
  335. * If this is not set, the next new row's primary key will have the max value of a primary
  336. * key plus one (i.e. sequence trimming).
  337. * @since 1.1.13
  338. */
  339. public function resetSequence($table,$value=null)
  340. {
  341. if($table->sequenceName===null)
  342. return;
  343. if($value!==null)
  344. $value=(int)$value;
  345. else
  346. {
  347. $value=(int)$this->getDbConnection()
  348. ->createCommand("SELECT MAX(\"{$table->primaryKey}\") FROM {$table->rawName}")
  349. ->queryScalar();
  350. $value++;
  351. }
  352. $this->getDbConnection()
  353. ->createCommand("DROP SEQUENCE \"{$table->name}_SEQ\"")
  354. ->execute();
  355. $this->getDbConnection()
  356. ->createCommand("CREATE SEQUENCE \"{$table->name}_SEQ\" START WITH {$value} INCREMENT BY 1 NOMAXVALUE NOCACHE")
  357. ->execute();
  358. }
  359. /**
  360. * Enables or disables integrity check.
  361. * @param boolean $check whether to turn on or off the integrity check.
  362. * @param string $schema the schema of the tables. Defaults to empty string, meaning the current or default schema.
  363. * @since 1.1.14
  364. */
  365. public function checkIntegrity($check=true,$schema='')
  366. {
  367. if($schema==='')
  368. $schema=$this->getDefaultSchema();
  369. $mode=$check ? 'ENABLE' : 'DISABLE';
  370. foreach($this->getTableNames($schema) as $table)
  371. {
  372. $constraints=$this->getDbConnection()
  373. ->createCommand("SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME=:t AND OWNER=:o")
  374. ->queryColumn(array(':t'=>$table,':o'=>$schema));
  375. foreach($constraints as $constraint)
  376. $this->getDbConnection()
  377. ->createCommand("ALTER TABLE \"{$schema}\".\"{$table}\" {$mode} CONSTRAINT \"{$constraint}\"")
  378. ->execute();
  379. }
  380. }
  381. }