2 // +----------------------------------------------------------------------+
3 // | PHP versions 4 and 5 |
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) 1998-2007 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. |
13 // | Redistribution and use in source and binary forms, with or without |
14 // | modification, are permitted provided that the following conditions |
17 // | Redistributions of source code must retain the above copyright |
18 // | notice, this list of conditions and the following disclaimer. |
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. |
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. |
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 // +----------------------------------------------------------------------+
45 // $Id: Common.php 327310 2012-08-27 15:16:18Z danielc $
54 * These are constants for the tableInfo-function
55 * they are bitwised or'ed. so if there are more constants to be defined
56 * in the future, adjust MDB2_TABLEINFO_FULL accordingly
59 define('MDB2_TABLEINFO_ORDER', 1);
60 define('MDB2_TABLEINFO_ORDERTABLE', 2);
61 define('MDB2_TABLEINFO_FULL', 3);
64 * Base class for the schema reverse engineering module that is extended by each MDB2 driver
66 * To load this module in the MDB2 object:
67 * $mdb->loadModule('Reverse');
71 * @author Lukas Smith <smith@pooteeweet.org>
73 class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
75 // {{{ splitTableSchema()
78 * Split the "[owner|schema].table" notation into an array
80 * @param string $table [schema and] table name
82 * @return array array(schema, table)
85 function splitTableSchema($table)
88 if (strpos($table, '.') !== false) {
89 return explode('.', $table);
91 return array(null, $table);
95 // {{{ getTableFieldDefinition()
98 * Get the structure of a field into an array
100 * @param string $table name of table that should be used in method
101 * @param string $field name of field that should be used in method
102 * @return mixed data array on success, a MDB2 error on failure.
103 * The returned array contains an array for each field definition,
104 * with all or some of these indices, depending on the field data type:
105 * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
108 function getTableFieldDefinition($table, $field)
110 $db = $this->getDBInstance();
111 if (MDB2::isError($db)) {
115 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
116 'method not implemented', __FUNCTION__);
120 // {{{ getTableIndexDefinition()
123 * Get the structure of an index into an array
125 * @param string $table name of table that should be used in method
126 * @param string $index name of index that should be used in method
127 * @return mixed data array on success, a MDB2 error on failure
128 * The returned array has this structure:
131 * [fields] => array (
132 * [field1name] => array() // one entry per each field covered
133 * [field2name] => array() // by the index
134 * [field3name] => array(
135 * [sorting] => ascending
142 function getTableIndexDefinition($table, $index)
144 $db = $this->getDBInstance();
145 if (MDB2::isError($db)) {
149 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
150 'method not implemented', __FUNCTION__);
154 // {{{ getTableConstraintDefinition()
157 * Get the structure of an constraints into an array
159 * @param string $table name of table that should be used in method
160 * @param string $index name of index that should be used in method
161 * @return mixed data array on success, a MDB2 error on failure
162 * The returned array has this structure:
169 * [fields] => array (
170 * [field1name] => array() // one entry per each field covered
171 * [field2name] => array() // by the index
172 * [field3name] => array(
173 * [sorting] => ascending
177 * [references] => array(
180 * [field1name] => array( //one entry per each referenced field
186 * [initiallydeferred] => 0
187 * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
188 * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
189 * [match] => SIMPLE|PARTIAL|FULL
194 function getTableConstraintDefinition($table, $index)
196 $db = $this->getDBInstance();
197 if (MDB2::isError($db)) {
201 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
202 'method not implemented', __FUNCTION__);
206 // {{{ getSequenceDefinition()
209 * Get the structure of a sequence into an array
211 * @param string $sequence name of sequence that should be used in method
212 * @return mixed data array on success, a MDB2 error on failure
213 * The returned array has this structure:
221 function getSequenceDefinition($sequence)
223 $db = $this->getDBInstance();
224 if (MDB2::isError($db)) {
228 $start = $db->currId($sequence);
229 if (MDB2::isError($start)) {
232 if ($db->supports('current_id')) {
235 $db->warnings[] = 'database does not support getting current
236 sequence value, the sequence value was incremented';
238 $definition = array();
240 $definition = array('start' => $start);
246 // {{{ getTriggerDefinition()
249 * Get the structure of a trigger into an array
253 * WARNING: this function is experimental and may change the returned value
254 * at any time until labelled as non-experimental
256 * @param string $trigger name of trigger that should be used in method
257 * @return mixed data array on success, a MDB2 error on failure
258 * The returned array has this structure:
261 * [trigger_name] => 'trigger name',
262 * [table_name] => 'table name',
263 * [trigger_body] => 'trigger body definition',
264 * [trigger_type] => 'BEFORE' | 'AFTER',
265 * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
266 * //or comma separated list of multiple events, when supported
267 * [trigger_enabled] => true|false
268 * [trigger_comment] => 'trigger comment',
271 * The oci8 driver also returns a [when_clause] index.
274 function getTriggerDefinition($trigger)
276 $db = $this->getDBInstance();
277 if (MDB2::isError($db)) {
281 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
282 'method not implemented', __FUNCTION__);
289 * Returns information about a table or a result set
291 * The format of the resulting array depends on which <var>$mode</var>
292 * you select. The sample output below is based on this query:
294 * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
296 * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
302 * <kbd>null</kbd> (default)
309 * [flags] => primary_key not_null
323 * [flags] => primary_key not_null
329 * <kbd>MDB2_TABLEINFO_ORDER</kbd>
331 * <p>In addition to the information found in the default output,
332 * a notation of the number of columns is provided by the
333 * <samp>num_fields</samp> element while the <samp>order</samp>
334 * element provides an array with the column names as the keys and
335 * their location index number (corresponding to the keys in the
336 * the default output) as the values.</p>
338 * <p>If a result set has identical field names, the last one is
351 * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>
353 * <p>Similar to <kbd>MDB2_TABLEINFO_ORDER</kbd> but adds more
354 * dimensions to the array in which the table names are keys and
355 * the field names are sub-keys. This is helpful for queries that
356 * join tables which have identical field names.</p>
360 * [ordertable] => Array (
361 * [tblFoo] => Array (
365 * [tblBar] => Array (
374 * The <samp>flags</samp> element contains a space separated list
375 * of extra information about the field. This data is inconsistent
376 * between DBMS's due to the way each DBMS works.
377 * + <samp>primary_key</samp>
378 * + <samp>unique_key</samp>
379 * + <samp>multiple_key</samp>
380 * + <samp>not_null</samp>
382 * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
383 * elements if <var>$result</var> is a table name. The following DBMS's
384 * provide full information from queries:
388 * If the 'portability' option has <samp>MDB2_PORTABILITY_FIX_CASE</samp>
389 * turned on, the names of tables and fields will be lower or upper cased.
391 * @param object|string $result MDB2_result object from a query or a
392 * string containing the name of a table.
393 * While this also accepts a query result
394 * resource identifier, this behavior is
396 * @param int $mode either unused or one of the tableInfo modes:
397 * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>,
398 * <kbd>MDB2_TABLEINFO_ORDER</kbd> or
399 * <kbd>MDB2_TABLEINFO_FULL</kbd> (which does both).
400 * These are bitwise, so the first two can be
401 * combined using <kbd>|</kbd>.
403 * @return array an associative array with the information requested.
404 * A MDB2_Error object on failure.
406 * @see MDB2_Driver_Common::setOption()
408 function tableInfo($result, $mode = null)
410 $db = $this->getDBInstance();
411 if (MDB2::isError($db)) {
415 if (!is_string($result)) {
416 return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
417 'method not implemented', __FUNCTION__);
420 $db->loadModule('Manager', null, true);
421 $fields = $db->manager->listTableFields($result);
422 if (MDB2::isError($fields)) {
428 $idxname_format = $db->getOption('idxname_format');
429 $db->setOption('idxname_format', '%s');
431 $indexes = $db->manager->listTableIndexes($result);
432 if (MDB2::isError($indexes)) {
433 $db->setOption('idxname_format', $idxname_format);
437 foreach ($indexes as $index) {
438 $definition = $this->getTableIndexDefinition($result, $index);
439 if (MDB2::isError($definition)) {
440 $db->setOption('idxname_format', $idxname_format);
443 if (count($definition['fields']) > 1) {
444 foreach ($definition['fields'] as $field => $sort) {
445 $flags[$field] = 'multiple_key';
450 $constraints = $db->manager->listTableConstraints($result);
451 if (MDB2::isError($constraints)) {
455 foreach ($constraints as $constraint) {
456 $definition = $this->getTableConstraintDefinition($result, $constraint);
457 if (MDB2::isError($definition)) {
458 $db->setOption('idxname_format', $idxname_format);
461 $flag = !empty($definition['primary'])
462 ? 'primary_key' : (!empty($definition['unique'])
463 ? 'unique_key' : false);
465 foreach ($definition['fields'] as $field => $sort) {
466 if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
467 $flags[$field] = $flag;
476 $res['num_fields'] = count($fields);
479 foreach ($fields as $i => $field) {
480 $definition = $this->getTableFieldDefinition($result, $field);
481 if (MDB2::isError($definition)) {
482 $db->setOption('idxname_format', $idxname_format);
485 $res[$i] = $definition[0];
486 $res[$i]['name'] = $field;
487 $res[$i]['table'] = $result;
488 $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
489 // 'primary_key', 'unique_key', 'multiple_key'
490 $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
491 // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
492 if (!empty($res[$i]['notnull'])) {
493 $res[$i]['flags'].= ' not_null';
495 if (!empty($res[$i]['unsigned'])) {
496 $res[$i]['flags'].= ' unsigned';
498 if (!empty($res[$i]['auto_increment'])) {
499 $res[$i]['flags'].= ' autoincrement';
501 if (!empty($res[$i]['default'])) {
502 $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
505 if ($mode & MDB2_TABLEINFO_ORDER) {
506 $res['order'][$res[$i]['name']] = $i;
508 if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
509 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
513 $db->setOption('idxname_format', $idxname_format);