COciSchema.php 13 KB

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