thomascube
2006-02-22 745b1466fc76d5ded589e2469328086002430c1c
commit | author | age
c9462d 1 <?php
S 2 // +----------------------------------------------------------------------+
3 // | PHP versions 4 and 5                                                 |
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
6 // | Stig. S. Bakken, Lukas Smith                                         |
7 // | All rights reserved.                                                 |
8 // +----------------------------------------------------------------------+
9 // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB  |
10 // | API as well as database abstraction for PHP applications.            |
11 // | This LICENSE is in the BSD license style.                            |
12 // |                                                                      |
13 // | Redistribution and use in source and binary forms, with or without   |
14 // | modification, are permitted provided that the following conditions   |
15 // | are met:                                                             |
16 // |                                                                      |
17 // | Redistributions of source code must retain the above copyright       |
18 // | notice, this list of conditions and the following disclaimer.        |
19 // |                                                                      |
20 // | Redistributions in binary form must reproduce the above copyright    |
21 // | notice, this list of conditions and the following disclaimer in the  |
22 // | documentation and/or other materials provided with the distribution. |
23 // |                                                                      |
24 // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
25 // | Lukas Smith nor the names of his contributors may be used to endorse |
26 // | or promote products derived from this software without specific prior|
27 // | written permission.                                                  |
28 // |                                                                      |
29 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
30 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
31 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
32 // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
33 // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
34 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
35 // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
36 // |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
37 // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
38 // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
39 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
40 // | POSSIBILITY OF SUCH DAMAGE.                                          |
41 // +----------------------------------------------------------------------+
42 // | Author: Lukas Smith <smith@pooteeweet.org>                           |
43 // +----------------------------------------------------------------------+
44
45 // $Id$
46
47 require_once 'MDB2/Driver/Manager/Common.php';
48
49 /**
50  * MDB2 oci8 driver for the management modules
51  *
52  * @package MDB2
53  * @category Database
54  * @author Lukas Smith <smith@pooteeweet.org>
55  */
56 class MDB2_Driver_Manager_oci8 extends MDB2_Driver_Manager_Common
57 {
58     // {{{ createDatabase()
59
60     /**
61      * create a new database
62      *
63      * @param object $db database object that is extended by this class
64      * @param string $name name of the database that should be created
65      * @return mixed MDB2_OK on success, a MDB2 error on failure
66      * @access public
67      */
68     function createDatabase($name)
69     {
70         $db =& $this->getDBInstance();
71         if (PEAR::isError($db)) {
72             return $db;
73         }
74
75         $username = $db->options['database_name_prefix'].$name;
76         $password = $db->dsn['password'] ? $db->dsn['password'] : $name;
77         $tablespace = $db->options['default_tablespace']
78             ? ' DEFAULT TABLESPACE '.$db->options['default_tablespace'] : '';
79
80         $query = 'CREATE USER '.$username.' IDENTIFIED BY '.$password.$tablespace;
81         $result = $db->standaloneQuery($query);
82         if (PEAR::isError($result)) {
83             return $result;
84         }
85         $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE TO '.$username;
86         $result = $db->standaloneQuery($query);
87         if (PEAR::isError($result)) {
88             $query = 'DROP USER '.$username.' CASCADE';
89             $result2 = $db->standaloneQuery($query);
90             if (PEAR::isError($result2)) {
91                 return $db->raiseError(MDB2_ERROR, null, null,
92                     'createDatabase: could not setup the database user ('.$result->getUserinfo().
93                         ') and then could drop its records ('.$result2->getUserinfo().')');
94             }
95             return $result;
96         }
97         return MDB2_OK;
98     }
99
100     // }}}
101     // {{{ dropDatabase()
102
103     /**
104      * drop an existing database
105      *
106      * @param object $db database object that is extended by this class
107      * @param string $name name of the database that should be dropped
108      * @return mixed MDB2_OK on success, a MDB2 error on failure
109      * @access public
110      */
111     function dropDatabase($name)
112     {
113         $db =& $this->getDBInstance();
114         if (PEAR::isError($db)) {
115             return $db;
116         }
117
118         $username = $db->options['database_name_prefix'].$name;
119         return $db->standaloneQuery('DROP USER '.$username.' CASCADE');
120     }
121
122     function _makeAutoincrement($name, $table, $start = 1)
123     {
124         $db =& $this->getDBInstance();
125         if (PEAR::isError($db)) {
126             return $db;
127         }
128
129         $index_name  = $table . '_autoincrement_pk';
130         $definition = array(
131             'primary' => true,
132             'fields' => array($name),
133         );
134         $result = $db->manager->createIndex($table, $index_name, $definition);
135         if (PEAR::isError($result)) {
136             return $db->raiseError(MDB2_ERROR, null, null,
137                 '_makeAutoincrement: primary key for autoincrement PK could not be created');
138         }
139
140         $result = $db->manager->createSequence($table, $start);
141         if (PEAR::isError($result)) {
142             return $db->raiseError(MDB2_ERROR, null, null,
143                 '_makeAutoincrement: sequence for autoincrement PK could not be created');
144         }
145
146         $sequence_name = $db->getSequenceName($table);
147         $trigger_name  = $table . '_autoincrement_pk';
148         $trigger_sql = "CREATE TRIGGER $trigger_name BEFORE INSERT ON $table";
149         $trigger_sql.= " FOR EACH ROW BEGIN IF (:new.$name IS NULL) THEN SELECT ";
150         $trigger_sql.= "$sequence_name.NEXTVAL INTO :new.$name FROM DUAL; END IF; END;";
151
152         return $db->query($trigger_sql);
153     }
154
155     function _dropAutoincrement($name, $table)
156     {
157         $db =& $this->getDBInstance();
158         if (PEAR::isError($db)) {
159             return $db;
160         }
161
162         $result = $db->manager->dropSequence($table);
163         if (PEAR::isError($result)) {
164             return $db->raiseError(MDB2_ERROR, null, null,
165                 '_dropAutoincrement: sequence for autoincrement PK could not be dropped');
166         }
167
168         $sequence_name = $db->getSequenceName($table);
169         $trigger_name  = $table . '_autoincrement_pk';
170         $trigger_sql = 'DROP TRIGGER ' . $trigger_name;
171
172         return $db->query($trigger_sql);
173     }
174
175     // }}}
176     // {{{ createTable()
177
178     /**
179      * create a new table
180      *
181      * @param string $name     Name of the database that should be created
182      * @param array $fields Associative array that contains the definition of each field of the new table
183      *                        The indexes of the array entries are the names of the fields of the table an
184      *                        the array entry values are associative arrays like those that are meant to be
185      *                         passed with the field definitions to get[Type]Declaration() functions.
186      *
187      *                        Example
188      *                        array(
189      *
190      *                            'id' => array(
191      *                                'type' => 'integer',
192      *                                'unsigned' => 1
193      *                                'notnull' => 1
194      *                                'default' => 0
195      *                            ),
196      *                            'name' => array(
197      *                                'type' => 'text',
198      *                                'length' => 12
199      *                            ),
200      *                            'password' => array(
201      *                                'type' => 'text',
202      *                                'length' => 12
203      *                            )
204      *                        );
205      * @return mixed MDB2_OK on success, a MDB2 error on failure
206      * @access public
207      */
208     function createTable($name, $fields)
209     {
210         $result = parent::createTable($name, $fields);
211         if (PEAR::isError($result)) {
212             return $result;
213         }
214         foreach($fields as $field_name => $field) {
215             if (array_key_exists('autoincrement', $field) && $field['autoincrement']) {
216                 return $this->_makeAutoincrement($field_name, $name);
217             }
218         }
219     }
220
221     // }}}
222     // {{{ alterTable()
223
224     /**
225      * alter an existing table
226      *
227      * @param object $db database object that is extended by this class
228      * @param string $name name of the table that is intended to be changed.
229      * @param array $changes associative array that contains the details of each type
230      *                              of change that is intended to be performed. The types of
231      *                              changes that are currently supported are defined as follows:
232      *
233      *                              name
234      *
235      *                                 New name for the table.
236      *
237      *                             add
238      *
239      *                                 Associative array with the names of fields to be added as
240      *                                  indexes of the array. The value of each entry of the array
241      *                                  should be set to another associative array with the properties
242      *                                  of the fields to be added. The properties of the fields should
243      *                                  be the same as defined by the Metabase parser.
244      *
245      *
246      *                             remove
247      *
248      *                                 Associative array with the names of fields to be removed as indexes
249      *                                  of the array. Currently the values assigned to each entry are ignored.
250      *                                  An empty array should be used for future compatibility.
251      *
252      *                             rename
253      *
254      *                                 Associative array with the names of fields to be renamed as indexes
255      *                                  of the array. The value of each entry of the array should be set to
256      *                                  another associative array with the entry named name with the new
257      *                                  field name and the entry named Declaration that is expected to contain
258      *                                  the portion of the field declaration already in DBMS specific SQL code
259      *                                  as it is used in the CREATE TABLE statement.
260      *
261      *                             change
262      *
263      *                                 Associative array with the names of the fields to be changed as indexes
264      *                                  of the array. Keep in mind that if it is intended to change either the
265      *                                  name of a field and any other properties, the change array entries
266      *                                  should have the new names of the fields as array indexes.
267      *
268      *                                 The value of each entry of the array should be set to another associative
269      *                                  array with the properties of the fields to that are meant to be changed as
270      *                                  array entries. These entries should be assigned to the new values of the
271      *                                  respective properties. The properties of the fields should be the same
272      *                                  as defined by the Metabase parser.
273      *
274      *                             Example
275      *                                 array(
276      *                                     'name' => 'userlist',
277      *                                     'add' => array(
278      *                                         'quota' => array(
279      *                                             'type' => 'integer',
280      *                                             'unsigned' => 1
281      *                                         )
282      *                                     ),
283      *                                     'remove' => array(
284      *                                         'file_limit' => array(),
285      *                                         'time_limit' => array()
286      *                                         ),
287      *                                     'change' => array(
288      *                                         'gender' => array(
289      *                                             'default' => 'M',
290      *                                         )
291      *                                     ),
292      *                                     'rename' => array(
293      *                                         'sex' => array(
294      *                                             'name' => 'gender',
295      *                                         )
296      *                                     )
297      *                                 )
298      * @param boolean $check indicates whether the function should just check if the DBMS driver
299      *                              can perform the requested table alterations if the value is true or
300      *                              actually perform them otherwise.
301      * @access public
302      * @return mixed MDB2_OK on success, a MDB2 error on failure
303      */
304     function alterTable($name, $changes, $check)
305     {
306         $db =& $this->getDBInstance();
307         if (PEAR::isError($db)) {
308             return $db;
309         }
310
311         foreach ($changes as $change_name => $change) {
312             switch ($change_name) {
313             case 'add':
314             case 'remove':
315             case 'change':
316             case 'name':
317                 break;
318             case 'rename':
319             default:
320                 return $db->raiseError(MDB2_ERROR, null, null,
321                     'alterTable: change type "'.$change_name.'" not yet supported');
322             }
323         }
324
325         if ($check) {
326             return MDB2_OK;
327         }
328
329         if (array_key_exists('remove', $changes)) {
330             $query = ' DROP (';
331             $fields = $changes['remove'];
332             $query.= implode(', ', array_keys($fields));
333             $query.= ')';
334             if (PEAR::isError($result = $db->query("ALTER TABLE $name $query"))) {
335                 return $result;
336             }
337             $query = '';
338         }
339
340         $query = (array_key_exists('name', $changes) ? 'RENAME TO '.$changes['name'] : '');
341
342         if (array_key_exists('add', $changes)) {
343             foreach ($changes['add'] as $field_name => $field) {
344                 $type_declaration = $db->getDeclaration($field['type'], $field_name, $field);
345                 if (PEAR::isError($type_declaration)) {
346                     return $err;
347                 }
348                 $query.= ' ADD (' . $type_declaration . ')';
349             }
350         }
351
352         if (array_key_exists('change', $changes)) {
353             foreach ($changes['change'] as $field_name => $field) {
354                 $query.= "MODIFY ($field_name " . $db->getDeclaration($field['type'], $field_name, $field).')';
355             }
356         }
357
358         if (!$query) {
359             return MDB2_OK;
360         }
361
362         return $db->query("ALTER TABLE $name $query");
363     }
364
365     // }}}
366     // {{{ listDatabases()
367
368     /**
369      * list all databases
370      *
371      * @return mixed data array on success, a MDB2 error on failure
372      * @access public
373      */
374     function listDatabases()
375     {
376         $db =& $this->getDBInstance();
377         if (PEAR::isError($db)) {
378             return $db;
379         }
380
381         if ($db->options['database_name_prefix']) {
382             $query = 'SELECT SUBSTR(username, '
383                 .(strlen($db->options['database_name_prefix'])+1)
384                 .") FROM sys.dba_users WHERE username LIKE '"
385                 .$db->options['database_name_prefix']."%'";
386         } else {
387             $query = 'SELECT username FROM sys.dba_users';
388         }
389         $result = $db->standaloneQuery($query);
390         if (PEAR::isError($result)) {
391             return $result;
392         }
393         $databases = $result->fetchCol();
394         if (PEAR::isError($databases)) {
395             return $databases;
396         }
397         // is it legit to force this to lowercase?
398         $databases = array_keys(array_change_key_case(array_flip($databases), $db->options['field_case']));
399         $result->free();
400         return $databases;
401     }
402
403         // }}}
404     // {{{ listUsers()
405
406     /**
407      * list all users in the current database
408      *
409      * @return mixed data array on success, a MDB2 error on failure
410      * @access public
411      */
412     function listUsers()
413     {
414         $db =& $this->getDBInstance();
415         if (PEAR::isError($db)) {
416             return $db;
417         }
418
419         $query = 'SELECT username FROM sys.all_users';
420         $users = $db->queryCol($query);
421         if (PEAR::isError($users)) {
422             return $users;
423         }
424         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
425             && $db->options['field_case'] == CASE_LOWER
426         ) {
427             $users = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $users);
428         }
429         return $users;
430     }
431     // }}}
432     // {{{ listViews()
433
434     /**
435      * list all views in the current database
436      *
437      * @return mixed data array on success, a MDB2 error on failure
438      * @access public
439      */
440     function listViews()
441     {
442         $db =& $this->getDBInstance();
443         if (PEAR::isError($db)) {
444             return $db;
445         }
446
447         $query = 'SELECT view_name FROM sys.user_views';
448         $views = $db->queryCol($query);
449         if (PEAR::isError($views)) {
450             return $views;
451         }
452         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
453             && $db->options['field_case'] == CASE_LOWER
454         ) {
455             $views = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $views);
456         }
457         return $views;
458     }
459
460     // }}}
461     // {{{ listFunctions()
462
463     /**
464      * list all functions in the current database
465      *
466      * @return mixed data array on success, a MDB2 error on failure
467      * @access public
468      */
469     function listFunctions()
470     {
471         $db =& $this->getDBInstance();
472         if (PEAR::isError($db)) {
473             return $db;
474         }
475
476         $query = "SELECT name FROM sys.user_source WHERE line = 1 AND type = 'FUNCTION'";
477         $functions = $db->queryCol($query);
478         if (PEAR::isError($functions)) {
479             return $functions;
480         }
481         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
482             && $db->options['field_case'] == CASE_LOWER
483         ) {
484             $functions = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $functions);
485         }
486         return $functions;
487     }
488
489     // }}}
490     // {{{ listTables()
491
492     /**
493      * list all tables in the current database
494      *
495      * @return mixed data array on success, a MDB error on failure
496      * @access public
497      **/
498     function listTables()
499     {
500         $db =& $this->getDBInstance();
501         if (PEAR::isError($db)) {
502             return $db;
503         }
504
505         $query = 'SELECT table_name FROM sys.user_tables';
506         return $db->queryCol($query);
507     }
508
509     // }}}
510     // {{{ listTableFields()
511
512     /**
513      * list all fields in a tables in the current database
514      *
515      * @param string $table name of table that should be used in method
516      * @return mixed data array on success, a MDB error on failure
517      * @access public
518      */
519     function listTableFields($table)
520     {
521         $db =& $this->getDBInstance();
522         if (PEAR::isError($db)) {
523             return $db;
524         }
525
526         $table = strtoupper($table);
527         $query = "SELECT column_name FROM user_tab_columns WHERE table_name='$table' ORDER BY column_id";
528         $fields = $db->queryCol($query);
529         if (PEAR::isError($result)) {
530             return $result;
531         }
532         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
533             && $db->options['field_case'] == CASE_LOWER
534         ) {
535             $fields = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $fields);
536         }
537         return $fields;
538     }
539     // }}}
540     // {{{ createIndex()
541
542     /**
543      * get the stucture of a field into an array
544      *
545      * @param string    $table         name of the table on which the index is to be created
546      * @param string    $name         name of the index to be created
547      * @param array     $definition        associative array that defines properties of the index to be created.
548      *                                 Currently, only one property named FIELDS is supported. This property
549      *                                 is also an associative with the names of the index fields as array
550      *                                 indexes. Each entry of this array is set to another type of associative
551      *                                 array that specifies properties of the index that are specific to
552      *                                 each field.
553      *
554      *                                Currently, only the sorting property is supported. It should be used
555      *                                 to define the sorting direction of the index. It may be set to either
556      *                                 ascending or descending.
557      *
558      *                                Not all DBMS support index sorting direction configuration. The DBMS
559      *                                 drivers of those that do not support it ignore this property. Use the
560      *                                 function supports() to determine whether the DBMS driver can manage indexes.
561      *
562      *                                 Example
563      *                                    array(
564      *                                        'fields' => array(
565      *                                            'user_name' => array(
566      *                                                'sorting' => 'ascending'
567      *                                            ),
568      *                                            'last_login' => array()
569      *                                        )
570      *                                    )
571      * @return mixed MDB2_OK on success, a MDB2 error on failure
572      * @access public
573      */
574     function createIndex($table, $name, $definition)
575     {
576         $db =& $this->getDBInstance();
577         if (PEAR::isError($db)) {
578             return $db;
579         }
580         if (array_key_exists('primary', $definition) && $definition['primary']) {
581             $query = "ALTER TABLE $table ADD CONSTRAINT $name PRIMARY KEY (";
582         } else {
583             $query = 'CREATE';
584             if (array_key_exists('unique', $definition) && $definition['unique']) {
585                 $query.= ' UNIQUE';
586             }
587             $query .= " INDEX $name ON $table (";
588         }
589         $query .= implode(', ', array_keys($definition['fields'])) . ')';
590
591         return $db->query($query);
592     }
593
594     // }}}
595     // {{{ createSequence()
596
597     /**
598      * create sequence
599      *
600      * @param object $db database object that is extended by this class
601      * @param string $seq_name name of the sequence to be created
602      * @param string $start start value of the sequence; default is 1
603      * @return mixed MDB2_OK on success, a MDB2 error on failure
604      * @access public
605      */
606     function createSequence($seq_name, $start = 1)
607     {
608         $db =& $this->getDBInstance();
609         if (PEAR::isError($db)) {
610             return $db;
611         }
612
613         $sequence_name = $db->getSequenceName($seq_name);
614         return $db->query("CREATE SEQUENCE $sequence_name START WITH $start INCREMENT BY 1".
615             ($start < 1 ? " MINVALUE $start" : ''));
616     }
617
618     // }}}
619     // {{{ dropSequence()
620
621     /**
622      * drop existing sequence
623      *
624      * @param object $db database object that is extended by this class
625      * @param string $seq_name name of the sequence to be dropped
626      * @return mixed MDB2_OK on success, a MDB2 error on failure
627      * @access public
628      */
629     function dropSequence($seq_name)
630     {
631         $db =& $this->getDBInstance();
632         if (PEAR::isError($db)) {
633             return $db;
634         }
635
636         $sequence_name = $db->getSequenceName($seq_name);
637         return $db->query("DROP SEQUENCE $sequence_name");
638     }
639
640     // }}}
641     // {{{ listSequences()
642
643     /**
644      * list all sequences in the current database
645      *
646      * @return mixed data array on success, a MDB2 error on failure
647      * @access public
648      */
649     function listSequences()
650     {
651         $db =& $this->getDBInstance();
652         if (PEAR::isError($db)) {
653             return $db;
654         }
655
656         $query = "SELECT sequence_name FROM sys.user_sequences";
657         $table_names = $db->queryCol($query);
658         if (PEAR::isError($table_names)) {
659             return $table_names;
660         }
661         $sequences = array();
662         for ($i = 0, $j = count($table_names); $i < $j; ++$i) {
663             if ($sqn = $this->_isSequenceName($table_names[$i]))
664                 $sequences[] = $sqn;
665         }
666         if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
667             && $db->options['field_case'] == CASE_LOWER
668         ) {
669             $sequences = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $sequences);
670         }
671         return $sequences;
672     }}
673 ?>