Table.php 41.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
<?php
/*
 *  $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_Table   represents a database table
 *                  each Doctrine_Table holds the information of foreignKeys and associations
 *
 *
 * @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
 */
class Doctrine_Table extends Doctrine_Configurable implements Countable
{
    /**
     * @var array $data                                 temporary data which is then loaded into Doctrine_Record::$data
     */
    private $data             = array();
    /**
     * @var array $primaryKeys                          an array containing all primary key column names
     */
    private $primaryKeys      = array();
    /**
     * @var mixed $identifier
     */
    private $identifier;
    /**
     * @see Doctrine_Identifier constants
     * @var integer $identifierType                     the type of identifier this table uses
     */
    private $identifierType;
    /**
     * @var Doctrine_Connection $conn                   Doctrine_Connection object that created this table
     */
    private $conn;
    /**
     * @var array $identityMap                          first level cache
     */
    private $identityMap        = array();
    /**
     * @var Doctrine_Table_Repository $repository       record repository
     */
    private $repository;
    /**
     * @var array $columns                  an array of column definitions,
     *                                      keys as column names and values as column definitions
     *
zYne's avatar
zYne committed
69
     *                                      the definition array has atleast the following values:
70
     *
zYne's avatar
zYne committed
71 72
     *                                      -- type         the column type, eg. 'integer'
     *                                      -- length       the column length, eg. 11
73
     *
zYne's avatar
zYne committed
74 75 76 77 78
     *                                      additional keys:
     *                                      -- notnull      whether or not the column is marked as notnull
     *                                      -- values       enum values
     *                                      -- notblank     notblank validator + notnull constraint
     *                                      ... many more
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
     */
    protected $columns          = array();
    /**
     * @var array $columnAliases            an array of column aliases
     *                                      keys as column aliases and values as column names
     */
    protected $columnAliases    = array();
    /**
     * @var integer $columnCount            cached column count, Doctrine_Record uses this column count in when
     *                                      determining its state
     */
    private $columnCount;
    /**
     * @var boolean $hasDefaultValues       whether or not this table has default values
     */
    private $hasDefaultValues;
    /**
     * @var array $options                  an array containing all options
     *
     *      -- name                         name of the component, for example component name of the GroupTable is 'Group'
     *
     *      -- parents                      the parent classes of this component
     *
     *      -- declaringClass               name of the table definition declaring class (when using inheritance the class
     *                                      that defines the table structure can be any class in the inheritance hierarchy, 
     *                                      hence we need reflection to check out which class actually calls setTableDefinition)
     *
     *      -- 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
     *
     *      -- 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
     *
     *      -- enumMap                      enum value arrays
     *
     *      -- inheritanceMap               inheritanceMap is used for inheritance mapping, keys representing columns and values
     *                                      the column values that should correspond to child classes
     *
     *      -- type                         table type (mysql example: INNODB)
     *
     *      -- charset                      character set
     *
     *      -- foreignKeys                  the foreign keys of this table
     *
zYne's avatar
zYne committed
124 125 126
     *      -- checks                       the check constraints of this table, eg. 'price > dicounted_price'
     *
     *      -- collation                    collation attribute
127 128 129 130 131 132
     *
     *      -- indexes                      the index definitions of this table
     *
     *      -- treeImpl                     the tree implementation of this table (if any)
     *
     *      -- treeOptions                  the tree options
133 134
     *
     *      -- versioning
135 136
     */
    protected $options          = array('name'           => null,
zYne's avatar
zYne committed
137 138 139 140 141 142 143 144 145 146 147 148 149
                                        'tableName'      => null,
                                        'sequenceName'   => null,
                                        'inheritanceMap' => array(),
                                        'enumMap'        => array(),
                                        'engine'         => null,
                                        'charset'        => null,
                                        'collation'      => null,
                                        'treeImpl'       => null,
                                        'treeOptions'    => null,
                                        'indexes'        => array(),
                                        'parents'        => array(),
                                        'versioning'     => null,
                                        );
150 151 152 153 154 155 156 157
    /**
     * @var Doctrine_Tree $tree                 tree object associated with this table
     */
    protected $tree;
    /**
     * @var Doctrine_Relation_Parser $_parser   relation parser object
     */
    protected $_parser;
zYne's avatar
zYne committed
158
    /**
zYne's avatar
zYne committed
159
     * @var array $_templates                   an array containing all templates attached to this table
zYne's avatar
zYne committed
160
     */
zYne's avatar
zYne committed
161 162 163
    protected $_templates;


164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    /**
     * the constructor
     * @throws Doctrine_Connection_Exception    if there are no opened connections
     * @throws Doctrine_Table_Exception         if there is already an instance of this table
     * @return void
     */
    public function __construct($name, Doctrine_Connection $conn)
    {
        $this->conn = $conn;

        $this->setParent($this->conn);

        $this->options['name'] = $name;
        $this->_parser = new Doctrine_Relation_Parser($this);

        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 {
            if ($class == "Doctrine_Record") {
                break;                        
            }

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

        // reverse names
        $names = array_reverse($names);
        // save parents
        array_pop($names);
        $this->options['parents'] = $names;

        // create database table
        if (method_exists($record, 'setTableDefinition')) {
            $record->setTableDefinition();

            // set the table definition for the given tree implementation
            if ($this->isTree()) {
                $this->getTree()->setTableDefinition();
            }
            
            $this->columnCount = count($this->columns);

            if (isset($this->columns)) {
                // get the declaring class of setTableDefinition method
zYne's avatar
zYne committed
218 219
                $method = new ReflectionMethod($this->options['name'], 'setTableDefinition');
                $class  = $method->getDeclaringClass();
220 221 222 223 224 225 226 227 228

                $this->options['declaringClass'] = $class;

                if ( ! isset($this->options['tableName'])) {
                    $this->options['tableName'] = Doctrine::tableize($class->getName());
                }
                switch (count($this->primaryKeys)) {
                case 0:
                    $this->columns = array_merge(array('id' =>
zYne's avatar
zYne committed
229 230 231 232
                                                  array('type'          => 'integer',
                                                        'length'        => 20,
                                                        'autoincrement' => true,
                                                        'primary'       => true)), $this->columns);
233 234 235

                    $this->primaryKeys[] = 'id';
                    $this->identifier = 'id';
zYne's avatar
zYne committed
236
                    $this->identifierType = Doctrine::IDENTIFIER_AUTOINC;
237 238 239 240 241
                    $this->columnCount++;
                    break;
                default:
                    if (count($this->primaryKeys) > 1) {
                        $this->identifier = $this->primaryKeys;
zYne's avatar
zYne committed
242
                        $this->identifierType = Doctrine::IDENTIFIER_COMPOSITE;
243 244 245

                    } else {
                        foreach ($this->primaryKeys as $pk) {
zYne's avatar
zYne committed
246
                            $e = $this->columns[$pk];
247 248 249 250 251 252 253 254 255 256

                            $found = false;

                            foreach ($e as $option => $value) {
                                if ($found)
                                    break;

                                $e2 = explode(':', $option);

                                switch (strtolower($e2[0])) {
zYne's avatar
zYne committed
257 258 259 260 261 262 263 264 265 266 267 268
                                    case 'autoincrement':
                                    case 'autoinc':
                                        $this->identifierType = Doctrine::IDENTIFIER_AUTOINC;
                                        $found = true;
                                        break;
                                    case 'seq':
                                    case 'sequence':
                                        $this->identifierType = Doctrine::IDENTIFIER_SEQUENCE;
                                        $found = true;
    
                                        if ($value) {
                                            $this->options['sequenceName'] = $value;
269
                                        } else {
zYne's avatar
zYne committed
270 271 272 273 274
                                            if (($sequence = $this->getAttribute(Doctrine::ATTR_DEFAULT_SEQUENCE)) !== null) {
                                                $this->options['sequenceName'] = $sequence;
                                            } else {
                                                $this->options['sequenceName'] = $this->conn->getSequenceName($this->options['tableName']);
                                            }
275
                                        }
zYne's avatar
zYne committed
276
                                        break;
277 278 279
                                }
                            }
                            if ( ! isset($this->identifierType)) {
zYne's avatar
zYne committed
280
                                $this->identifierType = Doctrine::IDENTIFIER_NATURAL;
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
                            }
                            $this->identifier = $pk;
                        }
                    }
                }
            }
        } else {
            throw new Doctrine_Table_Exception("Class '$name' has no table definition.");
        }

        $record->setUp();

        // if tree, set up tree
        if ($this->isTree()) {
            $this->getTree()->setUp();
        }
        $this->repository = new Doctrine_Table_Repository($this);
    }
    /**
     * export
     * exports this table to database based on column and option definitions
     *
     * @throws Doctrine_Connection_Exception    if some error other than Doctrine::ERR_ALREADY_EXISTS
     *                                          occurred during the create table operation
     * @return boolean                          whether or not the export operation was successful
     *                                          false if table already existed in the database
     */
    public function export() 
    {
zYne's avatar
zYne committed
310
        $this->conn->export->exportTable($this);
311
    }
zYne's avatar
zYne committed
312 313 314 315 316 317
    /**
     * getExportableFormat
     * returns exportable presentation of this object
     *
     * @return array
     */
318
    public function getExportableFormat($parseForeignKeys = true)
zYne's avatar
zYne committed
319 320 321 322 323
    {
        $columns = array();
        $primary = array();

        foreach ($this->getColumns() as $name => $column) {
zYne's avatar
zYne committed
324
            $definition = $column;
zYne's avatar
zYne committed
325 326

            switch ($definition['type']) {
zYne's avatar
zYne committed
327 328 329 330 331 332 333 334 335 336
                case 'enum':
                    if (isset($definition['default'])) {
                        $definition['default'] = $this->enumIndex($name, $definition['default']);
                    }
                    break;
                case 'boolean':
                    if (isset($definition['default'])) {
                        $definition['default'] = $this->getConnection()->convertBooleans($definition['default']);
                    }
                    break;
zYne's avatar
zYne committed
337 338 339 340 341 342 343
            }
            $columns[$name] = $definition;

            if(isset($definition['primary']) && $definition['primary']) {
                $primary[] = $name;
            }
        }
zYne's avatar
zYne committed
344
        $options['foreignKeys'] = array();
zYne's avatar
zYne committed
345

346 347 348
        if ($parseForeignKeys) {
            if ($this->getAttribute(Doctrine::ATTR_EXPORT) & Doctrine::EXPORT_CONSTRAINTS) {
    
zYne's avatar
zYne committed
349 350 351 352 353
                $constraints = array();

                $emptyIntegrity = array('onUpdate' => null,
                                        'onDelete' => null);

354 355 356
                foreach ($this->getRelations() as $name => $relation) {
                    $fk = $relation->toArray();
                    $fk['foreignTable'] = $relation->getTable()->getTableName();
zYne's avatar
zYne committed
357

358
                    if ($relation->getTable() === $this && in_array($relation->getLocal(), $primary)) {
zYne's avatar
zYne committed
359 360 361 362 363
                        if ($relation->hasConstraint()) {
                            throw new Doctrine_Table_Exception("Badly constructed integrity constraints.");
                        }
                        
                        continue;
364
                    }
zYne's avatar
zYne committed
365 366 367

                    $integrity = array('onUpdate' => $fk['onUpdate'],
                                       'onDelete' => $fk['onDelete']);
zYne's avatar
zYne committed
368 369
                    
                    if ($relation instanceof Doctrine_Relation_LocalKey) {
zYne's avatar
zYne committed
370
                        $def = array('local'        => $relation->getLocal(),
zYne's avatar
zYne committed
371
                                     'foreign'      => $relation->getForeign(),
zYne's avatar
zYne committed
372 373 374 375 376 377 378 379 380 381 382
                                     'foreignTable' => $relation->getTable()->getTableName());

                        if (($key = array_search($def, $options['foreignKeys'])) === false) {
                            $options['foreignKeys'][] = $def;

                            $constraints[] = $integrity;
                        } else {
                            if ($integrity !== $emptyIntegrity) {
                                $constraints[$key] = $integrity;
                            }
                        }
383
                    }
zYne's avatar
zYne committed
384 385 386 387
                }

                foreach ($constraints as $k => $def) {
                    $options['foreignKeys'][$k] = array_merge($options['foreignKeys'][$k], $def);
zYne's avatar
zYne committed
388
                }
zYne's avatar
zYne committed
389

zYne's avatar
zYne committed
390 391
            }
        }
zYne's avatar
zYne committed
392
        $options['primary'] = $primary;
zYne's avatar
zYne committed
393
        
zYne's avatar
zYne committed
394 395 396
        return array('tableName' => $this->getOption('tableName'), 
                     'columns'   => $columns, 
                     'options'   => array_merge($this->getOptions(), $options));
zYne's avatar
zYne committed
397
    }
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    /**
     * exportConstraints
     * exports the constraints of this table into database based on option definitions
     *
     * @throws Doctrine_Connection_Exception    if something went wrong on db level
     * @return void
     */
    public function exportConstraints()
    {
        try {
            $this->conn->beginTransaction();

            foreach ($this->options['index'] as $index => $definition) {
                $this->conn->export->createIndex($this->options['tableName'], $index, $definition);
            }
            $this->conn->commit();
        } catch(Doctrine_Connection_Exception $e) {
            $this->conn->rollback();

            throw $e;
        }
    }
    /**
     * getRelationParser
     * return the relation parser associated with this table
     *
     * @return Doctrine_Relation_Parser     relation parser object
     */
    public function getRelationParser()
    {
        return $this->_parser;
    }
    /**
     * __get
     * an alias for getOption
     *
     * @param string $option
     */
    public function __get($option)
    {
        if (isset($this->options[$option])) {
            return $this->options[$option];
        }
        return null;
    }
    /**
     * __isset
     *
     * @param string $option
     */
    public function __isset($option) 
    {
        return isset($this->options[$option]);
    }
zYne's avatar
zYne committed
452 453 454 455 456 457 458 459
    /**
     * getOptions
     * returns all options of this table and the associated values
     *
     * @return array    all options and their values
     */
    public function getOptions()
    {
zYne's avatar
zYne committed
460
        return $this->options;
zYne's avatar
zYne committed
461
    }
462 463 464 465 466 467 468 469 470 471 472
    /**
     * addForeignKey
     *
     * adds a foreignKey to this table
     *
     * @return void
     */
    public function addForeignKey(array $definition)
    {
        $this->options['foreignKeys'][] = $definition;
    }
zYne's avatar
zYne committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    /**
     * addCheckConstraint
     * 
     * adds a check constraint to this table
     *
     * @return void
     */
    public function addCheckConstraint($definition, $name)
    {
    	if (is_string($name)) {
            $this->options['checks'][$name] = $definition;
        } else {
            $this->options['checks'][] = $definition;
        }
        
        return $this;
    }
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
    /**
     * addIndex
     * 
     * adds an index to this table
     *
     * @return void
     */
    public function addIndex($index, array $definition)
    {
        $this->options['indexes'][$index] = $definition;
    }
    /**
     * getIndex
     *
     * @return array|boolean        array on success, FALSE on failure
     */
    public function getIndex($index) 
    {
        if (isset($this->options['indexes'][$index])) {
            return $this->options['indexes'][$index];
        }

        return false;
    }
    public function bind($args, $type)
    {
    	$options = array();
        $options['type'] = $type;
        
zYne's avatar
zYne committed
519 520 521 522
        if ( ! isset($args[1])) {
            $args[1] = array();
        }
        
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        // the following is needed for backwards compatibility
        if (is_string($args[1])) {
            if ( ! isset($args[2])) {
                $args[2] = array();
            } elseif (is_string($args[2])) {
                $args[2] = (array) $args[2];
            }

            $classes = array_merge($this->options['parents'], array($this->getComponentName()));


            $e = explode('.', $args[1]);
            if (in_array($e[0], $classes)) {
                if ($options['type'] >= Doctrine_Relation::MANY) {
                    $options['foreign'] = $e[1];                                             	
                } else {
                    $options['local'] = $e[1];
                }
            } else {
                $e2 = explode(' as ', $args[0]);
                if ($e[0] !== $e2[0] && ( ! isset($e2[1]) || $e[0] !== $e2[1])) {
                    $options['refClass'] = $e[0];
                }

                $options['foreign'] = $e[1];
            }

            $options = array_merge($args[2], $options);

            $this->_parser->bind($args[0], $options);
zYne's avatar
zYne committed
553
        } else { 
554 555 556 557
            $options = array_merge($args[1], $options);
            $this->_parser->bind($args[0], $options);
        }
    }
meus's avatar
meus committed
558 559 560 561 562 563 564 565 566 567 568 569

    /** 
     * hasRelation
     *
     * @param string $alias      the relation to check if exists
     * @return boolean           true if the relation exists otherwise false
     */
    public function hasRelation($alias)
    {
        return $this->_parser->hasRelation($alias);
    }	

570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    /**
     * getRelation
     *
     * @param string $alias      relation alias
     */
    public function getRelation($alias, $recursive = true)
    {
        return $this->_parser->getRelation($alias, $recursive);
    }
    /**
     * getRelations
     * returns an array containing all relation objects
     *
     * @return array        an array of Doctrine_Relation objects
     */
    public function getRelations()
    {
        return $this->_parser->getRelations();
    }
    /**
     * 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());
    }
    /**
     * getRepository
     *
     * @return Doctrine_Table_Repository
     */
    public function getRepository()
    {
        return $this->repository;
    }
    /**
     * setOption
     * sets an option and returns this object in order to 
     * allow flexible method chaining
     *
     * @see Doctrine_Table::$_options   for available options
     * @param string $name              the name of the option to set
     * @param mixed $value              the value of the option
     * @return Doctrine_Table           this object
     */
    public function setOption($name, $value)
    {
        switch ($name) {
        case 'name':
        case 'tableName':
            break;
        case 'enumMap':
        case 'inheritanceMap':
        case 'index':
        case 'treeOptions':
            if ( ! is_array($value)) {
                throw new Doctrine_Table_Exception($name . ' should be an array.');
            }
            break;
        }
        $this->options[$name] = $value;
    }
    /**
     * getOption
     * returns the value of given option
     *
     * @param string $name  the name of the option
     * @return mixed        the value of given option
     */
    public function getOption($name)
    {
        if (isset($this->options[$name])) {
            return $this->options[$name];
        }
        return null;
    }
    /**
     * getColumnName
     *
     * returns a column name for column alias
     * if the actual name for the alias cannot be found
     * this method returns the given alias
     *
     * @param string $alias         column alias
     * @return string               column name
     */
    public function getColumnName($alias)
    {
        $alias = strtolower($alias);
        if(isset($this->columnAliases[$alias])) {
            return $this->columnAliases[$alias];
        }

        return $alias;
    }
    /**
     * setColumn
     *
     * @param string $name
     * @param string $type
     * @param integer $length
     * @param mixed $options
     * @throws Doctrine_Table_Exception     if trying use wrongly typed parameter
     * @return void
     */
    public function setColumn($name, $type, $length = null, $options = array())
    {
        if (is_string($options)) {
            $options = explode('|', $options);
        }

        foreach ($options as $k => $option) {
            if (is_numeric($k)) {
                if ( ! empty($option)) {
                    $options[$option] = true;
                }
                unset($options[$k]);
            }
        }

        $name  = strtolower($name);
        $parts = explode(' as ', $name);

        if (count($parts) > 1) {
            $this->columnAliases[$parts[1]] = $parts[0];
            $name = $parts[0];
        }


703 704 705 706 707

        if ($length == null) {
            switch ($type) {
                case 'string':
                case 'clob':
708
                case 'float':
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
                case 'integer':
                case 'array':
                case 'object':
                case 'blob':
                case 'gzip':
                    // use php int max
                    $length = 2147483647;
                break;
                case 'boolean':
                    $length = 1;
                case 'date':
                    // YYYY-MM-DD ISO 8601
                    $length = 10;
                case 'time':
                    // HH:NN:SS+00:00 ISO 8601
                    $length = 14;
                case 'timestamp':
                    // YYYY-MM-DDTHH:MM:SS+00:00 ISO 8601
                    $length = 25;
                break;
            }
730 731
        }

zYne's avatar
zYne committed
732 733 734
        $this->columns[$name] = $options;
        $this->columns[$name]['type'] = $type;
        $this->columns[$name]['length'] = $length;
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

        if (isset($options['primary'])) {
            $this->primaryKeys[] = $name;
        }
        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;
    }
    /**
     * getDefaultValueOf
     * returns the default value(if any) for given column
     *
     * @param string $column
     * @return mixed
     */
    public function getDefaultValueOf($column)
    {
        $column = strtolower($column);
        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
766 767
        if (isset($this->columns[$column]['default'])) {
            return $this->columns[$column]['default'];
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
        } else {
            return null;
        }
    }
    /**
     * @return mixed
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }
    /**
     * @return integer
     */
    public function getIdentifierType()
    {
        return $this->identifierType;
    }
    /**
     * hasColumn
     * @return boolean
     */
    public function hasColumn($name)
    {
        return isset($this->columns[$name]);
    }
    /**
     * @param mixed $key
     * @return void
     */
    public function setPrimaryKey($key)
    {
        switch (gettype($key)) {
        case "array":
            $this->primaryKeys = array_values($key);
            break;
        case "string":
            $this->primaryKeys[] = $key;
            break;
        };
    }
    /**
     * returns all primary keys
     * @return array
     */
    public function getPrimaryKeys()
    {
        return $this->primaryKeys;
    }
    /**
     * @return boolean
     */
    public function hasPrimaryKey($key)
    {
        return in_array($key,$this->primaryKeys);
    }
    /**
     * @return Doctrine_Connection
     */
    public function getConnection()
    {
        return $this->conn;
    }
    /**
     * 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()) {
        $this->data         = $array;
        $record = new $this->options['name']($this, true);
        $this->data         = array();
        return $record;
    }
    /**
     * finds a record by its identifier
     *
     * @param $id                       database row id
     * @return Doctrine_Record|false    a record for given database identifier
     */
    public function find($id)
    {
        if ($id !== null) {
            if ( ! is_array($id)) {
                $id = array($id);
            } else {
                $id = array_values($id);
            }

zYne's avatar
zYne committed
859 860 861 862
            $records = Doctrine_Query::create()
                       ->from($this->getComponentName())
                       ->where(implode(' = ? AND ', $this->primaryKeys) . ' = ?')
                       ->execute($id);
863

zYne's avatar
zYne committed
864
            if (count($records) === 0) {
865
                return false;
zYne's avatar
zYne committed
866
            }
867

zYne's avatar
zYne committed
868
            return $records->getFirst();
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
        }
        return false;
    }
    /**
     * applyInheritance
     * @param $where                    query where part to be modified
     * @return string                   query where part with column aggregation inheritance added
     */
    final public function applyInheritance($where)
    {
        if ( ! empty($this->options['inheritanceMap'])) {
            $a = array();
            foreach ($this->options['inheritanceMap'] as $field => $value) {
                $a[] = $field . ' = ?';
            }
            $i = implode(' AND ', $a);
            $where .= ' AND ' . $i;
        }
        return $where;
    }
    /**
     * findAll
     * returns a collection of records
     *
     * @return Doctrine_Collection
     */
    public function findAll()
    {
        $graph = new Doctrine_Query($this->conn);
        $users = $graph->query("FROM ".$this->options['name']);
        return $users;
    }
    /**
     * findByDql
     * finds records with given DQL where clause
     * returns a collection of records
     *
     * @param string $dql               DQL after WHERE clause
     * @param array $params             query parameters
     * @return Doctrine_Collection
     */
    public function findBySql($dql, array $params = array()) {
        $q = new Doctrine_Query($this->conn);
zYne's avatar
zYne committed
912
        $users = $q->query('FROM ' . $this->options['name'] . ' WHERE ' . $dql, $params);
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
        return $users;
    }

    public function findByDql($dql, array $params = array()) {
        return $this->findBySql($dql, $params);
    }
    /**
     * clear
     * clears the first level cache (identityMap)
     *
     * @return void
     */
    public function clear()
    {
        $this->identityMap = array();
    }
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    /**
     * addRecord
     * adds a record to identity map
     *
     * @param Doctrine_Record $record       record to be added
     * @return boolean
     */
    public function addRecord(Doctrine_Record $record)
    {
        $id = implode(' ', $record->identifier());
        
        if (isset($this->identityMap[$id])) {
            return false;
        }
        
        $this->identityMap[$id] = $record;
        
        return true;
    }
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
    /**
     * getRecord
     * first checks if record exists in identityMap, if not
     * returns a new record
     *
     * @return Doctrine_Record
     */
    public function getRecord()
    {
    	if ( ! empty($this->data)) {
            $this->data = array_change_key_case($this->data, CASE_LOWER);
    
            $key = $this->getIdentifier();
    
            if ( ! is_array($key)) {
                $key = array($key);
            }
    
zYne's avatar
zYne committed
966
            $found = false;
967 968
            foreach ($key as $k) {
                if ( ! isset($this->data[$k])) {
zYne's avatar
zYne committed
969 970 971
                    // primary key column not found return new record
                    $found = true;
                    break;
972 973 974
                }
                $id[] = $this->data[$k];
            }
zYne's avatar
zYne committed
975 976 977
            
            if ($found) {
                $recordName = $this->getClassnameToReturn();
zYne's avatar
zYne committed
978 979
                $record = new $recordName($this, true);
                $this->data = array();
zYne's avatar
zYne committed
980 981 982 983 984

                return $record;
            }


985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
            $id = implode(' ', $id);
    
            if (isset($this->identityMap[$id])) {
                $record = $this->identityMap[$id];
                $record->hydrate($this->data);
            } else {
                $recordName = $this->getClassnameToReturn();
                $record = new $recordName($this);
                $this->identityMap[$id] = $record;
            }
            $this->data = array();
        } else {
            $recordName = $this->getClassnameToReturn();
            $record = new $recordName($this, true);
        }


        return $record;
    }

    /**
     * Get the classname to return. Most often this is just the options['name']
     *
     * Check the subclasses option and the inheritanceMap for each subclass to see 
     * if all the maps in a subclass is met. If this is the case return that 
     * subclass name. If no subclasses match or if there are no subclasses defined 
     * return the name of the class for this tables record.
     *
     * @todo this function could use reflection to check the first time it runs 
     * if the subclassing option is not set. 
     *
     * @return string The name of the class to create
     *
     */ 
    public function getClassnameToReturn()
    {
        if (!isset($this->options['subclasses'])) {
            return $this->options['name'];
        }
        foreach ($this->options['subclasses'] as $subclass) {
            $table = $this->conn->getTable($subclass);
            $inheritanceMap = $table->getOption('inheritanceMap');
            $nomatch = false;
            foreach ($inheritanceMap as $key => $value) {
1029
                if ( ! isset($this->data[$key]) || $this->data[$key] != $value) {
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
                    $nomatch = true;
                    break;
                }
            }
            if ( ! $nomatch) {
                return $table->getComponentName();
            }
        }
        return $this->options['name'];
    }

    /**
     * @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);

            $params = array_merge(array($id), array_values($this->options['inheritanceMap']));

            $this->data = $this->conn->execute($query,$params)->fetch(PDO::FETCH_ASSOC);

            if ($this->data === false)
                return false;
        }
        return $this->getRecord();
    }
    /**
     * count
     *
     * @return integer
     */
    public function count()
    {
zYne's avatar
zYne committed
1069
        $a = $this->conn->execute('SELECT COUNT(1) FROM ' . $this->options['tableName'])->fetch(Doctrine::FETCH_NUM);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        return current($a);
    }
    /**
     * @return Doctrine_Query                           a Doctrine_Query object
     */
    public function getQueryObject()
    {
        $graph = new Doctrine_Query($this->getConnection());
        $graph->load($this->getComponentName());
        return $graph;
    }
    /**
     * @param string $field
     * @return array
     */
zYne's avatar
zYne committed
1085
    public function getEnumValues($field)
1086
    {
zYne's avatar
zYne committed
1087 1088
        if (isset($this->columns[$field]['values'])) {
            return $this->columns[$field]['values'];
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        } else {
            return array();
        }
    }
    /**
     * enumValue
     *
     * @param string $field
     * @param integer $index
     * @return mixed
     */
    public function enumValue($field, $index)
    {
        if ($index instanceof Doctrine_Null)
            return $index;

zYne's avatar
zYne committed
1105
        return isset($this->columns[$field]['values'][$index]) ? $this->columns[$field]['values'][$index] : $index;
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
    }
    /**
     * enumIndex
     *
     * @param string $field
     * @param mixed $value
     * @return mixed
     */
    public function enumIndex($field, $value)
    {
        $values = $this->getEnumValues($field);

        return array_search($value, $values);
    }
    /**
     * getColumnCount
     *
     * @return integer      the number of columns in this table
     */
zYne's avatar
zYne committed
1125
    public function getColumnCount()
1126 1127 1128 1129 1130 1131 1132 1133 1134
    {
        return $this->columnCount;
    }

    /**
     * returns all columns and their definitions
     *
     * @return array
     */
zYne's avatar
zYne committed
1135
    public function getColumns()
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
    {
        return $this->columns;
    }
    /**
     * returns an array containing all the column names
     *
     * @return array
     */
    public function getColumnNames()
    {
        return array_keys($this->columns);
    }
    /**
     * getDefinitionOf
     *
     * @return mixed        array on success, false on failure
     */
    public function getDefinitionOf($column)
    {
        if (isset($this->columns[$column])) {
            return $this->columns[$column];
        }
        return false;
    }
    /**
     * getTypeOf
     *
     * @return mixed        string on success, false on failure
     */
    public function getTypeOf($column)
    {
        if (isset($this->columns[$column])) {
zYne's avatar
zYne committed
1168
            return $this->columns[$column]['type'];
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        }
        return false;
    }
    /**
     * 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 internal data, used by Doctrine_Record instances
     * when retrieving data from database
     *
     * @return array
     */
zYne's avatar
zYne committed
1190
    public function getData()
1191 1192 1193
    {
        return $this->data;
    }
zYne's avatar
zYne committed
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    /**
     * prepareValue
     * this method performs special data preparation depending on 
     * the type of the given column
     *
     * 1. It unserializes array and object typed columns
     * 2. Uncompresses gzip typed columns
     * 3. Gets the appropriate enum values for enum typed columns
     * 4. Initializes special null object pointer for null values (for fast column existence checking purposes)
     *
     * example:
     * <code type='php'>
     * $field = 'name';
     * $value = null;
     * $table->prepareValue($field, $value); // Doctrine_Null
     * </code>
     *
     * @throws Doctrine_Table_Exception     if unserialization of array/object typed column fails or
     * @throws Doctrine_Table_Exception     if uncompression of gzip typed column fails         *
     * @param string $field     the name of the field
     * @param string $value     field value
     * @return mixed            prepared value
     */
    public function prepareValue($field, $value)
    {
1219
        if ($value === self::$_null) {
zYne's avatar
zYne committed
1220
            return self::$_null;
1221 1222
        } else if ($value === null) {
            return null;
zYne's avatar
zYne committed
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
        } else {
            $type = $this->getTypeOf($field);

            switch ($type) {
                case 'array':
                case 'object':
                    if (is_string($value)) {
                        $value = unserialize($value);

                        if ($value === false) {
                            throw new Doctrine_Table_Exception('Unserialization of ' . $field . ' failed.');
                        }
                        return $value;
                    }
                break;
                case 'gzip':
                    $value = gzuncompress($value);

                    if ($value === false) {
                        throw new Doctrine_Table_Exception('Uncompressing of ' . $field . ' failed.');
                    }
                    return $value;
                break;
                case 'enum':
                    return $this->enumValue($field, $value);
                break;
                case 'boolean':
                    return (boolean) $value;
                break;
                case 'integer':
zYne's avatar
zYne committed
1253
                    // don't do any casting here PHP INT_MAX is smaller than what the databases support
1254
                break;
zYne's avatar
zYne committed
1255 1256 1257 1258
            }
        }
        return $value;
    }
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    /**
     * getter for associated tree
     *
     * @return mixed  if tree return instance of Doctrine_Tree, otherwise returns false
     */    
    public function getTree() {
        if (isset($this->options['treeImpl'])) {
            if ( ! $this->tree) {
                $options = isset($this->options['treeOptions']) ? $this->options['treeOptions'] : array();
                $this->tree = Doctrine_Tree::factory($this, 
                    $this->options['treeImpl'], 
                    $options
                );
            }
            return $this->tree;
        }
        return false;
    }
    public function getComponentName() 
    {
        return $this->options['name'];
    }
    public function getTableName()
    {
        return $this->options['tableName'];
    }
    public function setTableName($tableName)
    {
        $this->options['tableName'] = $tableName;	
    }
    /**
     * determine if table acts as tree
     *
     * @return mixed  if tree return true, otherwise returns false
     */    
    public function isTree() {
        return ( ! is_null($this->options['treeImpl'])) ? true : false;
    }
zYne's avatar
zYne committed
1297 1298

    public function getTemplate($template)
zYne's avatar
zYne committed
1299
    {
zYne's avatar
zYne committed
1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
    	if ( ! isset($this->_templates[$template])) {
            throw new Doctrine_Table_Exception('Template ' . $template . ' not loaded');
    	}
    	
    	return $this->_templates[$template];
    }
    
    public function addTemplate($template, Doctrine_Template $impl)
    {
        $this->_templates[$template] = $impl;
zYne's avatar
zYne committed
1310
    }
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
    /**
     * returns a string representation of this object
     *
     * @return string
     */
    public function __toString()
    {
        return Doctrine_Lib::getTableAsString($this);
    }
}