public function testRetrieveTree() { list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); $tree = Table9Peer::retrieveTree(); $this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the whole tree'); $c = new Criteria(); $c->add(Table9Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL); $tree = Table9Peer::retrieveTree($c); $this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter'); }
public function testPreDelete() { $max = Table11Peer::getMaxRank(); $t3 = Table11Peer::retrieveByRank(3); $t3->delete(); $this->assertEquals($max - 1, Table11Peer::getMaxRank(), 'Sortable rearrange subsequent rows on delete'); $c = new Criteria(); $c->add(Table11Peer::TITLE, 'row4'); $t4 = Table11Peer::doSelectOne($c); $this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete'); }
/** * @see BasicValidator::isValid() * * @param ValidatorMap $map * @param string $str * * @return boolean */ public function isValid(ValidatorMap $map, $str) { $column = $map->getColumn(); $c = new Criteria(); $c->add($column->getFullyQualifiedName(), $str, Criteria::EQUAL); $table = $column->getTable()->getClassName(); $clazz = $table . 'Peer'; $count = call_user_func(array($clazz, 'doCount'), $c); $isValid = $count === 0; return $isValid; }
public function testDoInsert() { try { $c = new Criteria(); $c->setPrimaryTableName(BookPeer::TABLE_NAME); $c->add(BookPeer::AUTHOR_ID, 'lkhlkhj'); BasePeer::doInsert($c, Propel::getServiceContainer()->getWriteConnection(BookPeer::DATABASE_NAME)); } catch (RuntimeException $e) { $this->assertContains('[INSERT INTO `book` (`AUTHOR_ID`) VALUES (:p1)]', $e->getMessage(), 'SQL query is written in the exception message'); } }
public function testPreDelete() { $max = Table12Peer::getMaxRank(1); $t3 = Table12Peer::retrieveByRank(3, 1); $t3->delete(); $this->assertEquals($max - 1, Table12Peer::getMaxRank(1), 'Sortable rearrange subsequent rows on delete'); $c = new Criteria(); $c->add(Table12Peer::TITLE, 'row4'); $t4 = Table12Peer::doSelectOne($c); $this->assertEquals(3, $t4->getRank(), 'Sortable rearrange subsequent rows on delete'); $expected = array(1 => 'row5', 2 => 'row6'); $this->assertEquals($expected, $this->getFixturesArrayWithScope(2), 'delete() leaves other suites unchanged'); }
public function testCombineCriterionOrLessSimple() { $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); $this->c->add("INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); $this->c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); $this->c->addOr("INVOICE.COST4", "9000", Criteria::LESS_EQUAL); $expect = "SELECT FROM INVOICE WHERE INVOICE.COST3>=:p1 AND ((INVOICE.COST1>=:p2 OR INVOICE.COST2<=:p3) OR INVOICE.COST4<=:p4)"; $expect_params = array(array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000')); $params = array(); $result = BasePeer::createSelectSql($this->c, $params); $this->assertEquals($expect, $result); $this->assertEquals($expect_params, $params); }
public function testDoSelectOrderByRank() { $c = new Criteria(); $c->add(Table12Peer::SCOPE_COL, 1); $objects = Table12Peer::doSelectOrderByRank($c); $oldRank = 0; while ($object = array_shift($objects)) { $this->assertTrue($object->getRank() > $oldRank); $oldRank = $object->getRank(); } $c = new Criteria(); $c->add(Table12Peer::SCOPE_COL, 1); $objects = Table12Peer::doSelectOrderByRank($c, Criteria::DESC); $oldRank = 10; while ($object = array_shift($objects)) { $this->assertTrue($object->getRank() < $oldRank); $oldRank = $object->getRank(); } }
public function testClone() { $c1 = new Criteria(); $c1->add('tbl.COL1', 'foo', Criteria::EQUAL); $c2 = clone $c1; $c2->addAnd('tbl.COL1', 'bar', Criteria::EQUAL); $nbCrit = 0; foreach ($c1->keys() as $key) { foreach ($c1->getCriterion($key)->getAttachedCriterion() as $criterion) { $nbCrit++; } } $this->assertEquals(1, $nbCrit, 'cloning a Criteria clones its Criterions'); }
protected function getFixturesArrayWithScope($scope = null) { $c = new Criteria(); if ($scope !== null) { $c->add(Table12Peer::SCOPE_COL, $scope); } $c->addAscendingOrderByColumn(Table12Peer::RANK_COL); $ts = Table12Peer::doSelect($c); $ret = array(); foreach ($ts as $t) { $ret[$t->getRank()] = $t->getTitle(); } return $ret; }
protected function getByTitle($title) { $c = new Criteria(); $c->add(Table10Peer::TITLE, $title); return Table10Peer::doSelectOne($c); }
public function testIterateTwice() { $cr = new Criteria(); $cr->add(BookPeer::AUTHOR_ID, $this->authorId); $cr->addAscendingOrderByColumn(BookPeer::TITLE); $pager = new PropelPager($cr, "\\Propel\\Tests\\Bookstore\\BookPeer", "doSelect"); $i = 0; foreach ($pager as $book) { $i++; } foreach ($pager as $book) { $i++; } $this->assertEquals(14, $i); }
public function testToArrayIncludesForeignObjects() { BookstoreDataPopulator::populate(); BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); PublisherPeer::clearInstancePool(); $c = new Criteria(); $c->add(BookPeer::TITLE, 'Don Juan'); $books = BookPeer::doSelectJoinAuthor($c); $book = $books[0]; $arr1 = $book->toArray(BasePeer::TYPE_PHPNAME, null, array(), true); $expectedKeys = array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Author'); $this->assertEquals($expectedKeys, array_keys($arr1), 'toArray() can return sub arrays for hydrated related objects'); $this->assertEquals('George', $arr1['Author']['FirstName'], 'toArray() can return sub arrays for hydrated related objects'); $c = new Criteria(); $c->add(BookPeer::TITLE, 'Don Juan'); $books = BookPeer::doSelectJoinAll($c); $book = $books[0]; $arr2 = $book->toArray(BasePeer::TYPE_PHPNAME, null, array(), true); $expectedKeys = array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Publisher', 'Author'); $this->assertEquals($expectedKeys, array_keys($arr2), 'toArray() can return sub arrays for hydrated related objects'); }
public function testDebugLog() { $con = Propel::getServiceContainer()->getConnection(BookPeer::DATABASE_NAME); $config = Propel::getConfiguration(Registry::TYPE_OBJECT); // save data to return to normal state after test $logger = $con->getLogger(); $testLog = new myLogger(); $con->setLogger($testLog); $logEverything = array('exec', 'query', 'beginTransaction', 'commit', 'rollBack', 'statement_execute'); Propel::getConfiguration(Registry::TYPE_OBJECT)->setParameter("debugpdo.logging.methods", $logEverything, false); $con->useDebug(true); $con->beginTransaction(); // test transaction log $this->assertEquals('log: Begin transaction', $testLog->latestMessage, 'PropelPDO logs begin transation in debug mode'); $con->commit(); $this->assertEquals('log: Commit transaction', $testLog->latestMessage, 'PropelPDO logs commit transation in debug mode'); $con->beginTransaction(); $con->rollBack(); $this->assertEquals('log: Rollback transaction', $testLog->latestMessage, 'PropelPDO logs rollback transation in debug mode'); $con->beginTransaction(); $testLog->latestMessage = ''; $con->beginTransaction(); $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested begin transation in debug mode'); $con->commit(); $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested commit transation in debug mode'); $con->beginTransaction(); $con->rollBack(); $this->assertEquals('', $testLog->latestMessage, 'PropelPDO does not log nested rollback transation in debug mode'); $con->rollback(); // test query log $con->beginTransaction(); $c = new Criteria(); $c->add(BookPeer::TITLE, 'Harry%s', Criteria::LIKE); $books = BookPeer::doSelect($c, $con); $latestExecutedQuery = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.TITLE LIKE 'Harry%s'"; $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs queries and populates bound parameters in debug mode'); BookPeer::doDeleteAll($con); $latestExecutedQuery = "DELETE FROM `book`"; $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs deletion queries in debug mode'); $latestExecutedQuery = 'DELETE FROM book WHERE 1=1'; $con->exec($latestExecutedQuery); $this->assertEquals('log: ' . $latestExecutedQuery, $testLog->latestMessage, 'PropelPDO logs exec queries in debug mode'); $con->commit(); // return to normal state after test $con->setLogger($logger); $config->setParameter("debugpdo.logging.methods", array('PropelPDO::exec', 'PropelPDO::query', 'DebugPDOStatement::execute')); }
/** * @expectedException \Propel\Runtime\Exception\PropelException */ public function testModifyTableNoCopyDataKeepsAutoIncrement() { $content = new ConcreteContent(); $content->save(); $c = new Criteria(); $c->add(ConcreteQuizzPeer::ID, $content->getId()); ConcreteQuizzPeer::doInsert($c); }
protected function dumpTreeWithScope($scope) { $c = new Criteria(); $c->add(Table10Peer::SCOPE_COL, $scope); $c->addAscendingOrderBycolumn(Table10Peer::TITLE); return $this->dumpNodes(Table10Peer::doSelect($c)); }
public function testCachePoisoning() { /* Like testAddNewObjectAfterSaveWithPoisonedCache, emphasizing cache poisoning. */ $a = new Author(); $a->setFirstName("Douglas"); $a->setLastName("Adams"); $a->save(); $c = new Criteria(); $c->add(BookPeer::TITLE, "%Restaurant%", Criteria::LIKE); $this->assertEquals(0, count($a->getBooks($c))); $b1 = new Book(); $b1->setTitle("The Hitchhikers Guide To The Galaxy"); $a->addBook($b1); /* Like testAddNewObjectAfterSaveWithPoisonedCache, but this time with a real criteria. */ $this->assertEquals(0, count($a->getBooks($c))); $a->save(); $this->assertFalse($b1->isNew()); $this->assertEquals(0, count($a->getBooks($c))); }
/** * Issue an UPDATE query based the current ModelCriteria and a list of changes. * This method is called by ModelCriteria::update() inside a transaction. * * @param array $values Associative array of keys and values to replace * @param ConnectionInterface $con a connection object * @param boolean $forceIndividualSaves If false (default), the resulting call is a BasePeer::doUpdate(), ortherwise it is a series of save() calls on all the found objects * * @return Integer Number of updated rows */ public function doUpdate($values, $con, $forceIndividualSaves = false) { if ($forceIndividualSaves) { // Update rows one by one $objects = $this->setFormatter(ModelCriteria::FORMAT_OBJECT)->find($con); foreach ($objects as $object) { foreach ($values as $key => $value) { $object->setByName($key, $value); } } $objects->save($con); $affectedRows = count($objects); } else { // update rows in a single query $set = new Criteria($this->getDbName()); foreach ($values as $columnName => $value) { $realColumnName = $this->getTableMap()->getColumnByPhpName($columnName)->getFullyQualifiedName(); $set->add($realColumnName, $value); } $affectedRows = BasePeer::doUpdate($this, $set, $con); call_user_func(array($this->modelPeerName, 'clearInstancePool')); call_user_func(array($this->modelPeerName, 'clearRelatedInstancePool')); } return $affectedRows; }
/** * Test the doInsert() method when passed a generated object. */ public function testDoInsert_Obj() { $name = "A Sample Publisher - " . time(); $values = new Publisher(); $values->setName($name); PublisherPeer::doInsert($values); $c = new Criteria(); $c->add(PublisherPeer::NAME, $name); $matches = PublisherPeer::doSelect($c); $this->assertEquals(1, count($matches), "Expect there to be exactly 1 publisher just-inserted."); $this->assertTrue(1 != $matches[0]->getId(), "Expected to have different ID than one put in values Criteria."); }
public function testCommentDoDelete() { $c = new Criteria(); $c->setComment('Foo'); $c->add(BookPeer::TITLE, 'War And Peace'); $con = Propel::getServiceContainer()->getConnection(BookPeer::DATABASE_NAME); BasePeer::doDelete($c, $con); $expected = 'DELETE /* Foo */ FROM `book` WHERE book.TITLE=\'War And Peace\''; $this->assertEquals($expected, $con->getLastExecutedQuery(), 'Criteria::setComment() adds a comment to delete queries'); }
public function testMerge_OrWithWhereConditions() { $c1 = new Criteria(); $c1->add(BookPeer::TITLE, 'foo'); $c2 = new Criteria(); $c1->_or(); $c1->mergeWith($c2); $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() does not remove an existing where condition'); $c1 = new Criteria(); $c2 = new Criteria(); $c2->add(BookPeer::TITLE, 'foo'); $c1->_or(); $c1->mergeWith($c2); $sql = 'SELECT FROM `book` WHERE book.TITLE=:p1'; $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to an empty condition'); $c1 = new Criteria(); $c1->add(BookPeer::ID, 123); $c1->_or(); $c2 = new Criteria(); $c2->add(BookPeer::TITLE, 'foo'); $c1->mergeWith($c2); $sql = 'SELECT FROM `book` WHERE (book.ID=:p1 OR book.TITLE=:p2)'; $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions'); $c1 = new Criteria(); $c1->add(BookPeer::TITLE, 'foo'); $c1->_or(); $c2 = new Criteria(); $c2->add(BookPeer::TITLE, 'bar'); $c1->mergeWith($c2); $sql = 'SELECT FROM `book` WHERE (book.TITLE=:p1 OR book.TITLE=:p2)'; $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the same column'); $c1 = new Criteria(); $c1->add(BookPeer::TITLE, 'foo'); $c1->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID, Criteria::LEFT_JOIN); $c1->_or(); $c2 = new Criteria(); $c2->add(AuthorPeer::FIRST_NAME, 'bar'); $c1->mergeWith($c2); $sql = 'SELECT FROM `book` LEFT JOIN `author` ON (book.AUTHOR_ID=author.ID) WHERE (book.TITLE=:p1 OR author.FIRST_NAME=:p2)'; $this->assertCriteriaTranslation($c1, $sql, 'mergeWith() merges where condition to existing conditions on the different tables'); }
/** * Testing foreign keys with multiple referrer columns. * @link http://propel.phpdb.org/trac/ticket/606 */ public function testMultiColFk() { $con = Propel::getConnection(BookPeer::DATABASE_NAME); ReaderFavoritePeer::doDeleteAll(); $b1 = new Book(); $b1->setTitle("Book1"); $b1->setISBN("ISBN-1"); $b1->save(); $r1 = new BookReader(); $r1->setName("Me"); $r1->save(); $bo1 = new BookOpinion(); $bo1->setBookId($b1->getId()); $bo1->setReaderId($r1->getId()); $bo1->setRating(9); $bo1->setRecommendToFriend(true); $bo1->save(); $rf1 = new ReaderFavorite(); $rf1->setReaderId($r1->getId()); $rf1->setBookId($b1->getId()); $rf1->save(); $c = new Criteria(ReaderFavoritePeer::DATABASE_NAME); $c->add(ReaderFavoritePeer::BOOK_ID, $b1->getId()); $c->add(ReaderFavoritePeer::READER_ID, $r1->getId()); $results = ReaderFavoritePeer::doSelectJoinBookOpinion($c); $this->assertEquals(1, count($results), "Expected 1 result"); }
public function testRetrieveTree() { list($t1, $t2, $t3, $t4, $t5, $t6, $t7, $t8, $t9, $t10) = $this->initTreeWithScope(); /* Tree used for tests Scope 1 t1 | \ t2 t3 | \ t4 t5 | \ t6 t7 Scope 2 t8 | \ t9 t10 */ $tree = Table10Peer::retrieveTree(1); $this->assertEquals(array($t1, $t2, $t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() retrieves the scoped tree'); $tree = Table10Peer::retrieveTree(2); $this->assertEquals(array($t8, $t9, $t10), $tree, 'retrieveTree() retrieves the scoped tree'); $c = new Criteria(); $c->add(Table10Peer::LEFT_COL, 4, Criteria::GREATER_EQUAL); $tree = Table10Peer::retrieveTree(1, $c); $this->assertEquals(array($t3, $t4, $t5, $t6, $t7), $tree, 'retrieveTree() accepts a Criteria as first parameter'); }
public function testScenarioUsingQuery() { // Add publisher records // --------------------- try { $scholastic = new Publisher(); $scholastic->setName("Scholastic"); // do not save, will do later to test cascade $morrow = new Publisher(); $morrow->setName("William Morrow"); $morrow->save(); $morrow_id = $morrow->getId(); $penguin = new Publisher(); $penguin->setName("Penguin"); $penguin->save(); $penguin_id = $penguin->getId(); $vintage = new Publisher(); $vintage->setName("Vintage"); $vintage->save(); $vintage_id = $vintage->getId(); $this->assertTrue(true, 'Save Publisher records'); } catch (Exception $e) { $this->fail('Save publisher records'); } // Add author records // ------------------ try { $rowling = new Author(); $rowling->setFirstName("J.K."); $rowling->setLastName("Rowling"); // do not save, will do later to test cascade $stephenson = new Author(); $stephenson->setFirstName("Neal"); $stephenson->setLastName("Stephenson"); $stephenson->save(); $stephenson_id = $stephenson->getId(); $byron = new Author(); $byron->setFirstName("George"); $byron->setLastName("Byron"); $byron->save(); $byron_id = $byron->getId(); $grass = new Author(); $grass->setFirstName("Gunter"); $grass->setLastName("Grass"); $grass->save(); $grass_id = $grass->getId(); $this->assertTrue(true, 'Save Author records'); } catch (Exception $e) { $this->fail('Save Author records'); } // Add book records // ---------------- try { $phoenix = new Book(); $phoenix->setTitle("Harry Potter and the Order of the Phoenix"); $phoenix->setISBN("043935806X"); $phoenix->setAuthor($rowling); $phoenix->setPublisher($scholastic); $phoenix->save(); $phoenix_id = $phoenix->getId(); $this->assertFalse($rowling->isNew(), 'saving book also saves related author'); $this->assertFalse($scholastic->isNew(), 'saving book also saves related publisher'); $qs = new Book(); $qs->setISBN("0380977427"); $qs->setTitle("Quicksilver"); $qs->setAuthor($stephenson); $qs->setPublisher($morrow); $qs->save(); $qs_id = $qs->getId(); $dj = new Book(); $dj->setISBN("0140422161"); $dj->setTitle("Don Juan"); $dj->setAuthor($byron); $dj->setPublisher($penguin); $dj->save(); $dj_id = $qs->getId(); $td = new Book(); $td->setISBN("067972575X"); $td->setTitle("The Tin Drum"); $td->setAuthor($grass); $td->setPublisher($vintage); $td->save(); $td_id = $td->getId(); $this->assertTrue(true, 'Save Book records'); } catch (Exception $e) { $this->fail('Save Author records'); } // Add review records // ------------------ try { $r1 = new Review(); $r1->setBook($phoenix); $r1->setReviewedBy("Washington Post"); $r1->setRecommended(true); $r1->setReviewDate(time()); $r1->save(); $r1_id = $r1->getId(); $r2 = new Review(); $r2->setBook($phoenix); $r2->setReviewedBy("New York Times"); $r2->setRecommended(false); $r2->setReviewDate(time()); $r2->save(); $r2_id = $r2->getId(); $this->assertTrue(true, 'Save Review records'); } catch (Exception $e) { $this->fail('Save Review records'); } // Perform a "complex" search // -------------------------- $results = BookQuery::create()->filterByTitle('Harry%')->find(); $this->assertEquals(1, count($results)); $results = BookQuery::create()->where('Book.ISBN IN ?', array("0380977427", "0140422161"))->find(); $this->assertEquals(2, count($results)); // Perform a "limit" search // ------------------------ $results = BookQuery::create()->limit(2)->offset(1)->orderByTitle()->find(); $this->assertEquals(2, count($results)); // we ordered on book title, so we expect to get $this->assertEquals("Harry Potter and the Order of the Phoenix", $results[0]->getTitle()); $this->assertEquals("Quicksilver", $results[1]->getTitle()); // Perform a lookup & update! // -------------------------- // Updating just-created book title // First finding book by PK (=$qs_id) .... $qs_lookup = BookQuery::create()->findPk($qs_id); $this->assertNotNull($qs_lookup, 'just-created book can be found by pk'); $new_title = "Quicksilver (" . crc32(uniqid(rand())) . ")"; // Attempting to update found object $qs_lookup->setTitle($new_title); $qs_lookup->save(); // Making sure object was correctly updated: "; $qs_lookup2 = BookQuery::create()->findPk($qs_id); $this->assertEquals($new_title, $qs_lookup2->getTitle()); // Test some basic DATE / TIME stuff // --------------------------------- // that's the control timestamp. $control = strtotime('2004-02-29 00:00:00'); // should be two in the db $r = ReviewQuery::create()->findOne(); $r_id = $r->getId(); $r->setReviewDate($control); $r->save(); $r2 = ReviewQuery::create()->findPk($r_id); $this->assertEquals(new DateTime('2004-02-29 00:00:00'), $r2->getReviewDate(null), 'ability to fetch DateTime'); $this->assertEquals($control, $r2->getReviewDate('U'), 'ability to fetch native unix timestamp'); $this->assertEquals('2-29-2004', $r2->getReviewDate('n-j-Y'), 'ability to use date() formatter'); // Handle BLOB/CLOB Columns // ------------------------ $blob_path = __DIR__ . '/../../Fixtures/etc/lob/tin_drum.gif'; $blob2_path = __DIR__ . '/../../Fixtures/etc/lob/propel.gif'; $clob_path = __DIR__ . '/../../Fixtures/etc/lob/tin_drum.txt'; $m1 = new Media(); $m1->setBook($phoenix); $m1->setCoverImage(file_get_contents($blob_path)); $m1->setExcerpt(file_get_contents($clob_path)); $m1->save(); $m1_id = $m1->getId(); $m1_lookup = MediaQuery::create()->findPk($m1_id); $this->assertNotNull($m1_lookup, 'Can find just-created media item'); $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m1_lookup->getCoverImage())), 'BLOB was correctly updated'); $this->assertEquals(file_get_contents($clob_path), (string) $m1_lookup->getExcerpt(), 'CLOB was correctly updated'); // now update the BLOB column and save it & check the results $m1_lookup->setCoverImage(file_get_contents($blob2_path)); $m1_lookup->save(); $m2_lookup = MediaQuery::create()->findPk($m1_id); $this->assertNotNull($m2_lookup, 'Can find just-created media item'); $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2_lookup->getCoverImage())), 'BLOB was correctly overwritten'); // Test Validators // --------------- $bk1 = new Book(); $bk1->setTitle("12345"); // min length is 10 $ret = $bk1->validate(); $this->assertFalse($ret, 'validation failed'); $failures = $bk1->getValidationFailures(); $this->assertEquals(1, count($failures), '1 validation message was returned'); $el = array_shift($failures); $this->assertContains("must be more than", $el->getMessage(), 'Expected validation message was returned'); $bk2 = new Book(); $bk2->setTitle("Don Juan"); $ret = $bk2->validate(); $this->assertFalse($ret, 'validation failed'); $failures = $bk2->getValidationFailures(); $this->assertEquals(1, count($failures), '1 validation message was returned'); $el = array_shift($failures); $this->assertContains("Book title already in database.", $el->getMessage(), 'Expected validation message was returned'); //Now trying some more complex validation. $auth1 = new Author(); $auth1->setFirstName("Hans"); // last name required; will fail $bk1->setAuthor($auth1); $rev1 = new Review(); $rev1->setReviewDate("08/09/2001"); // will fail: reviewed_by column required $bk1->addReview($rev1); $ret2 = $bk1->validate(); $this->assertFalse($ret2, 'validation failed'); $failures2 = $bk1->getValidationFailures(); $this->assertEquals(3, count($failures2), '3 validation messages were returned'); $expectedKeys = array(AuthorPeer::LAST_NAME, BookPeer::TITLE, ReviewPeer::REVIEWED_BY); $this->assertEquals($expectedKeys, array_keys($failures2), 'correct columns failed'); $bk2 = new Book(); $bk2->setTitle("12345678901"); // passes $auth2 = new Author(); $auth2->setLastName("Blah"); //passes $auth2->setEmail("*****@*****.**"); //passes $auth2->setAge(50); //passes $bk2->setAuthor($auth2); $rev2 = new Review(); $rev2->setReviewedBy("Me!"); // passes $rev2->setStatus("new"); // passes $bk2->addReview($rev2); $ret3 = $bk2->validate(); $this->assertTrue($ret3, 'complex validation can pass'); // Testing doCount() functionality // ------------------------------- // old way $c = new Criteria(); $records = BookPeer::doSelect($c); $count = BookPeer::doCount($c); $this->assertEquals($count, count($records), 'correct number of results'); // new way $count = BookQuery::create()->count(); $this->assertEquals($count, count($records), 'correct number of results'); // Test many-to-many relationships // --------------- // init book club list 1 with 2 books $blc1 = new BookClubList(); $blc1->setGroupLeader("Crazyleggs"); $blc1->setTheme("Happiness"); $brel1 = new BookListRel(); $brel1->setBook($phoenix); $brel2 = new BookListRel(); $brel2->setBook($dj); $blc1->addBookListRel($brel1); $blc1->addBookListRel($brel2); $blc1->save(); $this->assertNotNull($blc1->getId(), 'BookClubList 1 was saved'); // init book club list 2 with 1 book $blc2 = new BookClubList(); $blc2->setGroupLeader("John Foo"); $blc2->setTheme("Default"); $brel3 = new BookListRel(); $brel3->setBook($phoenix); $blc2->addBookListRel($brel3); $blc2->save(); $this->assertNotNull($blc2->getId(), 'BookClubList 2 was saved'); // re-fetch books and lists from db to be sure that nothing is cached $crit = new Criteria(); $crit->add(BookPeer::ID, $phoenix->getId()); $phoenix = BookPeer::doSelectOne($crit); $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db"); $crit = new Criteria(); $crit->add(BookClubListPeer::ID, $blc1->getId()); $blc1 = BookClubListPeer::doSelectOne($crit); $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db'); $crit = new Criteria(); $crit->add(BookClubListPeer::ID, $blc2->getId()); $blc2 = BookClubListPeer::doSelectOne($crit); $this->assertNotNull($blc2, 'BookClubList 2 has been re-fetched from db'); $relCount = $phoenix->countBookListRels(); $this->assertEquals(2, $relCount, "book 'phoenix' has 2 BookListRels"); $relCount = $blc1->countBookListRels(); $this->assertEquals(2, $relCount, 'BookClubList 1 has 2 BookListRels'); $relCount = $blc2->countBookListRels(); $this->assertEquals(1, $relCount, 'BookClubList 2 has 1 BookListRel'); // Cleanup (tests DELETE) // ---------------------- // Removing books that were just created // First finding book by PK (=$phoenix_id) .... $hp = BookQuery::create()->findPk($phoenix_id); $this->assertNotNull($hp, 'Could find just-created book'); // Attempting to delete [multi-table] by found pk $c = new Criteria(); $c->add(BookPeer::ID, $hp->getId()); // The only way for cascading to work currently // is to specify the author_id and publisher_id (i.e. the fkeys // have to be in the criteria). $c->add(AuthorPeer::ID, $hp->getAuthor()->getId()); $c->add(PublisherPeer::ID, $hp->getPublisher()->getId()); $c->setSingleRecord(true); BookPeer::doDelete($c); // Checking to make sure correct records were removed. $this->assertEquals(3, AuthorPeer::doCount(new Criteria()), 'Correct records were removed from author table'); $this->assertEquals(3, PublisherPeer::doCount(new Criteria()), 'Correct records were removed from publisher table'); $this->assertEquals(3, BookPeer::doCount(new Criteria()), 'Correct records were removed from book table'); // Attempting to delete books by complex criteria BookQuery::create()->filterByISBN("043935806X")->orWhere('Book.ISBN = ?', "0380977427")->orWhere('Book.ISBN = ?', "0140422161")->delete(); // Attempting to delete book [id = $td_id] $td->delete(); // Attempting to delete authors AuthorQuery::create()->filterById($stephenson_id)->delete(); AuthorQuery::create()->filterById($byron_id)->delete(); $grass->delete(); // Attempting to delete publishers PublisherQuery::create()->filterById($morrow_id)->delete(); PublisherQuery::create()->filterById($penguin_id)->delete(); $vintage->delete(); // These have to be deleted manually also since we have onDelete // set to SETNULL in the foreign keys in book. Is this correct? $rowling->delete(); $scholastic->delete(); $blc1->delete(); $blc2->delete(); $this->assertEquals(array(), AuthorPeer::doSelect(new Criteria()), 'no records in [author] table'); $this->assertEquals(array(), PublisherPeer::doSelect(new Criteria()), 'no records in [publisher] table'); $this->assertEquals(array(), BookPeer::doSelect(new Criteria()), 'no records in [book] table'); $this->assertEquals(array(), ReviewPeer::doSelect(new Criteria()), 'no records in [review] table'); $this->assertEquals(array(), MediaPeer::doSelect(new Criteria()), 'no records in [media] table'); $this->assertEquals(array(), BookClubListPeer::doSelect(new Criteria()), 'no records in [book_club_list] table'); $this->assertEquals(array(), BookListRelPeer::doSelect(new Criteria()), 'no records in [book_x_list] table'); }
public function testCountRefFk() { $book = new Book(); $book->setTitle("Test Book"); $book->setISBN("TT-EE-SS-TT"); $num = 5; for ($i = 2; $i < $num + 2; $i++) { $r = new Review(); $r->setReviewedBy('Hans ' . $num); $dt = new DateTime("now"); $dt->modify("-" . $i . " weeks"); $r->setReviewDate($dt); $r->setRecommended($i % 2 == 0); $book->addReview($r); } $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return {$num}"); $this->assertEquals($num, count($book->getReviews()), "Expected getReviews to return {$num} reviews"); $book->save(); BookPeer::clearInstancePool(); ReviewPeer::clearInstancePool(); $book = BookPeer::retrieveByPK($book->getId()); $this->assertEquals($num, $book->countReviews(), "Expected countReviews() to return {$num} (after save)"); $this->assertEquals($num, count($book->getReviews()), "Expected getReviews() to return {$num} (after save)"); // Now set different criteria and expect different results $c = new Criteria(); $c->add(ReviewPeer::RECOMMENDED, false); $this->assertEquals(floor($num / 2), $book->countReviews($c), "Expected " . floor($num / 2) . " results from countReviews(recomm=false)"); // Change Criteria, run again -- expect different. $c = new Criteria(); $c->add(ReviewPeer::RECOMMENDED, true); $this->assertEquals(ceil($num / 2), count($book->getReviews($c)), "Expected " . ceil($num / 2) . " results from getReviews(recomm=true)"); $this->assertEquals($num, $book->countReviews(), "Expected countReviews to return {$num} with new empty Criteria"); }
public function testStaticDoSoftDelete() { $t1 = new Table4(); $t1->save(); $t2 = new Table4(); $t2->save(); $t3 = new Table4(); $t3->save(); // softDelete with a criteria $c = new Criteria(); $c->add(Table4Peer::ID, $t1->getId()); Table4Peer::doSoftDelete($c); Table4Peer::disableSoftDelete(); $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); Table4Peer::enableSoftDelete(); $this->assertEquals(2, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); // softDelete with a value Table4Peer::doSoftDelete(array($t2->getId())); Table4Peer::disableSoftDelete(); $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); Table4Peer::enableSoftDelete(); $this->assertEquals(1, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); // softDelete with an object Table4Peer::doSoftDelete($t3); Table4Peer::disableSoftDelete(); $this->assertEquals(3, Table4Peer::doCount(new Criteria()), 'doSoftDelete() keeps deleted record in the database'); Table4Peer::enableSoftDelete(); $this->assertEquals(0, Table4Peer::doCount(new Criteria()), 'doSoftDelete() marks deleted record as deleted'); }
public function testGetAncestors() { list($t1, $t2, $t3, $t4, $t5, $t6, $t7) = $this->initTree(); /* Tree used for tests t1 | \ t2 t3 | \ t4 t5 | \ t6 t7 */ $this->assertEquals(array(), $t1->getAncestors(), 'getAncestors() returns an empty array for roots'); $ancestors = $t5->getAncestors(); $expected = array('t1' => array(1, 14, 0), 't3' => array(4, 13, 1)); $this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() returns an array of ancestors'); $c = new Criteria(); $c->add(Table9Peer::TITLE, 't3'); $ancestors = $t5->getAncestors($c); $expected = array('t3' => array(4, 13, 1)); $this->assertEquals($expected, $this->dumpNodes($ancestors), 'getAncestors() accepts a criteria as parameter'); }