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 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'); } }
/** * @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 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'); }
public function testCreateSelectSqlPart() { Propel::setDb('oracle', new DBOracle()); $db = Propel::getDB(); $c = new Criteria(); $c->addSelectColumn(BookPeer::ID); $c->addAsColumn('book_ID', BookPeer::ID); $fromClause = array(); $selectSql = $db->createSelectSqlPart($c, $fromClause); $this->assertEquals('SELECT book.ID, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() returns a SQL SELECT clause with both select and as columns'); $this->assertEquals(array('book'), $fromClause, 'createSelectSqlPart() adds the tables from the select columns to the from clause'); }
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'); }
/** * Init some properties with the help of outer class * @param Criteria $criteria The outer class */ public function init(Criteria $criteria) { // init $this->db try { $db = Propel::getDB($criteria->getDbName()); $this->setDB($db); } catch (Exception $e) { // we are only doing this to allow easier debugging, so // no need to throw up the exception, just make note of it. Propel::log("Could not get a DBAdapter, sql may be wrong", Propel::LOG_ERR); } // init $this->realtable $realtable = $criteria->getTableForAlias($this->table); $this->realtable = $realtable ? $realtable : $this->table; }
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'); }
/** * @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); }
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 testCombineDirtyOperators() { $this->c->addCond('cond1', "INVOICE.COST1", "1000", Criteria::GREATER_EQUAL); $this->c->addCond('cond2', "INVOICE.COST2", "2000", Criteria::LESS_EQUAL); $this->c->combine(array('cond1', 'cond2'), 'AnD', 'cond12'); $this->c->addCond('cond3', "INVOICE.COST3", "8000", Criteria::GREATER_EQUAL); $this->c->addCond('cond4', "INVOICE.COST4", "9000", Criteria::LESS_EQUAL); $this->c->combine(array('cond3', 'cond4'), 'aNd', 'cond34'); $this->c->combine(array('cond12', 'cond34'), 'oR'); $expect = "SELECT FROM INVOICE WHERE ((INVOICE.COST1>=:p1 AND INVOICE.COST2<=:p2) OR (INVOICE.COST3>=:p3 AND INVOICE.COST4<=:p4))"; $expect_params = array(array('table' => 'INVOICE', 'column' => 'COST1', 'value' => '1000'), array('table' => 'INVOICE', 'column' => 'COST2', 'value' => '2000'), array('table' => 'INVOICE', 'column' => 'COST3', 'value' => '8000'), array('table' => 'INVOICE', 'column' => 'COST4', 'value' => '9000')); $params = array(); $result = BasePeer::createSelectSql($this->c, $params); $this->assertEquals($expect, $result); $this->assertEquals($expect_params, $params); }
/** * Builds a params array, like the kind populated by Criterion::appendPsTo(). * This is useful for building an array even when it is not using the appendPsTo() method. * @param array $columns * @param Criteria $values * @return array params array('column' => ..., 'table' => ..., 'value' => ...) */ private static function buildParams($columns, Criteria $values) { $params = array(); foreach ($columns as $key) { if ($values->containsKey($key)) { $crit = $values->getCriterion($key); $params[] = array('column' => $crit->getColumn(), 'table' => $crit->getTable(), 'value' => $crit->getValue()); } } return $params; }
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'); }
/** * Testing foreign keys with multiple referrer columns. * @link http://propel.phpdb.org/trac/ticket/606 */ public function testMultiColJoin() { BookstoreContestPeer::doDeleteAll(); BookstoreContestEntryPeer::doDeleteAll(); $bs = new Bookstore(); $bs->setStoreName("Test1"); $bs->setPopulationServed(5); $bs->save(); $bs1Id = $bs->getId(); $bs2 = new Bookstore(); $bs2->setStoreName("Test2"); $bs2->setPopulationServed(5); $bs2->save(); $bs2Id = $bs2->getId(); $ct1 = new Contest(); $ct1->setName("Contest1!"); $ct1->save(); $ct1Id = $ct1->getId(); $ct2 = new Contest(); $ct2->setName("Contest2!"); $ct2->save(); $ct2Id = $ct2->getId(); $cmr = new Customer(); $cmr->setName("Customer1"); $cmr->save(); $cmr1Id = $cmr->getId(); $cmr2 = new Customer(); $cmr2->setName("Customer2"); $cmr2->save(); $cmr2Id = $cmr2->getId(); $contest = new BookstoreContest(); $contest->setBookstoreId($bs1Id); $contest->setContestId($ct1Id); $contest->save(); $contest = new BookstoreContest(); $contest->setBookstoreId($bs2Id); $contest->setContestId($ct1Id); $contest->save(); $entry = new BookstoreContestEntry(); $entry->setBookstoreId($bs1Id); $entry->setContestId($ct1Id); $entry->setCustomerId($cmr1Id); $entry->save(); $entry = new BookstoreContestEntry(); $entry->setBookstoreId($bs1Id); $entry->setContestId($ct1Id); $entry->setCustomerId($cmr2Id); $entry->save(); // Note: this test isn't really working very well. We setup fkeys that // require that the BookstoreContest rows exist and then try to violate // the rules ... :-/ This may work in some lenient databases, but an error // is expected here. /* * Commented out for now ... though without it, this test may not really be testing anything $entry = new BookstoreContestEntry(); $entry->setBookstoreId($bs1Id); $entry->setContestId($ct2Id); $entry->setCustomerId($cmr2Id); $entry->save(); */ $c = new Criteria(); $c->addJoin(array(BookstoreContestEntryPeer::BOOKSTORE_ID, BookstoreContestEntryPeer::CONTEST_ID), array(BookstoreContestPeer::BOOKSTORE_ID, BookstoreContestPeer::CONTEST_ID)); $results = BookstoreContestEntryPeer::doSelect($c); $this->assertEquals(2, count($results)); foreach ($results as $result) { $this->assertEquals($bs1Id, $result->getBookstoreId()); $this->assertEquals($ct1Id, $result->getContestId()); } }
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')); }
/** * Ensures uniqueness of select column names by turning them all into aliases * This is necessary for queries on more than one table when the tables share a column name * Moved from BasePeer to PdoAdapter and turned from static to non static * * @see http://propel.phpdb.org/trac/ticket/795 * * @param Propel\Runtime\Query\Criteria $criteria * @return Propel\Runtime\Query\Criteria The input, with Select columns replaced by aliases */ public function turnSelectColumnsToAliases(Criteria $criteria) { $selectColumns = $criteria->getSelectColumns(); // clearSelectColumns also clears the aliases, so get them too $asColumns = $criteria->getAsColumns(); $criteria->clearSelectColumns(); $columnAliases = $asColumns; // add the select columns back foreach ($selectColumns as $clause) { // Generate a unique alias $baseAlias = preg_replace('/\\W/', '_', $clause); $alias = $baseAlias; // If it already exists, add a unique suffix $i = 0; while (isset($columnAliases[$alias])) { $i++; $alias = $baseAlias . '_' . $i; } // Add it as an alias $criteria->addAsColumn($alias, $clause); $columnAliases[$alias] = $clause; } // Add the aliases back, don't modify them foreach ($asColumns as $name => $clause) { $criteria->addAsColumn($name, $clause); } return $criteria; }
public function testMergeWithFurtherModified() { $c1 = new Criteria(); $c2 = new Criteria(); $c2->setLimit(123); $c1->mergeWith($c2); $this->assertEquals(123, $c1->getLimit(), 'mergeWith() makes the merge'); $c2->setLimit(456); $this->assertEquals(123, $c1->getLimit(), 'further modifying a merged criteria does not affect the merger'); }
public function testaddUsingOperatorResetsDefaultOperator() { $c = new Criteria(); $c->addUsingOperator('foo1', 'bar1'); $c->_or(); $c->addUsingOperator('foo2', 'bar2'); $c->addUsingOperator('foo3', 'bar3'); $expected = 'SELECT FROM WHERE (foo1=:p1 OR foo2=:p2) AND foo3=:p3'; $params = array(); $result = BasePeer::createSelectSql($c, $params); $this->assertEquals($expected, $result); }
/** * Set the custom join condition Criterion based on the conditions of this join * * @param Criteria $c A Criteria object to get Criterions from */ public function buildJoinCondition(Criteria $c) { $joinCondition = null; for ($i = 0; $i < $this->count; $i++) { $criterion = $c->getNewCriterion($this->getLeftColumn($i), $this->getLeftColumn($i) . $this->getOperator($i) . $this->getRightColumn($i), Criteria::CUSTOM); if (null === $joinCondition) { $joinCondition = $criterion; } else { $joinCondition = $joinCondition->addAnd($criterion); } } $this->joinCondition = $joinCondition; }
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; }
public function testLimit() { $c = new Criteria(); $this->assertEquals(0, $c->getLimit(), 'Limit is 0 by default'); $c2 = $c->setLimit(1); $this->assertEquals(1, $c->getLimit(), 'Limit is set by setLimit'); $this->assertSame($c, $c2, 'setLimit() returns the current Criteria'); }
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 testPopulateRelationCriteria() { AuthorPeer::clearInstancePool(); BookPeer::clearInstancePool(); $authors = AuthorQuery::create()->find(); $c = new Criteria(); $c->setLimit(3); $books = $authors->populateRelation('Book', $c); $this->assertEquals(3, count($books), 'populateRelation() accepts an optional criteria object to filter the query'); }
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"); }
/** * Add the content of a Criteria to the current Criteria * In case of conflict, the current Criteria keeps its properties * * @param Criteria $criteria The criteria to read properties from * @param string $operator The logical operator used to combine conditions * Defaults to Criteria::LOGICAL_AND, also accapts Criteria::LOGICAL_OR * This parameter is deprecated, use _or() instead * * @return Criteria The current criteria object */ public function mergeWith(Criteria $criteria, $operator = null) { // merge limit $limit = $criteria->getLimit(); if ($limit != 0 && $this->getLimit() == 0) { $this->limit = $limit; } // merge offset $offset = $criteria->getOffset(); if ($offset != 0 && $this->getOffset() == 0) { $this->offset = $offset; } // merge select modifiers $selectModifiers = $criteria->getSelectModifiers(); if ($selectModifiers && !$this->selectModifiers) { $this->selectModifiers = $selectModifiers; } // merge select columns $this->selectColumns = array_merge($this->getSelectColumns(), $criteria->getSelectColumns()); // merge as columns $commonAsColumns = array_intersect_key($this->getAsColumns(), $criteria->getAsColumns()); if (!empty($commonAsColumns)) { throw new PropelException('The given criteria contains an AsColumn with an alias already existing in the current object'); } $this->asColumns = array_merge($this->getAsColumns(), $criteria->getAsColumns()); // merge orderByColumns $orderByColumns = array_merge($this->getOrderByColumns(), $criteria->getOrderByColumns()); $this->orderByColumns = array_unique($orderByColumns); // merge groupByColumns $groupByColumns = array_merge($this->getGroupByColumns(), $criteria->getGroupByColumns()); $this->groupByColumns = array_unique($groupByColumns); // merge where conditions if ($operator == Criteria::LOGICAL_OR) { $this->_or(); } $isFirstCondition = true; foreach ($criteria->getMap() as $key => $criterion) { if ($isFirstCondition && $this->defaultCombineOperator == Criteria::LOGICAL_OR) { $this->addOr($criterion, null, null, false); $this->defaultCombineOperator == Criteria::LOGICAL_AND; } elseif ($this->containsKey($key)) { $this->addAnd($criterion); } else { $this->add($criterion); } $isFirstCondition = false; } // merge having if ($having = $criteria->getHaving()) { if ($this->getHaving()) { $this->addHaving($this->getHaving()->addAnd($having)); } else { $this->addHaving($having); } } // merge alias $commonAliases = array_intersect_key($this->getAliases(), $criteria->getAliases()); if (!empty($commonAliases)) { throw new PropelException('The given criteria contains an alias already existing in the current object'); } $this->aliases = array_merge($this->getAliases(), $criteria->getAliases()); // merge join $this->joins = array_merge($this->getJoins(), $criteria->getJoins()); return $this; }
public function testCreateSelectSqlPartAliasAll() { $db = Propel::getDB(BookPeer::DATABASE_NAME); $c = new Criteria(); $c->addSelectColumn(BookPeer::ID); $c->addAsColumn('book_ID', BookPeer::ID); $fromClause = array(); $selectSql = $db->createSelectSqlPart($c, $fromClause, true); $this->assertEquals('SELECT book.ID AS book_ID_1, book.ID AS book_ID', $selectSql, 'createSelectSqlPart() aliases all columns if passed true as last parameter'); $this->assertEquals(array(), $fromClause, 'createSelectSqlPart() does not add the tables from an all-aliased list of select columns'); }
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 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'); }
protected function getByTitle($title) { $c = new Criteria(); $c->add(Table10Peer::TITLE, $title); return Table10Peer::doSelectOne($c); }
/** * @see PdoAdapter::getDeleteFromClause() * * @param Propel\Runtime\Query\Criteria $criteria * @param string $tableName * * @return string */ public function getDeleteFromClause(Criteria $criteria, $tableName) { $sql = 'DELETE '; if ($queryComment = $criteria->getComment()) { $sql .= '/* ' . $queryComment . ' */ '; } if ($realTableName = $criteria->getTableForAlias($tableName)) { if ($this->useQuoteIdentifier()) { $realTableName = $this->quoteIdentifierTable($realTableName); } $sql .= 'FROM ' . $realTableName . ' AS ' . $tableName; } else { if ($this->useQuoteIdentifier()) { $tableName = $this->quoteIdentifierTable($tableName); } $sql .= 'FROM ' . $tableName; } return $sql; }