# Source for file Oracle.php

Documentation is available at Oracle.php

1. <?php
2. /*
3. * $Id: Oracle.php 2288 2007-08-29 21:51:49Z Jonathan.Wage $
4. *
5. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16. *
17. * This software consists of voluntary contributions made by many individuals
18. * and is licensed under the LGPL. For more information, see
19. * <http://www.phpdoctrine.com>.
20. */
21. Doctrine::autoload('Doctrine_Export');
22. /**
23. * Doctrine_Export_Oracle
24. *
25. * @package Doctrine
26. * @author Konsta Vesterinen <kvesteri@cc.hut.fi>
27. * @author Lukas Smith <smith@pooteeweet.org> (PEAR MDB2 library)
28. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
29. * @category Object Relational Mapping
30. * @link www.phpdoctrine.com
31. * @since 1.0
32. * @version $Revision: 2288 $
33. */
34. class Doctrine_Export_Oracle extends Doctrine_Export
35. {
36. /**
37. * create a new database
38. *
39. * @param object $db database object that is extended by this class
40. * @param string $name name of the database that should be created
41. * @return mixed MDB2_OK on success, a MDB2 error on failure
42. * @access public
43. */
44. public function createDatabase($name)
45. {
46. if ( ! $this->conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE))
47. throw new Doctrine_Export_Exception('database creation is only supported if the "emulate_database" attribute is enabled');
49. $username = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name);
50. $password = $this->conn->dsn['password'] ? $this->conn->dsn['password'] : $name;
52. $tablespace = $this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT)
53. ? ' DEFAULT TABLESPACE '.$this->conn->options['default_tablespace'] : '';
55. $query = 'CREATE USER ' . $username . ' IDENTIFIED BY ' . $password . $tablespace;
56. $result = $this->conn->exec($query);
58. try {
59. $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO ' . $username;
60. $result = $this->conn->exec($query);
61. } catch (Exception $e) {
62. $query = 'DROP USER '.$username.' CASCADE';
63. $result2 = $this->conn->exec($query);
64. }
65. return true;
66. }
67. /**
68. * drop an existing database
69. *
70. * @param object $this->conn database object that is extended by this class
71. * @param string $name name of the database that should be dropped
72. * @return mixed MDB2_OK on success, a MDB2 error on failure
73. * @access public
74. */
75. public function dropDatabase($name)
76. {
77. if ( ! $this->conn->getAttribute(Doctrine::ATTR_EMULATE_DATABASE))
78. throw new Doctrine_Export_Exception('database dropping is only supported if the
79. "emulate_database" option is enabled');
81. $username = sprintf($this->conn->getAttribute(Doctrine::ATTR_DB_NAME_FORMAT), $name);
83. return $this->conn->exec('DROP USER ' . $username . ' CASCADE');
84. }
85. /**
86. * add an autoincrement sequence + trigger
87. *
88. * @param string $name name of the PK field
89. * @param string $table name of the table
90. * @param string $start start value for the sequence
91. * @return mixed MDB2_OK on success, a MDB2 error on failure
92. * @access private
93. */
94. public function _makeAutoincrement($name, $table, $start = 1)
95. {
96. $sql = array();
97. $table = strtoupper($table);
98. $indexName = $table . '_AI_PK';
99. $definition = array(
100. 'primary' => true,
101. 'fields' => array($name => true),
102. );
104. $sql[] = $this->createConstraintSql($table, $indexName, $definition);
106. if (is_null($start)) {
107. $query = 'SELECT MAX(' . $this->conn->quoteIdentifier($name, true) . ') FROM ' . $this->conn->quoteIdentifier($table, true);
108. $start = $this->conn->fetchOne($query);
110. ++$start;
111. }
113. $sql[] = $this->createSequenceSql($table, $start);
115. $sequenceName = $this->conn->formatter->getSequenceName($table);
116. $triggerName = $this->conn->quoteIdentifier($table . '_AI_PK', true);
117. $table = $this->conn->quoteIdentifier($table, true);
118. $name = $this->conn->quoteIdentifier($name, true);
119. $sql[] = 'CREATE TRIGGER ' . $triggerName . '
120. BEFORE INSERT
121. ON '.$table.'
122. FOR EACH ROW
123. DECLARE
124. last_Sequence NUMBER;
125. last_InsertID NUMBER;
126. BEGIN
127. SELECT '.$sequenceName.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
128. IF (:NEW.'.$name.' IS NULL OR :NEW.'.$name.' = 0) THEN
129. SELECT '.$sequenceName.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
130. ELSE
131. SELECT NVL(Last_Number, 0) INTO last_Sequence
132. FROM User_Sequences
133. WHERE UPPER(Sequence_Name) = UPPER(\''.$sequenceName.'\');
134. SELECT :NEW.id INTO last_InsertID FROM DUAL;
135. WHILE (last_InsertID > last_Sequence) LOOP
136. SELECT ' . $sequenceName . '.NEXTVAL INTO last_Sequence FROM DUAL;
137. END LOOP;
138. END IF;
139. END;
140. ';
141. return $sql;
142. }
143. /**
144. * drop an existing autoincrement sequence + trigger
145. *
146. * @param string $table name of the table
147. * @return void
148. */
149. public function dropAutoincrement($table)
150. {
151. $table = strtoupper($table);
152. $triggerName = $table . '_AI_PK';
153. $trigger_name_quoted = $this->conn->quote($triggerName);
154. $query = 'SELECT trigger_name FROM user_triggers';
155. $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted);
156. $trigger = $this->conn->fetchOne($query);
158. if ($trigger) {
159. $trigger_name = $this->conn->quoteIdentifier($table . '_AI_PK', true);
160. $trigger_sql = 'DROP TRIGGER ' . $trigger_name;
162. // if throws exception, trigger for autoincrement PK could not be dropped
163. $this->conn->exec($trigger_sql);
165. // if throws exception, sequence for autoincrement PK could not be dropped
166. $this->dropSequence($table);
168. $indexName = $table . '_AI_PK';
170. // if throws exception, primary key for autoincrement PK could not be dropped
171. $this->dropConstraint($table, $indexName);
172. }
173. }
174. /**
175. * A method to return the required SQL string that fits between CREATE ... TABLE
176. * to create the table as a temporary table.
177. *
178. * @return string The string required to be placed between "CREATE" and "TABLE"
179. * to generate a temporary table, if possible.
180. */
181. public function getTemporaryTableQuery()
182. {
183. return 'GLOBAL TEMPORARY';
184. }
185. /**
186. * getAdvancedForeignKeyOptions
187. * Return the FOREIGN KEY query section dealing with non-standard options
188. * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
189. *
190. * @param array $definition foreign key definition
191. * @return string
192. * @access protected
193. */
194. public function getAdvancedForeignKeyOptions(array $definition)
195. {
196. $query = '';
197. if (isset($definition['onDelete'])) {
198. $query .= ' ON DELETE ' . $definition['onDelete'];
199. }
200. if (isset($definition['deferrable'])) {
201. $query .= ' DEFERRABLE';
202. } else {
203. $query .= ' NOT DEFERRABLE';
204. }
205. if (isset($definition['feferred'])) {
206. $query .= ' INITIALLY DEFERRED';
207. } else {
208. $query .= ' INITIALLY IMMEDIATE';
209. }
210. return $query;
211. }
213. /**
214. * create a new table
215. *
216. * @param string $name Name of the database that should be created
217. * @param array $fields Associative array that contains the definition of each field of the new table
218. * The indexes of the array entries are the names of the fields of the table an
219. * the array entry values are associative arrays like those that are meant to be
220. * passed with the field definitions to get[Type]Declaration() functions.
221. *
222. * Example
223. * array(
224. *
225. * 'id' => array(
226. * 'type' => 'integer',
227. * 'unsigned' => 1
228. * 'notnull' => 1
229. * 'default' => 0
230. * ),
231. * 'name' => array(
232. * 'type' => 'text',
233. * 'length' => 12
234. * ),
235. * 'password' => array(
236. * 'type' => 'text',
237. * 'length' => 12
238. * )
239. * );
240. * @param array $options An associative array of table options:
241. *
242. * @return void
243. */
244. public function createTable($name, array $fields, array $options = array())
245. {
246. $this->conn->beginTransaction();
248. foreach ($this->createTableSql($name, $fields, $options) as $sql) {
249. $this->conn->exec($sql);
250. }
252. $this->conn->commit();
253. }
255. /**
256. * create a new table
257. *
258. * @param string $name Name of the database that should be created
259. * @param array $fields Associative array that contains the definition of each field of the new table
260. * The indexes of the array entries are the names of the fields of the table an
261. * the array entry values are associative arrays like those that are meant to be
262. * passed with the field definitions to get[Type]Declaration() functions.
263. *
264. * Example
265. * array(
266. *
267. * 'id' => array(
268. * 'type' => 'integer',
269. * 'unsigned' => 1
270. * 'notnull' => 1
271. * 'default' => 0
272. * ),
273. * 'name' => array(
274. * 'type' => 'text',
275. * 'length' => 12
276. * ),
277. * 'password' => array(
278. * 'type' => 'text',
279. * 'length' => 12
280. * )
281. * );
282. * @param array $options An associative array of table options:
283. *
284. * @return void
285. */
286. public function createTableSql($name, array $fields, array $options = array())
287. {
288. $sql = parent::createTableSql($name, $fields, $options);
290. foreach ($fields as $fieldName => $field) {
291. if (isset($field['autoincrement']) && $field['autoincrement'] ||
292. (isset($field['autoinc']) && $fields['autoinc'])) {
293. $sql = array_merge($sql, $this->_makeAutoincrement($fieldName, $name));
294. }
295. }
297. return $sql;
298. }
299. /**
300. * drop an existing table
301. *
302. * @param string $name name of the table that should be dropped
303. * @return void
304. */
305. public function dropTable($name)
306. {
307. //$this->conn->beginNestedTransaction();
308. $result = $this->dropAutoincrement($name);
309. $result = parent::dropTable($name);
310. //$this->conn->completeNestedTransaction();
311. return $result;
312. }
313. /**
314. * alter an existing table
315. *
316. * @param string $name name of the table that is intended to be changed.
317. * @param array $changes associative array that contains the details of each type
318. * of change that is intended to be performed. The types of
319. * changes that are currently supported are defined as follows:
320. *
321. * name
322. *
323. * New name for the table.
324. *
325. * add
326. *
327. * Associative array with the names of fields to be added as
328. * indexes of the array. The value of each entry of the array
329. * should be set to another associative array with the properties
330. * of the fields to be added. The properties of the fields should
331. * be the same as defined by the MDB2 parser.
332. *
333. *
334. * remove
335. *
336. * Associative array with the names of fields to be removed as indexes
337. * of the array. Currently the values assigned to each entry are ignored.
338. * An empty array should be used for future compatibility.
339. *
340. * rename
341. *
342. * Associative array with the names of fields to be renamed as indexes
343. * of the array. The value of each entry of the array should be set to
344. * another associative array with the entry named name with the new
345. * field name and the entry named Declaration that is expected to contain
346. * the portion of the field declaration already in DBMS specific SQL code
347. * as it is used in the CREATE TABLE statement.
348. *
349. * change
350. *
351. * Associative array with the names of the fields to be changed as indexes
352. * of the array. Keep in mind that if it is intended to change either the
353. * name of a field and any other properties, the change array entries
354. * should have the new names of the fields as array indexes.
355. *
356. * The value of each entry of the array should be set to another associative
357. * array with the properties of the fields to that are meant to be changed as
358. * array entries. These entries should be assigned to the new values of the
359. * respective properties. The properties of the fields should be the same
360. * as defined by the MDB2 parser.
361. *
362. * Example
363. * array(
364. * 'name' => 'userlist',
365. * 'add' => array(
366. * 'quota' => array(
367. * 'type' => 'integer',
368. * 'unsigned' => 1
369. * )
370. * ),
371. * 'remove' => array(
372. * 'file_limit' => array(),
373. * 'time_limit' => array()
374. * ),
375. * 'change' => array(
376. * 'name' => array(
377. * 'length' => '20',
378. * 'definition' => array(
379. * 'type' => 'text',
380. * 'length' => 20,
381. * ),
382. * )
383. * ),
384. * 'rename' => array(
385. * 'sex' => array(
386. * 'name' => 'gender',
387. * 'definition' => array(
388. * 'type' => 'text',
389. * 'length' => 1,
390. * 'default' => 'M',
391. * ),
392. * )
393. * )
394. * )
395. *
396. * @param boolean $check indicates whether the function should just check if the DBMS driver
397. * can perform the requested table alterations if the value is true or
398. * actually perform them otherwise.
399. * @return void
400. */
401. public function alterTable($name, array $changes, $check)
402. {
404. foreach ($changes as $changeName => $change) {
405. switch ($changeName) {
406. case 'add':
407. case 'remove':
408. case 'change':
409. case 'name':
410. case 'rename':
411. break;
412. default:
413. throw new Doctrine_Export_Exception('change type "' . $changeName . '" not yet supported');
414. }
415. }
417. if ($check) {
418. return false;
419. }
421. $name = $this->conn->quoteIdentifier($name, true);
423. if ( ! empty($changes['add']) && is_array($changes['add'])) {
424. $fields = array();
425. foreach ($changes['add'] as $fieldName => $field) {
426. $fields[] = $this->conn->getDeclaration($field['type'], $fieldName, $field);
427. }
428. $result = $this->conn->exec('ALTER TABLE ' . $name . ' ADD (' . implode(', ', $fields) . ')');
429. }
431. if ( ! empty($changes['change']) && is_array($changes['change'])) {
432. $fields = array();
433. foreach ($changes['change'] as $fieldName => $field) {
434. $fields[] = $fieldName. ' ' . $this->conn->getDeclaration($field['definition']['type'], '', $field['definition']);
435. }
436. $result = $this->conn->exec('ALTER TABLE ' . $name . ' MODIFY (' . implode(', ', $fields) . ')');
437. }
439. if ( ! empty($changes['rename']) && is_array($changes['rename'])) {
440. foreach ($changes['rename'] as $fieldName => $field) {
441. $query = 'ALTER TABLE ' . $name . ' RENAME COLUMN ' . $this->conn->quoteIdentifier($fieldName, true)
442. . ' TO ' . $this->conn->quoteIdentifier($field['name']);
444. $result = $this->conn->exec($query);
445. }
446. }
448. if ( ! empty($changes['remove']) && is_array($changes['remove'])) {
449. $fields = array();
450. foreach ($changes['remove'] as $fieldName => $field) {
451. $fields[] = $this->conn->quoteIdentifier($fieldName, true);
452. }
453. $result = $this->conn->exec('ALTER TABLE ' . $name . ' DROP COLUMN ' . implode(', ', $fields));
454. }
456. if ( ! empty($changes['name'])) {
457. $changeName = $this->conn->quoteIdentifier($changes['name'], true);
458. $result = $this->conn->exec('ALTER TABLE ' . $name . ' RENAME TO ' . $changeName);
459. }
460. }
461. /**
462. * create sequence
463. *
464. * @param string $seqName name of the sequence to be created
465. * @param string $start start value of the sequence; default is 1
466. * @param array $options An associative array of table options:
467. * array(
468. * 'comment' => 'Foo',
469. * 'charset' => 'utf8',
470. * 'collate' => 'utf8_unicode_ci',
471. * );
472. * @return string
473. */
474. public function createSequenceSql($seqName, $start = 1, array $options = array())
475. {
476. $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true);
477. $query = 'CREATE SEQUENCE ' . $sequenceName . ' START WITH ' . $start . ' INCREMENT BY 1 NOCACHE';
478. $query .= ($start < 1 ? ' MINVALUE ' . $start : '');
479. return $query;
480. }
481. /**
482. * drop existing sequence
483. *
484. * @param object $this->conn database object that is extended by this class
485. * @param string $seqName name of the sequence to be dropped
486. * @return string
487. */
488. public function dropSequenceSql($seqName)
489. {
490. $sequenceName = $this->conn->quoteIdentifier($this->conn->formatter->getSequenceName($seqName), true);
491. return 'DROP SEQUENCE ' . $sequenceName;
492. }
493. }