Session.php 29.1 KB
Newer Older
doctrine's avatar
doctrine committed
1 2 3 4
<?php
require_once("Configurable.class.php");
require_once("Record.class.php");
/**
5 6
 * Doctrine_Session
 *
doctrine's avatar
doctrine committed
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
 * @package     Doctrine ORM
 * @url         www.phpdoctrine.com
 * @license     LGPL
 * @version     1.0 alpha
 */
abstract class Doctrine_Session extends Doctrine_Configurable implements Countable, IteratorAggregate {
    /**
     * Doctrine_Session is in open state when it is opened and there are no active transactions
     */
    const STATE_OPEN        = 0;
    /**
     * Doctrine_Session is in closed state when it is closed
     */
    const STATE_CLOSED      = 1;
    /**
     * Doctrine_Session is in active state when it has one active transaction
     */
    const STATE_ACTIVE      = 2;
    /**
     * Doctrine_Session is in busy state when it has multiple active transactions
     */
    const STATE_BUSY        = 3;
    /**
     * @var $dbh                            the database handle
     */
    private $dbh;
33 34 35 36
    /**
     * @see Doctrine_Session::STATE_* constants
     * @var boolean $state                  the current state of the session
     */
37
    private $state              = 0;
38 39 40
    /**
     * @var integer $transaction_level      the nesting level of transactions, used by transaction methods
     */
41
    private $transaction_level  = 0;
42 43

    /**
44
     * @var PDO $cacheHandler               cache handler
45 46
     */
    private $cacheHandler;
doctrine's avatar
doctrine committed
47 48 49 50
    /**
     * @var array $tables                   an array containing all the initialized Doctrine_Table objects
     *                                      keys representing Doctrine_Table component names and values as Doctrine_Table objects
     */
51
    protected $tables           = array();
doctrine's avatar
doctrine committed
52
    /**
53
     * @var Doctrine_Validator $validator   transaction validator
doctrine's avatar
doctrine committed
54
     */
55
    protected $validator;
doctrine's avatar
doctrine committed
56 57 58 59
    /**
     * @var array $update                   two dimensional pending update list, the records in
     *                                      this list will be updated when transaction is committed
     */
60
    protected $update           = array();
doctrine's avatar
doctrine committed
61 62 63 64
    /**
     * @var array $insert                   two dimensional pending insert list, the records in
     *                                      this list will be inserted when transaction is committed
     */
65
    protected $insert           = array();
doctrine's avatar
doctrine committed
66 67 68 69
    /**
     * @var array $delete                   two dimensional pending delete list, the records in
     *                                      this list will be deleted when transaction is committed
     */
70
    protected $delete           = array();
71

doctrine's avatar
doctrine committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86



    /**
     * the constructor
     * @param PDO $pdo  -- database handle
     */
    public function __construct(Doctrine_Manager $manager,PDO $pdo) {
        $this->dbh      = $pdo;

        $this->setParent($manager);

        $this->state = Doctrine_Session::STATE_OPEN;

        $this->dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
doctrine's avatar
doctrine committed
87 88 89 90 91 92 93 94 95 96 97 98
        $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);   

        switch($this->getAttribute(Doctrine::ATTR_CACHE)):
            case Doctrine::CACHE_SQLITE:
                $dir = $this->getAttribute(Doctrine::ATTR_CACHE_DIR).DIRECTORY_SEPARATOR;
                $dsn = "sqlite:".$dir."data.cache";

                $this->cacheHandler = Doctrine_DB::getConn($dsn);
                $this->cacheHandler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->cacheHandler->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
            break;
        endswitch;
doctrine's avatar
doctrine committed
99 100 101

        $this->getAttribute(Doctrine::ATTR_LISTENER)->onOpen($this);
    }
doctrine's avatar
doctrine committed
102 103 104 105

    public function getCacheHandler() {
        return $this->cacheHandler;
    }
doctrine's avatar
doctrine committed
106
    /**
107 108 109
     * returns the state of this session
     *
     * @see Doctrine_Session::STATE_* constants
doctrine's avatar
doctrine committed
110 111 112 113 114 115
     * @return integer          the session state
     */
    public function getState() {
        return $this->state;
    }
    /**
116 117
     * returns the manager that created this session
     *
doctrine's avatar
doctrine committed
118 119 120 121 122 123
     * @return Doctrine_Manager
     */
    public function getManager() {
        return $this->getParent();
    }
    /**
124 125 126
     * returns the database handler of which this session uses
     *
     * @return object PDO       the database handler
doctrine's avatar
doctrine committed
127 128 129 130 131 132 133
     */
    public function getDBH() {
        return $this->dbh;
    }
    /**
     * query
     * queries the database with Doctrine Query Language
134 135 136
     *
     * @param string $query         DQL query
     * @param array $params         query parameters
doctrine's avatar
doctrine committed
137 138
     */
    final public function query($query,array $params = array()) {
139
        $parser = new Doctrine_Query($this);
doctrine's avatar
doctrine committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

        return $parser->query($query, $params);
    }
    /**
     * queries the database with limit and offset
     * added to the query and returns a PDOStatement object
     *
     * @param string $query
     * @param integer $limit
     * @param integer $offset
     * @return PDOStatement
     */
    public function select($query,$limit = 0,$offset = 0) {
        if($limit > 0 || $offset > 0)
            $query = $this->modifyLimitQuery($query,$limit,$offset);
155

doctrine's avatar
doctrine committed
156 157 158
        return $this->dbh->query($query);
    }
    /**
159 160 161 162
     * @param string $query     sql query
     * @param array $params     query parameters
     *
     * @return PDOStatement
doctrine's avatar
doctrine committed
163 164 165 166 167 168 169 170 171 172 173
     */
    public function execute($query, array $params = array()) {
        if( ! empty($params)) {
            $stmt = $this->dbh->prepare($query);
            $stmt->execute($params);
            return $stmt;
        } else {
            return $this->dbh->query($query);
        }
    }
    /**
174 175 176
     * whether or not this session has table $name initialized
     *
     * @param $mixed $name
doctrine's avatar
doctrine committed
177 178 179 180 181 182
     * @return boolean
     */
    public function hasTable($name) {
        return isset($this->tables[$name]);
    }
    /**
183 184
     * returns a table object for given component name
     *
doctrine's avatar
doctrine committed
185 186 187 188 189 190
     * @param string $name              component name
     * @return object Doctrine_Table
     */
    public function getTable($name) {
        if(isset($this->tables[$name]))
            return $this->tables[$name];
doctrine's avatar
doctrine committed
191

doctrine's avatar
doctrine committed
192 193
        $class = $name."Table";

194
        if(class_exists($class) && in_array("Doctrine_Table", class_parents($class))) {
doctrine's avatar
doctrine committed
195
            return new $class($name);
doctrine's avatar
doctrine committed
196 197
        } else {

doctrine's avatar
doctrine committed
198
            return new Doctrine_Table($name);
doctrine's avatar
doctrine committed
199
        }
doctrine's avatar
doctrine committed
200 201
    }
    /**
202 203 204
     * returns an array of all initialized tables
     *
     * @return array
doctrine's avatar
doctrine committed
205 206 207 208 209
     */
    public function getTables() {
        return $this->tables;
    }
    /**
210 211 212
     * returns an iterator that iterators through all 
     * initialized table objects
     *
doctrine's avatar
doctrine committed
213 214 215 216 217 218
     * @return ArrayIterator
     */
    public function getIterator() {
        return new ArrayIterator($this->tables);
    }
    /**
219 220
     * returns the count of initialized table objects
     *
doctrine's avatar
doctrine committed
221 222 223 224 225 226
     * @return integer
     */
    public function count() {
        return count($this->tables);
    }
    /**
227
     * @param $objTable             a Doctrine_Table object to be added into registry
doctrine's avatar
doctrine committed
228 229 230 231 232 233 234 235 236 237 238 239
     * @return boolean
     */
    public function addTable(Doctrine_Table $objTable) {
        $name = $objTable->getComponentName();

        if(isset($this->tables[$name]))
            return false;

        $this->tables[$name] = $objTable;
        return true;
    }
    /**
240 241
     * creates a record
     *
doctrine's avatar
doctrine committed
242 243 244 245 246 247 248 249
     * create                       creates a record
     * @param string $name          component name
     * @return Doctrine_Record      Doctrine_Record object
     */
    public function create($name) {
        return $this->getTable($name)->create();
    }

doctrine's avatar
doctrine committed
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

    /**
     * buildFlushTree
     * builds a flush tree that is used in transactions
     *
     * @return array
     */
    public function buildFlushTree(array $tables) {
        $tree = array();
        foreach($tables as $k => $table) {
            $k = $k.$table;
            if( ! ($table instanceof Doctrine_Table))
                $table = $this->getTable($table);

            $nm     = $table->getComponentName();

            $index  = array_search($nm,$tree);
            if($index === false) {
                $tree[] = $nm;
                $index  = max(array_keys($tree));

                //print "$k -- adding <b>$nm</b>...<br \>";
            }

            $rels = $table->getForeignKeys();
            
            // group relations
            
            foreach($rels as $key => $rel) {
                if($rel instanceof Doctrine_ForeignKey) {
                    unset($rels[$key]);
                    array_unshift($rels, $rel);
                }
            }

            foreach($rels as $rel) {
                $name   = $rel->getTable()->getComponentName();
                $index2 = array_search($name,$tree);
                $type   = $rel->getType();

                // skip self-referenced relations
                if($name === $nm)
                    continue;

                if($rel instanceof Doctrine_ForeignKey) {
                    if($index2 !== false) {
                        if($index2 >= $index)
                            continue;

                        unset($tree[$index]);
                        array_splice($tree,$index2,0,$nm);
                        $index = $index2;
                        
                        //print "$k -- pushing $nm into $index2...<br \>";

                    } else {
                        $tree[] = $name;
                        //print "$k -- adding $nm :$name...<br>";
                    }

                } elseif($rel instanceof Doctrine_LocalKey) {
                    if($index2 !== false) {
                        if($index2 <= $index)
                            continue;

                        unset($tree[$index2]);
                        array_splice($tree,$index,0,$name);

                        //print "$k -- pushing $name into <b>$index</b>...<br \>";

                    } else {
                        //array_splice($tree, $index, 0, $name);
                        array_unshift($tree,$name);
                        $index++;

                        //print "$k -- pushing <b>$name</b> into 0...<br \>";
                    }
                } elseif($rel instanceof Doctrine_Association) {
                    $t = $rel->getAssociationFactory();
                    $n = $t->getComponentName();
                    
                    if($index2 !== false)
                        unset($tree[$index2]);
                    
                    array_splice($tree,$index, 0,$name);
                    $index++;

                    $index3 = array_search($n,$tree);

                    if($index3 !== false) {
                        if($index3 >= $index)
                            continue;

                        unset($tree[$index]);
                        array_splice($tree,$index3,0,$n);
                        $index = $index2;

                        //print "$k -- pushing $nm into $index3...<br \>";

                    } else {
                        $tree[] = $n;
                        //print "$k -- adding $nm :$name...<br>";
                    }
                }
                //print_r($tree);
            }
            //print_r($tree);

        }
        return array_values($tree);
doctrine's avatar
doctrine committed
360 361 362
    }

    /**
363 364 365 366
     * flush                        
     * saves all the records from all tables
     * this operation is isolated using a transaction
     *
doctrine's avatar
doctrine committed
367 368 369 370 371 372 373 374
     * @return void
     */
    public function flush() {
        $this->beginTransaction();
        $this->saveAll();
        $this->commit();
    }
    /**
375 376
     * saveAll                      
     * saves all the records from all tables
377 378
     *
     * @return void
doctrine's avatar
doctrine committed
379 380
     */
    private function saveAll() {
doctrine's avatar
doctrine committed
381
        $tree = $this->buildFlushTree($this->tables);
doctrine's avatar
doctrine committed
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397

        foreach($tree as $name) {
            $table = $this->tables[$name];

            foreach($table->getRepository() as $record) {
                $this->save($record);
            }
        }
        foreach($tree as $name) {
            $table = $this->tables[$name];
            foreach($table->getRepository() as $record) {
                $record->saveAssociations();
            }
        }
    }
    /**
398
     * clear
399
     * clears all repositories
400
     *
doctrine's avatar
doctrine committed
401 402 403
     * @return void
     */
    public function clear() {
404 405 406
        foreach($this->tables as $k => $table) {
            $table->getRepository()->evictAll();
            $table->clear();
doctrine's avatar
doctrine committed
407 408 409 410 411 412
        }
        $this->tables = array();
    }
    /**
     * close
     * closes the session
413
     *
doctrine's avatar
doctrine committed
414 415 416 417 418 419 420 421 422 423 424 425
     * @return void
     */
    public function close() {
        $this->getAttribute(Doctrine::ATTR_LISTENER)->onPreClose($this);

        $this->clear();
        $this->state = Doctrine_Session::STATE_CLOSED;
        
        $this->getAttribute(Doctrine::ATTR_LISTENER)->onClose($this);
    }
    /**
     * get the current transaction nesting level
426 427
     *
     * @return integer
doctrine's avatar
doctrine committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
     */
    public function getTransactionLevel() {
        return $this->transaction_level;
    }
    /**
     * beginTransaction
     * starts a new transaction
     * @return void
     */
    public function beginTransaction() {
        if($this->transaction_level == 0) {

            if($this->getAttribute(Doctrine::ATTR_LOCKMODE) == Doctrine::LOCK_PESSIMISTIC) {
                $this->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionBegin($this);
                $this->dbh->beginTransaction();
                $this->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionBegin($this);
            }
            $this->state  = Doctrine_Session::STATE_ACTIVE;
        } else {
            $this->state = Doctrine_Session::STATE_BUSY;
        }
        $this->transaction_level++;
    }
    /**
     * commits the current transaction
     * if lockmode is optimistic this method starts a transaction 
     * and commits it instantly
     * @return void
     */
    public function commit() {

459 460
        $this->transaction_level--;
    
doctrine's avatar
doctrine committed
461
        if($this->transaction_level == 0) {
462 463
    
    
doctrine's avatar
doctrine committed
464 465
            if($this->getAttribute(Doctrine::ATTR_LOCKMODE) == Doctrine::LOCK_OPTIMISTIC) {
                $this->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionBegin($this);
466
    
doctrine's avatar
doctrine committed
467
                $this->dbh->beginTransaction();
468
    
doctrine's avatar
doctrine committed
469 470
                $this->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionBegin($this);
            }
471 472
    
            if($this->getAttribute(Doctrine::ATTR_VLD))
doctrine's avatar
doctrine committed
473
                $this->validator = new Doctrine_Validator();
474

475 476 477 478 479 480 481 482 483 484 485 486
            try {
                
                $this->bulkInsert();
                $this->bulkUpdate();
                $this->bulkDelete();

                if($this->getAttribute(Doctrine::ATTR_VLD)) {
                    if($this->validator->hasErrors()) {
                        $this->rollback();
                        throw new Doctrine_Validator_Exception($this->validator);
                    }
                }
doctrine's avatar
doctrine committed
487

488 489
            } catch(PDOException $e) {
                $this->rollback();
doctrine's avatar
doctrine committed
490

491
                throw new Doctrine_Exception($e->getMessage());
doctrine's avatar
doctrine committed
492 493 494 495
            }
            $this->dbh->commit();
            $this->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionCommit($this);

496
            $this->delete = array();
doctrine's avatar
doctrine committed
497
            $this->state  = Doctrine_Session::STATE_OPEN;
498
    
doctrine's avatar
doctrine committed
499
            $this->validator = null;
500
    
doctrine's avatar
doctrine committed
501 502 503 504 505
        } elseif($this->transaction_level == 1)
            $this->state = Doctrine_Session::STATE_ACTIVE;
    }
    /**
     * rollback
506
     * rolls back all transactions
doctrine's avatar
doctrine committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
     * @return void
     */
    public function rollback() {
        $this->getAttribute(Doctrine::ATTR_LISTENER)->onPreTransactionRollback($this);

        $this->transaction_level = 0;
        $this->dbh->rollback();
        $this->state = Doctrine_Session::STATE_OPEN;

        $this->getAttribute(Doctrine::ATTR_LISTENER)->onTransactionRollback($this);
    }
    /**
     * bulkInsert
     * inserts all the objects in the pending insert list into database
     * @return void
     */
    public function bulkInsert() {
524 525 526
        if(empty($this->insert))
            return false;

doctrine's avatar
doctrine committed
527
        foreach($this->insert as $name => $inserts) {
doctrine's avatar
doctrine committed
528
            if( ! isset($inserts[0]))
doctrine's avatar
doctrine committed
529 530 531 532 533
                continue;

            $record    = $inserts[0];
            $table     = $record->getTable();
            $seq       = $table->getSequenceName();
534

doctrine's avatar
doctrine committed
535 536
            $increment = false;
            $keys      = $table->getPrimaryKeys();
537
            $id        = null;
doctrine's avatar
doctrine committed
538

539
            if(count($keys) == 1 && $keys[0] == $table->getIdentifier()) {
doctrine's avatar
doctrine committed
540 541
                $increment = true;
            }
542

doctrine's avatar
doctrine committed
543 544 545 546 547
            foreach($inserts as $k => $record) {
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($record);
                // listen the onPreInsert event
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreInsert($record);

548 549

                $this->insert($record);
550 551 552
                if($increment) {
                    if($k == 0) {
                        // record uses auto_increment column
553
    
554 555 556 557 558 559 560
                        $id = $table->getMaxIdentifier();
                    }
    
                    $record->setID($id);
                    $id++;
                } else
                    $record->setID(true);
doctrine's avatar
doctrine committed
561 562 563 564 565 566 567

                // listen the onInsert event
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onInsert($record);

                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onSave($record);
            }
        }
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        $this->insert = array();
        return true;
    }
    /**
     * returns maximum identifier values
     *
     * @param array $names          an array of component names
     * @return array
     */   
    public function getMaximumValues(array $names) {
        $values = array();
        foreach($names as $name) {
            $table     = $this->tables[$name];
            $keys      = $table->getPrimaryKeys();
            $tablename = $table->getTableName();

584
            if(count($keys) == 1 && $keys[0] == $table->getIdentifier()) {
585 586
                // record uses auto_increment column

587
                $sql    = "SELECT MAX(".$table->getIdentifier().") FROM ".$tablename;
588 589 590 591 592 593 594 595
                $stmt   = $this->dbh->query($sql);
                $data   = $stmt->fetch(PDO::FETCH_NUM);
                $values[$tablename] = $data[0];

                $stmt->closeCursor();
            }
        }
        return $values;
doctrine's avatar
doctrine committed
596 597 598 599
    }
    /**
     * bulkUpdate
     * updates all objects in the pending update list
600
     *
doctrine's avatar
doctrine committed
601 602 603 604
     * @return void
     */
    public function bulkUpdate() {
        foreach($this->update as $name => $updates) {
doctrine's avatar
doctrine committed
605 606
            $ids = array();

doctrine's avatar
doctrine committed
607 608 609 610 611 612 613 614
            foreach($updates as $k => $record) {
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($record);
                // listen the onPreUpdate event
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onPreUpdate($record);

                $this->update($record);
                // listen the onUpdate event
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onUpdate($record);
doctrine's avatar
doctrine committed
615

doctrine's avatar
doctrine committed
616
                $record->getTable()->getAttribute(Doctrine::ATTR_LISTENER)->onSave($record);
doctrine's avatar
doctrine committed
617 618

                $ids[] = $record->getID();
doctrine's avatar
doctrine committed
619
            }
doctrine's avatar
doctrine committed
620 621
            if(isset($record))
                $record->getTable()->getCache()->deleteMultiple($ids);
doctrine's avatar
doctrine committed
622
        }
623
        $this->update = array();
doctrine's avatar
doctrine committed
624 625 626
    }
    /**
     * bulkDelete
627 628
     * deletes all records from the pending delete list
     *
doctrine's avatar
doctrine committed
629 630 631 632 633
     * @return void
     */
    public function bulkDelete() {
        foreach($this->delete as $name => $deletes) {
            $record = false;
634
            $ids    = array();
doctrine's avatar
doctrine committed
635 636
            foreach($deletes as $k => $record) {
                $ids[] = $record->getID();
637
                $record->setID(false);
doctrine's avatar
doctrine committed
638 639
            }
            if($record instanceof Doctrine_Record) {
640 641
                $table  = $record->getTable();

doctrine's avatar
doctrine committed
642
                $params  = substr(str_repeat("?, ",count($ids)),0,-2);
643
                $query   = "DELETE FROM ".$record->getTable()->getTableName()." WHERE ".$table->getIdentifier()." IN(".$params.")";
doctrine's avatar
doctrine committed
644 645 646 647 648
                $this->execute($query,$ids);

                $record->getTable()->getCache()->deleteMultiple($ids);
            }
        }
649
        $this->delete = array();
doctrine's avatar
doctrine committed
650 651
    }
    /**
652 653
     * saves a collection
     *
doctrine's avatar
doctrine committed
654 655 656 657 658 659 660 661 662 663 664 665 666
     * @param Doctrine_Collection $coll
     * @return void
     */
    public function saveCollection(Doctrine_Collection $coll) {
        $this->beginTransaction();

        foreach($coll as $key=>$record):
                $record->save();
        endforeach;

        $this->commit();
    }
    /**
667 668
     * deletes all records from collection
     *
doctrine's avatar
doctrine committed
669 670 671 672 673 674 675 676 677 678 679
     * @param Doctrine_Collection $coll
     * @return void
     */
    public function deleteCollection(Doctrine_Collection $coll) {
        $this->beginTransaction();
        foreach($coll as $k=>$record) {
            $record->delete();
        }
        $this->commit();
    }
    /**
680 681
     * saves the given record
     *
doctrine's avatar
doctrine committed
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
     * @param Doctrine_Record $record
     * @return void
     */
    public function save(Doctrine_Record $record) {
        switch($record->getState()):
            case Doctrine_Record::STATE_TDIRTY:
                $this->addInsert($record);
            break;
            case Doctrine_Record::STATE_DIRTY:
            case Doctrine_Record::STATE_PROXY:
                $this->addUpdate($record);
            break;
            case Doctrine_Record::STATE_CLEAN:
            case Doctrine_Record::STATE_TCLEAN:
                // do nothing
            break;
        endswitch;
    }
    /**
701 702
     * saves all related records to $record
     *
doctrine's avatar
doctrine committed
703 704 705 706 707 708 709 710 711
     * @param Doctrine_Record $record
     */
    final public function saveRelated(Doctrine_Record $record) {
        $saveLater = array();
        foreach($record->getReferences() as $k=>$v) {
            $fk = $record->getTable()->getForeignKey($k);
            if($fk instanceof Doctrine_ForeignKey ||
               $fk instanceof Doctrine_LocalKey) {
                switch($fk->getType()):
712 713
                    case Doctrine_Relation::ONE_COMPOSITE:
                    case Doctrine_Relation::MANY_COMPOSITE:
doctrine's avatar
doctrine committed
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
                        $local = $fk->getLocal();
                        $foreign = $fk->getForeign();

                        if($record->getTable()->hasPrimaryKey($fk->getLocal())) {
                            switch($record->getState()):
                                case Doctrine_Record::STATE_TDIRTY:
                                case Doctrine_Record::STATE_TCLEAN:
                                    $saveLater[$k] = $fk;
                                break;
                                case Doctrine_Record::STATE_CLEAN:
                                case Doctrine_Record::STATE_DIRTY:
                                    $v->save();    
                                break;
                            endswitch;
                        } else {
                            // ONE-TO-ONE relationship
                            $obj = $record->get($fk->getTable()->getComponentName());

                            if($obj->getState() != Doctrine_Record::STATE_TCLEAN)
                                $obj->save();

                        }
                    break;
                endswitch;
            } elseif($fk instanceof Doctrine_Association) {
                $v->save();
            }
        }
        return $saveLater;
    }
    /**
745 746
     * updates the given record
     *
doctrine's avatar
doctrine committed
747 748 749 750 751
     * @param Doctrine_Record $record
     * @return boolean
     */
    private function update(Doctrine_Record $record) {
        $array = $record->getModified();
752

doctrine's avatar
doctrine committed
753 754 755 756 757 758 759 760
        if(empty($array))
            return false;

        $set   = array();
        foreach($array as $name => $value):
                $set[] = $name." = ?";

                if($value instanceof Doctrine_Record) {
doctrine's avatar
doctrine committed
761 762 763 764 765 766 767 768
                    switch($value->getState()):
                        case Doctrine_Record::STATE_TCLEAN:
                        case Doctrine_Record::STATE_TDIRTY:
                            $record->save();
                        default:
                            $array[$name] = $value->getID();
                            $record->set($name, $value->getID());
                    endswitch;
doctrine's avatar
doctrine committed
769 770 771 772 773 774 775 776 777 778
                }
        endforeach;

        if(isset($this->validator)) {
            if( ! $this->validator->validateRecord($record)) {
                return false;
            }
        }

        $params   = array_values($array);
779 780 781 782 783 784 785 786
        $id       = $record->getID();


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

        $id     = array_values($id);
        $params = array_merge($params, $id);
doctrine's avatar
doctrine committed
787 788 789


        $sql  = "UPDATE ".$record->getTable()->getTableName()." SET ".implode(", ",$set)." WHERE ".implode(" = ? && ",$record->getTable()->getPrimaryKeys())." = ?";
790

doctrine's avatar
doctrine committed
791 792 793
        $stmt = $this->dbh->prepare($sql);
        $stmt->execute($params);

794
        $record->setID(true);
doctrine's avatar
doctrine committed
795 796 797 798

        return true;
    }
    /**
799 800
     * inserts a record into database
     *
doctrine's avatar
doctrine committed
801 802 803
     * @param Doctrine_Record $record
     * @return boolean
     */
804
    private function insert(Doctrine_Record $record) {
805 806
        $array = $record->getPrepared();

doctrine's avatar
doctrine committed
807 808 809 810
        if(empty($array))
            return false;

        $seq = $record->getTable()->getSequenceName();
811

doctrine's avatar
doctrine committed
812
        if( ! empty($seq)) {
813 814 815
            $id             = $this->getNextID($seq);
            $name           = $record->getTable()->getIdentifier();
            $array[$name]   = $id;
doctrine's avatar
doctrine committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
        }

        if(isset($this->validator)) {
            if( ! $this->validator->validateRecord($record)) {
                return false;
            }
        }

        $strfields = join(", ", array_keys($array));
        $strvalues = substr(str_repeat("?, ",count($array)),0,-2);

        $sql  = "INSERT INTO ".$record->getTable()->getTableName()." (".$strfields.") VALUES (".$strvalues.")";

        $stmt = $this->dbh->prepare($sql);

        $stmt->execute(array_values($array));

        return true;
    }
    /**
     * deletes all related composites
837
     * this method is always called internally when a record is deleted
doctrine's avatar
doctrine committed
838 839 840 841 842 843
     *
     * @return void
     */
    final public function deleteComposites(Doctrine_Record $record) {
        foreach($record->getTable()->getForeignKeys() as $fk) {
            switch($fk->getType()):
844 845
                case Doctrine_Relation::ONE_COMPOSITE:
                case Doctrine_Relation::MANY_COMPOSITE:
doctrine's avatar
doctrine committed
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
                    $obj = $record->get($fk->getTable()->getComponentName());
                    $obj->delete();
                break;
            endswitch;
        }
    }
    /**
     * deletes this data access object and all the related composites
     * this operation is isolated by a transaction
     * 
     * this event can be listened by the onPreDelete and onDelete listeners
     *
     * @return boolean      true on success, false on failure
     */
    final public function delete(Doctrine_Record $record) {
        switch($record->getState()):
            case Doctrine_Record::STATE_PROXY:
            case Doctrine_Record::STATE_CLEAN:
            case Doctrine_Record::STATE_DIRTY:
                $this->beginTransaction();

                $this->deleteComposites($record);
                $this->addDelete($record);

                $this->commit();
                return true;
            break;
            default:
                return false;
        endswitch;    
    }
    /**
878
     * adds record into pending insert list
doctrine's avatar
doctrine committed
879 880 881 882 883 884 885
     * @param Doctrine_Record $record
     */
    public function addInsert(Doctrine_Record $record) {
        $name = $record->getTable()->getComponentName();
        $this->insert[$name][] = $record;
    }
    /**
886
     * adds record into penging update list
doctrine's avatar
doctrine committed
887 888 889 890 891 892 893
     * @param Doctrine_Record $record
     */
    public function addUpdate(Doctrine_Record $record) {
        $name = $record->getTable()->getComponentName();
        $this->update[$name][] = $record;
    }
    /**
894
     * adds record into pending delete list
doctrine's avatar
doctrine committed
895 896 897 898 899 900
     * @param Doctrine_Record $record
     */
    public function addDelete(Doctrine_Record $record) {
        $name = $record->getTable()->getComponentName();
        $this->delete[$name][] = $record;
    }
901
    /**
902 903
     * returns the pending insert list
     *
904 905 906 907 908 909
     * @return array
     */
    public function getInserts() {
        return $this->insert;
    }
    /**
910 911
     * returns the pending update list
     *
912 913 914 915 916 917
     * @return array
     */
    public function getUpdates() {
        return $this->update;
    }
    /**
918 919
     * returns the pending delete list
     *
920 921 922 923 924 925
     * @return array
     */
    public function getDeletes() {
        return $this->delete;
    }

doctrine's avatar
doctrine committed
926 927 928 929 930 931 932 933 934
    /**
     * returns a string representation of this object
     * @return string
     */
    public function __toString() {
        return Doctrine_Lib::getSessionAsString($this);
    }
}
?>