Table.php 37.3 KB
Newer Older
doctrine's avatar
doctrine committed
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.phpdoctrine.com>.
 */
doctrine's avatar
doctrine committed
21 22 23
/**
 * Doctrine_Table   represents a database table
 *                  each Doctrine_Table holds the information of foreignKeys and associations
24
 *
doctrine's avatar
doctrine committed
25
 *
26 27 28 29 30 31 32 33
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @package     Doctrine
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version     $Revision$
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 */
34
class Doctrine_Table extends Doctrine_Configurable implements Countable {
doctrine's avatar
doctrine committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    /**
     * @var array $data                                 temporary data which is then loaded into Doctrine_Record::$data
     */
    private $data             = array();
    /**
     * @var array $relations                            an array containing all the Doctrine_Relation objects for this table
     */
    private $relations        = array();
    /**
     * @var array $primaryKeys                          an array containing all primary key column names
     */
    private $primaryKeys      = array();
    /**
     * @var mixed $identifier
     */
    private $identifier;
    /**
52 53
     * @see Doctrine_Identifier constants
     * @var integer $identifierType                     the type of identifier this table uses
doctrine's avatar
doctrine committed
54 55 56 57 58 59 60
     */
    private $identifierType;
    /**
     * @var string $query                               cached simple query
     */
    private $query;
    /**
zYne's avatar
zYne committed
61
     * @var Doctrine_Connection $connection             Doctrine_Connection object that created this table
doctrine's avatar
doctrine committed
62
     */
zYne's avatar
zYne committed
63
    private $connection;
doctrine's avatar
doctrine committed
64
    /**
zYne's avatar
zYne committed
65
     * @var string $name
doctrine's avatar
doctrine committed
66 67 68 69 70 71
     */
    private $name;
    /**
     * @var array $identityMap                          first level cache
     */
    private $identityMap        = array();
72
    /**
73
     * @var Doctrine_Table_Repository $repository       record repository
74
     */
doctrine's avatar
doctrine committed
75 76
    private $repository;
    /**
zYne's avatar
zYne committed
77 78 79 80 81 82 83 84 85 86 87
     * @var array $columns                  an array of column definitions,
     *                                      keys as column names and values as column definitions
     *                                      
     *                                      the value array has three values:
     *                                      
     *                                      the column type, eg. 'integer'
     *                                      the column length, eg. 11
     *                                      the column options/constraints/validators. eg array('notnull' => true)
     *
     *                                      so the full columns array might look something like the following:
     *                                      array(
88 89
     *                                             'name' => array('string',  20, array('notnull' => true, 'default' => 'someone')),
     *                                             'age'  => array('integer', 11, array('notnull' => true))
zYne's avatar
zYne committed
90
     *                                              )
doctrine's avatar
doctrine committed
91
     */
zYne's avatar
zYne committed
92
    protected $columns          = array();
doctrine's avatar
doctrine committed
93 94 95 96 97 98 99 100 101
    /**
     * @var array $bound                                bound relations
     */
    private $bound              = array();
    /**
     * @var array $boundAliases                         bound relation aliases
     */
    private $boundAliases       = array();
    /**
102 103
     * @var integer $columnCount                        cached column count, Doctrine_Record uses this column count in when
     *                                                  determining its state
doctrine's avatar
doctrine committed
104 105 106 107 108 109
     */
    private $columnCount;
    /**
     * @var array $parents                              the parent classes of this component
     */
    private $parents            = array();
110 111 112 113
    /**
     * @var boolean $hasDefaultValues                   whether or not this table has default values
     */
    private $hasDefaultValues;
zYne's avatar
zYne committed
114
    /**
115
     * @var array $options                  an array containing all options
zYne's avatar
zYne committed
116
     *
117
     *      -- name                         name of the component, for example component name of the GroupTable is 'Group'
zYne's avatar
zYne committed
118
     *
119 120
     *      -- tableName                    database table name, in most cases this is the same as component name but in some cases
     *                                      where one-table-multi-class inheritance is used this will be the name of the inherited table
zYne's avatar
zYne committed
121
     *
122 123 124
     *      -- sequenceName                 Some databases need sequences instead of auto incrementation primary keys,
     *                                      you can set specific sequence for your table by calling setOption('sequenceName', $seqName)
     *                                      where $seqName is the name of the desired sequence
zYne's avatar
zYne committed
125
     *
126
     *      -- enumMap                      enum value arrays
zYne's avatar
zYne committed
127
     *
128 129
     *      -- inheritanceMap               inheritanceMap is used for inheritance mapping, keys representing columns and values
     *                                      the column values that should correspond to child classes
zYne's avatar
zYne committed
130 131 132 133 134 135 136
     */
    protected $options          = array('name'           => null,
                                        'tableName'      => null,
                                        'sequenceName'   => null,
                                        'inheritanceMap' => array(),
                                        'enumMap'        => array(),
                                        );
doctrine's avatar
doctrine committed
137 138


doctrine's avatar
doctrine committed
139

zYne's avatar
zYne committed
140

doctrine's avatar
doctrine committed
141 142
    /**
     * the constructor
zYne's avatar
zYne committed
143 144
     * @throws Doctrine_Connection_Exception    if there are no opened connections
     * @throws Doctrine_Table_Exception         if there is already an instance of this table
doctrine's avatar
doctrine committed
145 146
     * @return void
     */
147 148
    public function __construct($name, Doctrine_Connection $conn) {
        $this->connection = $conn;
doctrine's avatar
doctrine committed
149

zYne's avatar
zYne committed
150
        $this->setParent($this->connection);
doctrine's avatar
doctrine committed
151

zYne's avatar
zYne committed
152
        $this->options['name'] = $name;
doctrine's avatar
doctrine committed
153 154 155 156 157 158 159 160 161 162 163 164 165

        if( ! class_exists($name) || empty($name))
            throw new Doctrine_Exception("Couldn't find class $name");

        $record = new $name($this);

        $names = array();

        $class = $name;

        // get parent classes

        do {
zYne's avatar
zYne committed
166 167
            if($class == "Doctrine_Record") 
                break;
doctrine's avatar
doctrine committed
168 169 170 171 172 173 174 175 176

           	$name  = $class;
            $names[] = $name;
        } while($class = get_parent_class($class));

        // reverse names
        $names = array_reverse($names);

        // create database table
177
        if(method_exists($record, 'setTableDefinition')) {
doctrine's avatar
doctrine committed
178 179 180 181 182
            $record->setTableDefinition();

            $this->columnCount = count($this->columns);

            if(isset($this->columns)) {
zYne's avatar
zYne committed
183 184
                                      	
                // get the declaring class of setTableDefinition method
185
                $method    = new ReflectionMethod($this->options['name'], 'setTableDefinition');
doctrine's avatar
doctrine committed
186 187
                $class     = $method->getDeclaringClass();

zYne's avatar
zYne committed
188 189
                if( ! isset($this->options['tableName']))
                    $this->options['tableName'] = Doctrine::tableize($class->getName());
doctrine's avatar
doctrine committed
190 191 192

                switch(count($this->primaryKeys)):
                    case 0:
193 194 195 196 197 198 199 200 201 202 203
                        $this->columns = array_merge(array('id' => 
                                                        array('integer', 
                                                              20,
                                                              array('autoincrement' => true,
                                                                    'primary'       => true
                                                                    )
                                                              )
                                                        ), $this->columns);

                        $this->primaryKeys[] = 'id';
                        $this->identifier = 'id';
doctrine's avatar
doctrine committed
204
                        $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT;
205
                        $this->columnCount++;
doctrine's avatar
doctrine committed
206 207 208 209 210
                    break;
                    default:
                        if(count($this->primaryKeys) > 1) {
                            $this->identifier = $this->primaryKeys;
                            $this->identifierType = Doctrine_Identifier::COMPOSITE;
211

doctrine's avatar
doctrine committed
212 213
                        } else {
                            foreach($this->primaryKeys as $pk) {
214
                                $e = $this->columns[$pk][2];
215

216
                                $found = false;
doctrine's avatar
doctrine committed
217

218
                                foreach($e as $option => $value) {
doctrine's avatar
doctrine committed
219 220
                                    if($found)
                                        break;
221

doctrine's avatar
doctrine committed
222
                                    $e2 = explode(":",$option);
223

doctrine's avatar
doctrine committed
224 225 226 227 228 229 230 231 232 233 234 235 236
                                    switch(strtolower($e2[0])):
                                        case "autoincrement":
                                            $this->identifierType = Doctrine_Identifier::AUTO_INCREMENT;
                                            $found = true;
                                        break;
                                        case "seq":
                                            $this->identifierType = Doctrine_Identifier::SEQUENCE;
                                            $found = true;
                                        break;
                                    endswitch;
                                }
                                if( ! isset($this->identifierType))
                                    $this->identifierType = Doctrine_Identifier::NORMAL;
237

doctrine's avatar
doctrine committed
238 239 240 241 242
                                $this->identifier = $pk;
                            }
                        }
                endswitch;

zYne's avatar
zYne committed
243 244 245
                 if($this->getAttribute(Doctrine::ATTR_CREATE_TABLES)) {
                    if(Doctrine_DataDict::isValidClassname($class->getName())) {
                        $dict      = new Doctrine_DataDict($this->getConnection()->getDBH());
zYne's avatar
zYne committed
246
                        $dict->createTable($this->options['tableName'], $this->columns);
zYne's avatar
zYne committed
247
                    }
doctrine's avatar
doctrine committed
248 249 250 251
                }

            }
        } else {
zYne's avatar
zYne committed
252
            throw new Doctrine_Table_Exception("Class '$name' has no table definition.");
doctrine's avatar
doctrine committed
253
        }
254

zYne's avatar
zYne committed
255

doctrine's avatar
doctrine committed
256 257 258 259 260 261 262 263 264
        $record->setUp();

        // save parents
        array_pop($names);
        $this->parents   = $names;

        $this->query     = "SELECT ".implode(", ",array_keys($this->columns))." FROM ".$this->getTableName();

        // check if an instance of this table is already initialized
zYne's avatar
zYne committed
265
        if( ! $this->connection->addTable($this))
doctrine's avatar
doctrine committed
266
            throw new Doctrine_Table_Exception();
267
            
268
        $this->repository = new Doctrine_Table_Repository($this);
doctrine's avatar
doctrine committed
269
    }
zYne's avatar
zYne committed
270 271 272 273 274 275 276 277 278 279
    /**
     * createQuery
     * creates a new Doctrine_Query object and adds the component name
     * of this table as the query 'from' part
     * 
     * @return Doctrine_Query
     */
    public function createQuery() {
        return Doctrine_Query::create()->from($this->getComponentName());
    }
doctrine's avatar
doctrine committed
280
    /**
281 282 283
     * getRepository
     *
     * @return Doctrine_Table_Repository
doctrine's avatar
doctrine committed
284 285 286 287
     */
    public function getRepository() {
        return $this->repository;
    }
zYne's avatar
zYne committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301
    
    public function setOption($name, $value) {
        switch($name) {
            case 'name':
            case 'tableName':
            break;
            case 'enumMap':
            case 'inheritanceMap':
                if( ! is_array($value))
                    throw new Doctrine_Table_Exception($name.' should be an array.');
            break;
        }
        $this->options[$name] = $value;
    }
302 303 304 305 306 307 308 309 310 311
    
    public function usesInheritanceMap() {
        return ( ! empty($this->options['inheritanceMap']));
    }
    public function getOption($name) {
        if(isset($this->options[$name]))
            return $this->options[$name];
            
        return null;
    }
doctrine's avatar
doctrine committed
312 313 314 315 316 317 318 319
    /**
     * setColumn
     * @param string $name
     * @param string $type
     * @param integer $length
     * @param mixed $options
     * @return void
     */
320 321 322 323
    final public function setColumn($name, $type, $length, $options = array()) {
        if(is_string($options)) 
            $options = explode('|', $options);

324 325 326 327 328 329 330 331
        foreach($options as $k => $option) {
            if(is_numeric($k)) {
                if( ! empty($option))
                    $options[$option] = true;

                unset($options[$k]);
            }
        }
332
        $name = strtolower($name);
doctrine's avatar
doctrine committed
333
        $this->columns[$name] = array($type,$length,$options);
334

335
        if(isset($options['primary'])) {
doctrine's avatar
doctrine committed
336 337
            $this->primaryKeys[] = $name;
        }
338 339 340 341 342 343 344 345 346 347 348 349
        if(isset($options['default'])) {
            $this->hasDefaultValues = true;
        }
    }
    /**
     * hasDefaultValues
     * returns true if this table has default values, otherwise false
     *
     * @return boolean
     */
    public function hasDefaultValues() {
        return $this->hasDefaultValues;
doctrine's avatar
doctrine committed
350
    }
351 352 353 354 355 356 357 358
    /**
     * getDefaultValueOf
     * returns the default value(if any) for given column
     *
     * @param string $column
     * @return mixed
     */
    public function getDefaultValueOf($column) {
359
        $column = strtolower($column);
360 361
        if( ! isset($this->columns[$column]))
            throw new Doctrine_Table_Exception("Couldn't get default value. Column ".$column." doesn't exist.");
zYne's avatar
zYne committed
362

363 364 365 366 367 368
        if(isset($this->columns[$column][2]['default'])) {

            return $this->columns[$column][2]['default'];
        } else
            return null;
    }
doctrine's avatar
doctrine committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    /**
     * @return mixed
     */
    final public function getIdentifier() {
        return $this->identifier;
    }
    /**
     * @return integer
     */
    final public function getIdentifierType() {
        return $this->identifierType;
    }
    /**
     * hasColumn
     * @return boolean
     */
    final public function hasColumn($name) {
        return isset($this->columns[$name]);
    }
    /**
     * @param mixed $key
     * @return void
     */
    final public function setPrimaryKey($key) {
        switch(gettype($key)):
            case "array":
                $this->primaryKeys = array_values($key);
            break;
            case "string":
                $this->primaryKeys[] = $key;
            break;
        endswitch;
    }
    /**
     * returns all primary keys
     * @return array
     */
    final public function getPrimaryKeys() {
        return $this->primaryKeys;
    }
    /**
     * @return boolean
     */
    final public function hasPrimaryKey($key) {
        return in_array($key,$this->primaryKeys);
    }
    /**
     * @param $sequence
     * @return void
     */
    final public function setSequenceName($sequence) {
zYne's avatar
zYne committed
420
        $this->options['sequenceName'] = $sequence;
doctrine's avatar
doctrine committed
421 422 423 424 425
    }
    /**
     * @return string   sequence name
     */
    final public function getSequenceName() {
zYne's avatar
zYne committed
426
        return $this->options['sequenceName'];
doctrine's avatar
doctrine committed
427
    }
428 429 430 431
    /**
     * getParents
     */
    final public function getParents() {
doctrine's avatar
doctrine committed
432
        return $this->parents;
433 434 435 436 437
    }
    /**
     * @return boolean
     */
    final public function hasInheritanceMap() {
zYne's avatar
zYne committed
438
        return (empty($this->options['inheritanceMap']));
doctrine's avatar
doctrine committed
439 440 441 442 443
    }
    /**
     * @return array        inheritance map (array keys as fields)
     */
    final public function getInheritanceMap() {
zYne's avatar
zYne committed
444
        return $this->options['inheritanceMap'];
doctrine's avatar
doctrine committed
445 446 447 448 449 450 451 452 453 454
    }
    /**
     * return all composite paths in the form [component1].[component2]. . .[componentN]
     * @return array
     */
    final public function getCompositePaths() {
        $array = array();
        $name  = $this->getComponentName();
        foreach($this->bound as $k=>$a) {
            try {
455
            $fk = $this->getRelation($k);
doctrine's avatar
doctrine committed
456 457 458 459 460 461 462 463 464 465 466 467 468
            switch($fk->getType()):
                case Doctrine_Relation::ONE_COMPOSITE:
                case Doctrine_Relation::MANY_COMPOSITE:
                    $n = $fk->getTable()->getComponentName();
                    $array[] = $name.".".$n;
                    $e = $fk->getTable()->getCompositePaths();
                    if( ! empty($e)) {
                        foreach($e as $name) {
                            $array[] = $name.".".$n.".".$name;
                        }
                    }
                break;
            endswitch;
469
            } catch(Doctrine_Table_Exception $e) {
470

doctrine's avatar
doctrine committed
471 472 473 474 475 476 477 478 479
            }
        }
        return $array;
    }
    /**
     * returns all bound relations
     *
     * @return array
     */
480
    public function getBounds() {
doctrine's avatar
doctrine committed
481 482 483 484 485 486 487 488
        return $this->bound;
    }
    /**
     * returns a bound relation array
     *
     * @param string $name
     * @return array
     */
489
    public function getBound($name) {
490
        if( ! isset($this->bound[$name]))
491
            throw new Doctrine_Table_Exception('Unknown bound '.$name);
doctrine's avatar
doctrine committed
492 493 494 495 496 497 498 499 500

        return $this->bound[$name];
    }
    /**
     * returns a bound relation array
     *
     * @param string $name
     * @return array
     */
501
    public function getBoundForName($name, $component) {
502

doctrine's avatar
doctrine committed
503
        foreach($this->bound as $k => $bound) {
504
            $e = explode('.', $bound[0]);
505

506
            if($bound[3] == $name && $e[0] == $component) {
doctrine's avatar
doctrine committed
507 508 509
                return $this->bound[$k];
            }
        }
510
        throw new Doctrine_Table_Exception('Unknown bound '.$name);
doctrine's avatar
doctrine committed
511 512 513 514 515 516 517
    }
    /**
     * returns the alias for given component name
     *
     * @param string $name
     * @return string
     */
zYne's avatar
zYne committed
518
    public function getAlias($name) {
doctrine's avatar
doctrine committed
519 520
        if(isset($this->boundAliases[$name]))
            return $this->boundAliases[$name];
521

doctrine's avatar
doctrine committed
522 523 524 525
        return $name;
    }
    /**
     * returns component name for given alias
526
     *
doctrine's avatar
doctrine committed
527 528 529
     * @param string $alias
     * @return string
     */
zYne's avatar
zYne committed
530
    public function getAliasName($alias) {
531
        if($name = array_search($alias, $this->boundAliases))
doctrine's avatar
doctrine committed
532
            return $name;
533

zYne's avatar
zYne committed
534
        return $alias;
doctrine's avatar
doctrine committed
535 536 537
    }
    /**
     * unbinds all relations
538
     *
doctrine's avatar
doctrine committed
539 540
     * @return void
     */
541
    public function unbindAll() {
doctrine's avatar
doctrine committed
542 543 544 545 546 547 548 549 550 551 552
        $this->bound        = array();
        $this->relations    = array();
        $this->boundAliases = array();
    }
    /**
     * unbinds a relation
     * returns true on success, false on failure
     *
     * @param $name
     * @return boolean
     */
553
    public function unbind($name) {
doctrine's avatar
doctrine committed
554 555
        if( ! isset($this->bound[$name]))
            return false;
556

doctrine's avatar
doctrine committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
        unset($this->bound[$name]);

        if(isset($this->relations[$name]))
            unset($this->relations[$name]);

        if(isset($this->boundAliases[$name]))
            unset($this->boundAliases[$name]);

        return true;
    }
    /**
     * binds a relation
     *
     * @param string $name
     * @param string $field
     * @return void
     */
574
    public function bind($name, $field, $type, $localKey) {
doctrine's avatar
doctrine committed
575
        if(isset($this->relations[$name]))
576
            unset($this->relations[$name]);
doctrine's avatar
doctrine committed
577 578 579 580 581 582 583 584 585 586 587

        $e          = explode(" as ",$name);
        $name       = $e[0];

        if(isset($e[1])) {
            $alias = $e[1];
            $this->boundAliases[$name] = $alias;
        } else
            $alias = $name;


588
        $this->bound[$alias] = array($field, $type, $localKey, $name);
doctrine's avatar
doctrine committed
589 590 591 592 593
    }
    /**
     * getComponentName
     * @return string                   the component name
     */
594
    public function getComponentName() {
zYne's avatar
zYne committed
595
        return $this->options['name'];
doctrine's avatar
doctrine committed
596 597
    }
    /**
zYne's avatar
zYne committed
598
     * @return Doctrine_Connection
doctrine's avatar
doctrine committed
599
     */
600
    public function getConnection() {
zYne's avatar
zYne committed
601
        return $this->connection;
doctrine's avatar
doctrine committed
602
    }
603 604 605 606 607 608 609 610 611 612 613
    /**
     * hasRelatedComponent
     * @return boolean
     */
    final public function hasRelatedComponent($name, $component) {
         return (strpos($this->bound[$name][0], $component.'.') !== false);
    }
    /**
     * @param string $name              component name of which a foreign key object is bound
     * @return boolean
     */
614
    final public function hasRelation($name) {
615 616 617 618 619 620 621 622 623 624
        if(isset($this->bound[$name]))
            return true;

        foreach($this->bound as $k=>$v)
        {
            if($this->hasRelatedComponent($k, $name))
                return true;
        }
        return false;
    }
doctrine's avatar
doctrine committed
625
    /**
626 627
     * getRelation
     *
doctrine's avatar
doctrine committed
628 629 630
     * @param string $name              component name of which a foreign key object is bound
     * @return Doctrine_Relation
     */
631
    final public function getRelation($name, $recursive = true) {
632 633
        $original = $name;

doctrine's avatar
doctrine committed
634
        if(isset($this->relations[$name]))
zYne's avatar
zYne committed
635
            return $this->relations[$name]; 
doctrine's avatar
doctrine committed
636 637 638 639 640 641 642 643

        if(isset($this->bound[$name])) {
            $type       = $this->bound[$name][1];
            $local      = $this->bound[$name][2];
            list($component, $foreign) = explode(".",$this->bound[$name][0]);
            $alias      = $name;
            $name       = $this->bound[$alias][3];

zYne's avatar
zYne committed
644
            $table      = $this->connection->getTable($name);
doctrine's avatar
doctrine committed
645

zYne's avatar
zYne committed
646
            if($component == $this->options['name'] || in_array($component, $this->parents)) {
doctrine's avatar
doctrine committed
647 648 649 650 651 652 653

                // ONE-TO-ONE
                if($type == Doctrine_Relation::ONE_COMPOSITE ||
                   $type == Doctrine_Relation::ONE_AGGREGATE) {
                    if( ! isset($local))
                        $local = $table->getIdentifier();

zYne's avatar
zYne committed
654
                    $relation = new Doctrine_Relation_LocalKey($table, $foreign, $local, $type, $alias);
doctrine's avatar
doctrine committed
655
                } else
zYne's avatar
zYne committed
656 657
                    $relation = new Doctrine_Relation_ForeignKey($table, $foreign, $local, $type, $alias);

doctrine's avatar
doctrine committed
658

zYne's avatar
zYne committed
659
            } elseif($component == $name ||
zYne's avatar
zYne committed
660
                    ($component == $alias)) {     //  && ($name == $this->options['name'] || in_array($name,$this->parents))
zYne's avatar
zYne committed
661

doctrine's avatar
doctrine committed
662 663 664 665
                if( ! isset($local))
                    $local = $this->identifier;

                // ONE-TO-MANY or ONE-TO-ONE
666
                $relation = new Doctrine_Relation_ForeignKey($table, $local, $foreign, $type, $alias);
doctrine's avatar
doctrine committed
667 668 669 670 671

            } else {
                // MANY-TO-MANY
                // only aggregate relations allowed

672
                if($type != Doctrine_Relation::MANY_AGGREGATE)
673
                    throw new Doctrine_Table_Exception("Only aggregate relations are allowed for many-to-many relations");
doctrine's avatar
doctrine committed
674

zYne's avatar
zYne committed
675
                $classes = array_merge($this->parents, array($this->options['name']));
doctrine's avatar
doctrine committed
676 677 678

                foreach(array_reverse($classes) as $class) {
                    try {
679
                        $bound = $table->getBoundForName($class, $component);
doctrine's avatar
doctrine committed
680
                        break;
681
                    } catch(Doctrine_Table_Exception $exc) { }
doctrine's avatar
doctrine committed
682
                }
683 684 685 686 687
                if( ! isset($bound)) 
                    throw new Doctrine_Table_Exception("Couldn't map many-to-many relation for "
                                                      . $this->options['name'] . " and $name. Components use different join tables.");


doctrine's avatar
doctrine committed
688 689 690
                if( ! isset($local))
                    $local = $this->identifier;

691 692
                $e2     = explode('.', $bound[0]);
                $fields = explode('-', $e2[1]);
doctrine's avatar
doctrine committed
693 694

                if($e2[0] != $component)
695
                    throw new Doctrine_Table_Exception($e2[0] . ' doesn\'t match ' . $component);
doctrine's avatar
doctrine committed
696

zYne's avatar
zYne committed
697
                $associationTable = $this->connection->getTable($e2[0]);
doctrine's avatar
doctrine committed
698 699 700

                if(count($fields) > 1) {
                    // SELF-REFERENCING THROUGH JOIN TABLE
701
                    $this->relations[$e2[0]] = new Doctrine_Relation_ForeignKey($associationTable, $local, $fields[0],Doctrine_Relation::MANY_COMPOSITE, $e2[0]);
702

703
                    $relation = new Doctrine_Relation_Association_Self($table, $associationTable, $fields[0], $fields[1], $type, $alias);
doctrine's avatar
doctrine committed
704
                } else {
705 706

                    // auto initialize a new one-to-one relationship for association table
707 708
                    $associationTable->bind($this->getComponentName(),  $associationTable->getComponentName(). '.' .$e2[1], Doctrine_Relation::ONE_AGGREGATE, $this->getIdentifier());
                    $associationTable->bind($table->getComponentName(), $associationTable->getComponentName(). '.' .$foreign, Doctrine_Relation::ONE_AGGREGATE, $table->getIdentifier());
709

doctrine's avatar
doctrine committed
710
                    // NORMAL MANY-TO-MANY RELATIONSHIP
711
                    $this->relations[$e2[0]] = new Doctrine_Relation_ForeignKey($associationTable, $local, $e2[1], Doctrine_Relation::MANY_COMPOSITE, $e2[0]);
doctrine's avatar
doctrine committed
712

713
                    $relation = new Doctrine_Relation_Association($table, $associationTable, $e2[1], $foreign, $type, $alias);
doctrine's avatar
doctrine committed
714 715 716
                }

            }
zYne's avatar
zYne committed
717

doctrine's avatar
doctrine committed
718 719 720
            $this->relations[$alias] = $relation;
            return $this->relations[$alias];
        }
zYne's avatar
zYne committed
721

722 723 724 725 726 727
        // load all relations
        $this->getRelations();
        
        if($recursive) {
            return $this->getRelation($original, false);
        } else {
zYne's avatar
zYne committed
728
            throw new Doctrine_Table_Exception($this->options['name'] . " doesn't have a relation to " . $original);     
729
        }
doctrine's avatar
doctrine committed
730 731 732 733 734 735
    }
    /**
     * returns an array containing all foreign key objects
     *
     * @return array
     */
736
    final public function getRelations() {
doctrine's avatar
doctrine committed
737 738
        $a = array();
        foreach($this->bound as $k=>$v) {
739
            $this->getRelation($k);
doctrine's avatar
doctrine committed
740 741 742 743 744 745 746 747 748 749 750
        }

        return $this->relations;
    }
    /**
     * sets the database table name
     *
     * @param string $name              database table name
     * @return void
     */
    final public function setTableName($name) {
zYne's avatar
zYne committed
751
        $this->options['tableName'] = $name;
doctrine's avatar
doctrine committed
752 753 754 755 756 757 758 759
    }

    /**
     * returns the database table name
     *
     * @return string
     */
    final public function getTableName() {
zYne's avatar
zYne committed
760
        return $this->options['tableName'];
doctrine's avatar
doctrine committed
761 762 763 764 765 766 767 768 769
    }
    /**
     * create
     * creates a new record
     *
     * @param $array                    an array where keys are field names and values representing field values
     * @return Doctrine_Record
     */
    public function create(array $array = array()) {
770
        $this->data         = $array;
chtito's avatar
chtito committed
771
        $record = new $this->options['name']($this, true);
doctrine's avatar
doctrine committed
772 773 774 775 776 777 778
        $this->data         = array();
        return $record;
    }
    /**
     * finds a record by its identifier
     *
     * @param $id                       database row id
zYne's avatar
zYne committed
779
     * @return Doctrine_Record|false    a record for given database identifier
doctrine's avatar
doctrine committed
780 781 782 783 784
     */
    public function find($id) {
        if($id !== null) {
            if( ! is_array($id))
                $id = array($id);
785
            else
doctrine's avatar
doctrine committed
786 787 788 789
                $id = array_values($id);

            $query  = $this->query." WHERE ".implode(" = ? AND ",$this->primaryKeys)." = ?";
            $query  = $this->applyInheritance($query);
doctrine's avatar
doctrine committed
790 791


zYne's avatar
zYne committed
792
            $params = array_merge($id, array_values($this->options['inheritanceMap']));
doctrine's avatar
doctrine committed
793

zYne's avatar
zYne committed
794
            $stmt  = $this->connection->execute($query,$params);
doctrine's avatar
doctrine committed
795 796

            $this->data = $stmt->fetch(PDO::FETCH_ASSOC);
doctrine's avatar
doctrine committed
797 798

            if($this->data === false)
799
                return false;
pookey's avatar
pookey committed
800 801
            
            return $this->getRecord();
doctrine's avatar
doctrine committed
802
        }
pookey's avatar
pookey committed
803
        return false;
doctrine's avatar
doctrine committed
804 805 806 807 808 809 810
    }
    /**
     * applyInheritance
     * @param $where                    query where part to be modified
     * @return string                   query where part with column aggregation inheritance added
     */
    final public function applyInheritance($where) {
zYne's avatar
zYne committed
811
        if( ! empty($this->options['inheritanceMap'])) {
doctrine's avatar
doctrine committed
812
            $a = array();
zYne's avatar
zYne committed
813
            foreach($this->options['inheritanceMap'] as $field => $value) {
doctrine's avatar
doctrine committed
814 815 816 817 818 819 820 821 822 823 824 825 826 827
                $a[] = $field." = ?";
            }
            $i = implode(" AND ",$a);
            $where .= " AND $i";
        }
        return $where;
    }
    /**
     * findAll
     * returns a collection of records
     *
     * @return Doctrine_Collection
     */
    public function findAll() {
zYne's avatar
zYne committed
828
        $graph = new Doctrine_Query($this->connection);
zYne's avatar
zYne committed
829
        $users = $graph->query("FROM ".$this->options['name']);
doctrine's avatar
doctrine committed
830 831 832
        return $users;
    }
    /**
833 834
     * findByDql
     * finds records with given DQL where clause
doctrine's avatar
doctrine committed
835 836
     * returns a collection of records
     *
837
     * @param string $dql               DQL after WHERE clause
doctrine's avatar
doctrine committed
838 839 840
     * @param array $params             query parameters
     * @return Doctrine_Collection
     */
841
    public function findBySql($dql, array $params = array()) {
zYne's avatar
zYne committed
842
        $q = new Doctrine_Query($this->connection);
zYne's avatar
zYne committed
843
        $users = $q->query("FROM ".$this->options['name']." WHERE ".$dql, $params);
doctrine's avatar
doctrine committed
844 845
        return $users;
    }
846

847 848 849
    public function findByDql($dql, array $params = array()) {
        return $this->findBySql($dql, $params);
    }
doctrine's avatar
doctrine committed
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
    /**
     * clear
     * clears the first level cache (identityMap)
     *
     * @return void
     */
    public function clear() {
        $this->identityMap = array();
    }
    /**
     * getRecord
     * first checks if record exists in identityMap, if not
     * returns a new record
     *
     * @return Doctrine_Record
     */
    public function getRecord() {
zYne's avatar
zYne committed
867 868
        $this->data = array_change_key_case($this->data, CASE_LOWER);

doctrine's avatar
doctrine committed
869 870 871 872 873 874 875
        $key = $this->getIdentifier();

        if( ! is_array($key))
            $key = array($key);

        foreach($key as $k) {
            if( ! isset($this->data[$k]))
876
                throw new Doctrine_Exception("Primary key value for $k wasn't found");
877

doctrine's avatar
doctrine committed
878 879
            $id[] = $this->data[$k];
        }
880

doctrine's avatar
doctrine committed
881 882 883 884
        $id = implode(' ', $id);

        if(isset($this->identityMap[$id]))
            $record = $this->identityMap[$id];
885
        else {      
zYne's avatar
zYne committed
886
            $record = new $this->options['name']($this);
doctrine's avatar
doctrine committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900
            $this->identityMap[$id] = $record;
        }
        $this->data = array();

        return $record;
    }
    /**
     * @param $id                       database row id
     * @throws Doctrine_Find_Exception
     */
    final public function getProxy($id = null) {
        if($id !== null) {
            $query = "SELECT ".implode(", ",$this->primaryKeys)." FROM ".$this->getTableName()." WHERE ".implode(" = ? && ",$this->primaryKeys)." = ?";
            $query = $this->applyInheritance($query);
901

zYne's avatar
zYne committed
902
            $params = array_merge(array($id), array_values($this->options['inheritanceMap']));
doctrine's avatar
doctrine committed
903

zYne's avatar
zYne committed
904
            $this->data = $this->connection->execute($query,$params)->fetch(PDO::FETCH_ASSOC);
doctrine's avatar
doctrine committed
905 906

            if($this->data === false)
907
                return false;
doctrine's avatar
doctrine committed
908 909 910
        }
        return $this->getRecord();
    }
911 912
    /**
     * count
913
     *
914 915 916
     * @return integer
     */
    public function count() {
zYne's avatar
zYne committed
917
        $a = $this->connection->getDBH()->query("SELECT COUNT(1) FROM ".$this->options['tableName'])->fetch(PDO::FETCH_NUM);
918 919
        return current($a);
    }
doctrine's avatar
doctrine committed
920 921 922 923
    /**
     * @return Doctrine_Query                           a Doctrine_Query object
     */
    public function getQueryObject() {
zYne's avatar
zYne committed
924
        $graph = new Doctrine_Query($this->getConnection());
doctrine's avatar
doctrine committed
925 926 927 928 929 930 931 932 933 934 935 936
        $graph->load($this->getComponentName());
        return $graph;
    }
    /**
     * execute
     * @param string $query
     * @param array $array
     * @param integer $limit
     * @param integer $offset
     */
    public function execute($query, array $array = array(), $limit = null, $offset = null) {
        $coll  = new Doctrine_Collection($this);
zYne's avatar
zYne committed
937
        $query = $this->connection->modifyLimitQuery($query,$limit,$offset);
doctrine's avatar
doctrine committed
938
        if( ! empty($array)) {
zYne's avatar
zYne committed
939
            $stmt = $this->connection->getDBH()->prepare($query);
doctrine's avatar
doctrine committed
940 941
            $stmt->execute($array);
        } else {
zYne's avatar
zYne committed
942
            $stmt = $this->connection->getDBH()->query($query);
doctrine's avatar
doctrine committed
943 944 945 946 947 948 949 950 951 952 953
        }
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stmt->closeCursor();

        foreach($data as $row) {
            $this->data = $row;
            $record = $this->getRecord();
            $coll->add($record);
        }
        return $coll;
    }
doctrine's avatar
doctrine committed
954 955 956 957 958 959 960 961
    /**
     * sets enumerated value array for given field
     *
     * @param string $field
     * @param array $values
     * @return void
     */
    final public function setEnumValues($field, array $values) {
zYne's avatar
zYne committed
962
        $this->options['enumMap'][strtolower($field)] = $values;
doctrine's avatar
doctrine committed
963
    }
doctrine's avatar
doctrine committed
964 965 966 967 968
    /**
     * @param string $field
     * @return array
     */
    final public function getEnumValues($field) {
zYne's avatar
zYne committed
969 970
        if(isset($this->options['enumMap'][$field]))
            return $this->options['enumMap'][$field];
doctrine's avatar
doctrine committed
971 972 973
        else
            return array();
    }
doctrine's avatar
doctrine committed
974 975
    /**
     * enumValue
976 977 978 979
     *
     * @param string $field
     * @param integer $index
     * @return mixed
doctrine's avatar
doctrine committed
980 981
     */
    final public function enumValue($field, $index) {
982
        if ($index instanceof Doctrine_Null)
983
            return $index;
984

zYne's avatar
zYne committed
985
        return isset($this->options['enumMap'][$field][$index]) ? $this->options['enumMap'][$field][$index] : $index;
doctrine's avatar
doctrine committed
986
    }
987 988 989 990 991 992
    /**
     * invokeSet
     *
     * @param mixed $value
     */
    public function invokeSet(Doctrine_Record $record, $name, $value) {
chtito's avatar
chtito committed
993
        if( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_SET))
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
            return $value;

        $method = 'set' . $name;

        if(method_exists($record, $method)) {
            return $record->$method($value);
        }

        return $value;
    }
    /**
     * invokeGet
     *
     * @param mixed $value
     */
    public function invokeGet(Doctrine_Record $record, $name, $value) {
chtito's avatar
chtito committed
1010
        if( ! ($this->getAttribute(Doctrine::ATTR_ACCESSORS) & Doctrine::ACCESSOR_GET))
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
            return $value;

        $method = 'get' . $name;

        if(method_exists($record, $method)) {
            return $record->$method($value);
        }

        return $value;
    }
doctrine's avatar
doctrine committed
1021 1022
    /**
     * enumIndex
1023 1024 1025 1026
     *
     * @param string $field
     * @param mixed $value
     * @return mixed
doctrine's avatar
doctrine committed
1027 1028
     */
    final public function enumIndex($field, $value) {
zYne's avatar
zYne committed
1029
        if( ! isset($this->options['enumMap'][$field])) 
1030 1031
            $values = array();
        else
zYne's avatar
zYne committed
1032
            $values = $this->options['enumMap'][$field];
1033 1034

        return array_search($value, $values);
doctrine's avatar
doctrine committed
1035
    }
doctrine's avatar
doctrine committed
1036
    /**
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
     * getDefinitionOf
     *
     * @return string       ValueWrapper class name on success, false on failure
     */
    public function getValueWrapperOf($column) {
        if(isset($this->columns[$column][2]['wrapper']))
            return $this->columns[$column][2]['wrapper'];
        
        return false;
    }
    /**
     * getColumnCount
     *
     * @return integer      the number of columns in this table
doctrine's avatar
doctrine committed
1051 1052
     */
    final public function getColumnCount() {
1053
        return $this->columnCount;
doctrine's avatar
doctrine committed
1054
    }
doctrine's avatar
doctrine committed
1055

doctrine's avatar
doctrine committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    /**
     * returns all columns and their definitions
     *
     * @return array
     */
    final public function getColumns() {
        return $this->columns;
    }
    /**
     * returns an array containing all the column names
     *
     * @return array
     */
    public function getColumnNames() {
        return array_keys($this->columns);
    }
doctrine's avatar
doctrine committed
1072 1073
    /**
     * getDefinitionOf
1074 1075
     *
     * @return mixed        array on success, false on failure
doctrine's avatar
doctrine committed
1076 1077 1078 1079
     */
    public function getDefinitionOf($column) {
        if(isset($this->columns[$column]))
            return $this->columns[$column];
1080 1081

        return false;
doctrine's avatar
doctrine committed
1082
    }
doctrine's avatar
doctrine committed
1083 1084
    /**
     * getTypeOf
1085 1086
     *
     * @return mixed        string on success, false on failure
doctrine's avatar
doctrine committed
1087 1088 1089
     */
    public function getTypeOf($column) {
        if(isset($this->columns[$column]))
1090
            return $this->columns[$column][0];
1091 1092

        return false;
doctrine's avatar
doctrine committed
1093
    }
doctrine's avatar
doctrine committed
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
    /**
     * setData
     * doctrine uses this function internally
     * users are strongly discouraged to use this function
     *
     * @param array $data               internal data
     * @return void
     */
    public function setData(array $data) {
        $this->data = $data;
    }
    /**
     * returns the maximum primary key value
     *
     * @return integer
     */
    final public function getMaxIdentifier() {
        $sql  = "SELECT MAX(".$this->getIdentifier().") FROM ".$this->getTableName();
zYne's avatar
zYne committed
1112
        $stmt = $this->connection->getDBH()->query($sql);
doctrine's avatar
doctrine committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
        $data = $stmt->fetch(PDO::FETCH_NUM);
        return isset($data[0])?$data[0]:1;
    }
    /**
     * returns simple cached query
     *
     * @return string
     */
    final public function getQuery() {
        return $this->query;
    }
    /**
1125
     * returns internal data, used by Doctrine_Record instances
doctrine's avatar
doctrine committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
     * when retrieving data from database
     *
     * @return array
     */
    final public function getData() {
        return $this->data;
    }
    /**
     * returns a string representation of this object
     *
     * @return string
     */
    public function __toString() {
        return Doctrine_Lib::getTableAsString($this);
    }
}
1142