public function testFrom()
 {
     $q = PropelQuery::from('\\Propel\\Tests\\Bookstore\\Book');
     $expected = new BookQuery();
     $this->assertEquals($expected, $q, 'from() returns a Model query instance based on the model name');
     $q = PropelQuery::from('\\Propel\\Tests\\Bookstore\\Book b');
     $expected = new BookQuery();
     $expected->setModelAlias('b');
     $this->assertEquals($expected, $q, 'from() sets the model alias if found after the blank');
     $q = PropelQuery::from('\\Propel\\Tests\\Runtime\\Query\\myBook');
     $expected = new myBookQuery();
     $this->assertEquals($expected, $q, 'from() can find custom query classes');
     try {
         $q = PropelQuery::from('Foo');
         $this->fail('PropelQuery::from() throws an exception when called on a non-existing query class');
     } catch (PropelException $e) {
         $this->assertTrue(true, 'PropelQuery::from() throws an exception when called on a non-existing query class');
     }
 }
 public function testSerializeHydratedObject()
 {
     $book = new Book();
     $book->setTitle('Foo3');
     $book->setISBN('1234');
     $book->save();
     BookTableMap::clearInstancePool();
     $book = BookQuery::create()->findOneByTitle('Foo3');
     $sb = serialize($book);
     $this->assertEquals($book, unserialize($sb));
 }
 public function testMagicFindByObject()
 {
     $con = Propel::getServiceContainer()->getConnection(BookPeer::DATABASE_NAME);
     $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author');
     $testAuthor = $c->findOne();
     $q = BookQuery::create()->findByAuthor($testAuthor);
     $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.AUTHOR_ID=" . $testAuthor->getId();
     $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)');
     $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author');
     $testAuthor = $c->findOne();
     $q = BookQuery::create()->findByAuthorAndISBN($testAuthor, 1234);
     $expectedSQL = "SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book` WHERE book.AUTHOR_ID=" . $testAuthor->getId() . " AND book.ISBN=1234";
     $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX, YYY), $value)');
 }
 public function testMagicRequireOneWithAndThrowsException()
 {
     $this->setExpectedException('\\Propel\\Runtime\\Exception\\EntityNotFoundException', 'Book could not be found');
     BookQuery::create()->requireOneByTitleAndId('Not Existing Book', -1337);
 }
Exemple #5
0
 public function testDebugLog()
 {
     $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
     // save data to return to normal state after test
     $logger = $con->getLogger();
     $logMethods = $con->getLogMethods();
     $testLog = new Logger('debug');
     $handler = new LastMessageHandler();
     $testLog->pushHandler($handler);
     $con->setLogger($testLog);
     $con->setLogMethods(['exec', 'query', 'execute', 'beginTransaction', 'commit', 'rollBack']);
     $con->useDebug(true);
     $con->beginTransaction();
     // test transaction log
     $this->assertEquals('Begin transaction', $handler->latestMessage, 'PropelPDO logs begin transaction in debug mode');
     $con->commit();
     $this->assertEquals('Commit transaction', $handler->latestMessage, 'PropelPDO logs commit transaction in debug mode');
     $con->beginTransaction();
     $con->rollBack();
     $this->assertEquals('Rollback transaction', $handler->latestMessage, 'PropelPDO logs rollback transaction in debug mode');
     $con->beginTransaction();
     $handler->latestMessage = '';
     $con->beginTransaction();
     $this->assertEquals('', $handler->latestMessage, 'PropelPDO does not log nested begin transaction in debug mode');
     $con->commit();
     $this->assertEquals('', $handler->latestMessage, 'PropelPDO does not log nested commit transaction in debug mode');
     $con->beginTransaction();
     $con->rollBack();
     $this->assertEquals('', $handler->latestMessage, 'PropelPDO does not log nested rollback transaction in debug mode');
     $con->rollback();
     // test query log
     $con->beginTransaction();
     $c = new Criteria();
     $c->add(BookTableMap::COL_TITLE, 'Harry%s', Criteria::LIKE);
     $books = BookQuery::create(null, $c)->find($con);
     $latestExecutedQuery = $this->getSql("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($latestExecutedQuery, $handler->latestMessage, 'PropelPDO logs queries and populates bound parameters in debug mode');
     BookTableMap::doDeleteAll($con);
     $latestExecutedQuery = $this->getSql("DELETE FROM book");
     $this->assertEquals($latestExecutedQuery, $handler->latestMessage, 'PropelPDO logs deletion queries in debug mode');
     $latestExecutedQuery = 'DELETE FROM book WHERE 1=1';
     $con->exec($latestExecutedQuery);
     $this->assertEquals($latestExecutedQuery, $handler->latestMessage, 'PropelPDO logs exec queries in debug mode');
     $con->commit();
     // return to normal state after test
     $con->setLogger($logger);
     $con->setLogMethods($logMethods);
 }
 public function configureSelectColumns()
 {
     return parent::configureSelectColumns();
 }
 public function __construct($dbName = 'bookstore', $modelName = '\\Propel\\Tests\\Bookstore\\Book', $modelAlias = null)
 {
     self::$preSelectWasCalled = false;
     parent::__construct($dbName, $modelName, $modelAlias);
 }
 public function testGetResultsRespectsFormatter()
 {
     $this->createBooks(5);
     $query = BookQuery::create();
     $query->setFormatter(ModelCriteria::FORMAT_ARRAY);
     $pager = new PropelModelPager($query, 4);
     $pager->setPage(1);
     $pager->init();
     $this->assertTrue($pager->getResults() instanceof ArrayCollection, 'getResults() returns a PropelArrayCollection if the query uses array hydration');
 }
 public function testGroupBy()
 {
     $params = array();
     $c = BookQuery::create()->joinReview()->withColumn('COUNT(Review.Id)', 'Count')->groupById();
     $result = $c->createSelectSql($params);
     if ($this->runningOnPostgreSQL()) {
         $sql = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, COUNT(review.ID) AS Count FROM book LEFT JOIN review ON (book.ID=review.BOOK_ID) GROUP BY book.ID,book.TITLE,book.ISBN,book.PRICE,book.PUBLISHER_ID,book.AUTHOR_ID';
     } else {
         $sql = $this->getSql('SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, COUNT(review.ID) AS Count FROM `book` LEFT JOIN `review` ON (book.ID=review.BOOK_ID) GROUP BY book.ID');
     }
     $this->assertEquals($sql, $result);
 }
 public function testSubQueryCount()
 {
     $subCriteria = new BookQuery();
     $c = new BookQuery();
     $c->addSelectQuery($subCriteria, 'subCriteriaAlias');
     $c->filterByPrice(20, Criteria::LESS_THAN);
     $nbBooks = $c->count();
     $query = Propel::getConnection()->getLastExecutedQuery();
     $sql = $this->getSql("SELECT COUNT(*) FROM (SELECT subCriteriaAlias.id, subCriteriaAlias.title, subCriteriaAlias.isbn, subCriteriaAlias.price, subCriteriaAlias.publisher_id, subCriteriaAlias.author_id FROM (SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book) AS subCriteriaAlias WHERE subCriteriaAlias.price<20) propelmatch4cnt");
     $this->assertEquals($sql, $query, 'addSelectQuery() doCount is defined as complexQuery');
 }
 public function testCountableInterface()
 {
     BookQuery::create()->deleteAll();
     $pager = $this->getPager(10);
     $this->assertCount(0, $pager);
     $this->createBooks(15);
     $pager = $this->getPager(10);
     $this->assertCount(10, $pager);
     $pager = $this->getPager(10, 2);
     $this->assertCount(5, $pager);
 }
Exemple #12
0
 public function testGroupBy()
 {
     $params = [];
     $c = BookQuery::create()->joinReview()->withColumn('COUNT(Review.id)', 'Count')->groupById();
     $result = $c->createSelectSql($params);
     if ($this->runningOnPostgreSQL()) {
         $sql = 'SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, COUNT(review.id) AS Count FROM book LEFT JOIN review ON (book.id=review.book_id) GROUP BY book.id,book.title,book.isbn,book.price,book.publisher_id,book.author_id';
     } else {
         $sql = $this->getSql('SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, COUNT(review.id) AS Count FROM book LEFT JOIN review ON (book.id=review.book_id) GROUP BY book.id');
     }
     $this->assertEquals($sql, $result);
 }
 public function testPopulateRelationManyToOne()
 {
     $con = Propel::getServiceContainer()->getReadConnection(BookTableMap::DATABASE_NAME);
     AuthorTableMap::clearInstancePool();
     BookTableMap::clearInstancePool();
     $books = BookQuery::create()->find($con);
     $count = $con->getQueryCount();
     $books->populateRelation('Author', null, $con);
     foreach ($books as $book) {
         $author = $book->getAuthor();
     }
     $this->assertEquals($count + 1, $con->getQueryCount(), 'populateRelation() populates a many-to-one relationship with a single supplementary query');
 }
 public function testRemoveObjectOneToManyWithFkRequired()
 {
     BookSummaryQuery::create()->deleteAll();
     BookQuery::create()->deleteAll();
     $bookSummary = new BookSummary();
     $bookSummary->setSummary('summary Propel Book');
     $bookSummary2 = new BookSummary();
     $bookSummary2->setSummary('summary2 Propel Book');
     $book = new Book();
     $book->setTitle('Propel Book');
     $book->setISBN('01234');
     $book->addBookSummary($bookSummary);
     $book->addBookSummary($bookSummary2);
     $this->assertCount(2, $book->getBookSummaries());
     $book->removeBookSummary($bookSummary);
     $bookSummaries = $book->getBookSummaries();
     $this->assertCount(1, $bookSummaries);
     $this->assertEquals('summary2 Propel Book', $bookSummaries->getFirst()->getSummary());
     $book->save();
     $bookSummary2->save();
     $this->assertEquals(1, BookQuery::create()->count(), 'One Book');
     $this->assertEquals(1, BookSummaryQuery::create()->count(), 'One Summary');
     $this->assertEquals(1, BookSummaryQuery::create()->filterBySummarizedBook($book)->count());
     $book->addBookSummary($bookSummary);
     $bookSummary->save();
     $book->save();
     $this->assertEquals(2, BookSummaryQuery::create()->filterBySummarizedBook($book)->count());
     $book->removeBookSummary($bookSummary2);
     $book->save();
     $this->assertEquals(1, BookSummaryQuery::create()->filterBySummarizedBook($book)->count());
     $this->assertEquals(1, BookSummaryQuery::create()->count(), 'One Book summary because FK is required so book summary is deleted when book is saved');
 }
 public function testMagicFindByObject()
 {
     $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME);
     $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author');
     $testAuthor = $c->findOne();
     $q = BookQuery::create()->findByAuthor($testAuthor);
     $expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=" . $testAuthor->getId());
     $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)');
     $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author');
     $testAuthor = $c->findOne();
     $q = BookQuery::create()->findByAuthorAndISBN($testAuthor, 1234);
     $expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=" . $testAuthor->getId() . " AND book.isbn=1234");
     $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX, YYY), $value)');
 }
 public function testSetterOneToManyReplacesOldObjectsByNewObjects()
 {
     // Ensure no data
     BookQuery::create()->deleteAll();
     AuthorQuery::create()->deleteAll();
     $books = new ObjectCollection();
     foreach (array('foo', 'bar') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $books[] = $b;
     }
     $a = new Author();
     $a->setBooks($books);
     $a->save();
     $books = $a->getBooks();
     $this->assertEquals('foo', $books[0]->getTitle());
     $this->assertEquals('bar', $books[1]->getTitle());
     $books = new ObjectCollection();
     foreach (array('bam', 'bom') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $books[] = $b;
     }
     $a->setBooks($books);
     $a->save();
     $books = $a->getBooks();
     $this->assertEquals('bam', $books[0]->getTitle());
     $this->assertEquals('bom', $books[1]->getTitle());
     $this->assertEquals(1, AuthorQuery::create()->count());
     $this->assertEquals(2, BookQuery::create()->count());
 }
 public function testLobSetting_WriteMode()
 {
     $blob_path = $this->getLobFile('tin_drum.gif');
     $blob2_path = $this->getLobFile('propel.gif');
     $clob_path = $this->getLobFile('tin_drum.txt');
     $book = BookQuery::create()->findOne();
     $m1 = new Media();
     $m1->setBook($book);
     $m1->setCoverImage(file_get_contents($blob_path));
     $m1->setExcerpt(file_get_contents($clob_path));
     $m1->save();
     MediaTableMap::clearInstancePool();
     // make sure we have the latest from the db:
     $m2 = MediaQuery::create()->findPk($m1->getId());
     // now attempt to assign a temporary stream, opened in 'w' mode, to the db
     $stream = fopen("php://memory", 'w');
     fwrite($stream, file_get_contents($blob2_path));
     $m2->setCoverImage($stream);
     $m2->save();
     fclose($stream);
     $m2->reload();
     $this->assertEquals(md5(file_get_contents($blob2_path)), md5(stream_get_contents($m2->getCoverImage())), "Expected contents to match when setting stream w/ 'w' mode");
     $stream2 = fopen("php://memory", 'w+');
     fwrite($stream2, file_get_contents($blob_path));
     rewind($stream2);
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($stream2)), "Expecting setup to be correct");
     $m2->setCoverImage($stream2);
     $m2->save();
     $m2->reload();
     $this->assertEquals(md5(file_get_contents($blob_path)), md5(stream_get_contents($m2->getCoverImage())), "Expected contents to match when setting stream w/ 'w+' mode");
 }
 public function testToArrayIncludesForeignObjects()
 {
     BookstoreDataPopulator::populate();
     BookTableMap::clearInstancePool();
     AuthorTableMap::clearInstancePool();
     PublisherTableMap::clearInstancePool();
     $c = new Criteria();
     $c->add(BookTableMap::COL_TITLE, 'Don Juan');
     $books = BookQuery::create(null, $c)->joinWith('Author')->find();
     $book = $books[0];
     $arr1 = $book->toArray(TableMap::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');
 }
 public function testFindOneWithLeftJoinWithOneToManyAndNullObjectsAndWithAdditionalJoins()
 {
     BookTableMap::clearInstancePool();
     AuthorTableMap::clearInstancePool();
     BookOpinionTableMap::clearInstancePool();
     BookReaderTableMap::clearInstancePool();
     $freud = new Author();
     $freud->setFirstName("Sigmund");
     $freud->setLastName("Freud");
     $freud->save($this->con);
     $publisher = new Publisher();
     $publisher->setName('Psycho Books');
     $publisher->save();
     $book = new Book();
     $book->setAuthor($freud);
     $book->setTitle('Weirdness');
     $book->setIsbn('abc123456');
     $book->setPrice('14.99');
     $book->setPublisher($publisher);
     $book->save();
     $query = BookQuery::create()->filterByTitle('Weirdness')->innerJoinAuthor()->useBookOpinionQuery(null, Criteria::LEFT_JOIN)->leftJoinBookReader()->endUse()->with('Author')->with('BookOpinion')->with('BookReader');
     $books = $query->find($this->con)->get(0);
     $this->assertEquals(0, count($books->getBookOpinions()));
 }
 public function testSelectArrayPaginate()
 {
     BookstoreDataPopulator::depopulate($this->con);
     BookstoreDataPopulator::populate($this->con);
     $pager = BookQuery::create()->select(array('Id', 'Title', 'ISBN', 'Price'))->paginate(1, 10, $this->con);
     $this->assertInstanceOf('Propel\\Runtime\\Util\\PropelModelPager', $pager);
     foreach ($pager as $result) {
         $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price'), array_keys($result));
     }
 }
 public function testFindPkWithOneToMany()
 {
     BookstoreDataPopulator::populate();
     BookPeer::clearInstancePool();
     AuthorPeer::clearInstancePool();
     ReviewPeer::clearInstancePool();
     $con = Propel::getServiceContainer()->getConnection(BookPeer::DATABASE_NAME);
     $book = BookQuery::create()->findOneByTitle('Harry Potter and the Order of the Phoenix', $con);
     $pk = $book->getPrimaryKey();
     BookPeer::clearInstancePool();
     $book = BookQuery::create()->setFormatter(ModelCriteria::FORMAT_ARRAY)->joinWith('Review')->findPk($pk, $con);
     $reviews = $book['Reviews'];
     $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated');
 }
 public function testSetterOneToManyReplacesOldObjectsByNewObjectsWithFkRequired()
 {
     // Ensure no data
     BookSummaryQuery::create()->deleteAll();
     BookQuery::create()->deleteAll();
     $bookSummaries = new ObjectCollection();
     foreach (array('foo', 'bar') as $summary) {
         $s = new BookSummary();
         $s->setSummary($summary);
         $bookSummaries[] = $s;
     }
     $b = new Book();
     $b->setTitle('Hello');
     $b->setBookSummaries($bookSummaries);
     $b->save();
     $bookSummaries = $b->getBookSummaries();
     $this->assertEquals('foo', $bookSummaries[0]->getSummary());
     $this->assertEquals('bar', $bookSummaries[1]->getSummary());
     $bookSummaries = new ObjectCollection();
     foreach (array('bam', 'bom') as $summary) {
         $s = new BookSummary();
         $s->setSummary($summary);
         $bookSummaries[] = $s;
     }
     $b->setBookSummaries($bookSummaries);
     $b->save();
     $bookSummaries = $b->getBookSummaries();
     $this->assertEquals('bam', $bookSummaries[0]->getSummary());
     $this->assertEquals('bom', $bookSummaries[1]->getSummary());
     $this->assertEquals(1, BookQuery::create()->count());
     $this->assertEquals(2, BookSummaryQuery::create()->count());
 }
Exemple #23
0
 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');
 }
Exemple #24
0
 public function testIsPrimary()
 {
     $q = AuthorQuery::create()->joinBook();
     $joins = $q->getJoins();
     $join = $joins['Book'];
     $with = new ModelWith($join);
     $this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary');
     $q = BookQuery::create()->joinAuthor()->joinReview();
     $joins = $q->getJoins();
     $join = $joins['Review'];
     $with = new ModelWith($join);
     $this->assertTrue($with->isPrimary(), 'A ModelWith initialized from a primary join is primary');
     $q = AuthorQuery::create()->join('Propel\\Tests\\Bookstore\\Author.Book')->join('Book.Publisher');
     $joins = $q->getJoins();
     $join = $joins['Publisher'];
     $with = new ModelWith($join);
     $this->assertFalse($with->isPrimary(), 'A ModelWith initialized from a non-primary join is not primary');
 }
Exemple #25
0
 public function testIneffectualUpdateUsingBookObject()
 {
     $con = Propel::getConnection(BookTableMap::DATABASE_NAME);
     $book = BookQuery::create()->findOne($con);
     $count = $con->getQueryCount();
     $book->setTitle($book->getTitle());
     $book->setISBN($book->getISBN());
     try {
         $rowCount = $book->save($con);
         $this->assertEquals(0, $rowCount, 'save() should indicate zero rows updated');
     } catch (Exception $ex) {
         $this->fail('save() threw an exception');
     }
     $this->assertEquals($count, $con->getQueryCount(), 'save() does not execute any queries when there are no changes');
 }
 public function testPruneSimpleKey()
 {
     BookstoreDataPopulator::depopulate();
     BookstoreDataPopulator::populate();
     $nbBooks = BookQuery::create()->prune()->count();
     $this->assertEquals(4, $nbBooks, 'prune() does nothing when passed a null object');
     $testBook = BookQuery::create()->findOne();
     $nbBooks = BookQuery::create()->prune($testBook)->count();
     $this->assertEquals(3, $nbBooks, 'prune() removes an object from the result');
 }
 public function testSetterCollectionReplacesOldObjectsByNewObjects()
 {
     // Ensure no data
     BookQuery::create()->deleteAll();
     BookClubListQuery::create()->deleteAll();
     BookListRelQuery::create()->deleteAll();
     $books = new ObjectCollection();
     foreach (array('foo', 'bar') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $books[] = $b;
     }
     $bookClubList = new BookClubList();
     $bookClubList->setBooks($books);
     $bookClubList->save();
     $books = $bookClubList->getBooks();
     $this->assertEquals('foo', $books[0]->getTitle());
     $this->assertEquals('bar', $books[1]->getTitle());
     $books = new ObjectCollection();
     foreach (array('bam', 'bom') as $title) {
         $b = new Book();
         $b->setTitle($title);
         $books[] = $b;
     }
     $bookClubList->setBooks($books);
     $bookClubList->save();
     $books = $bookClubList->getBooks();
     $this->assertEquals('bam', $books[0]->getTitle());
     $this->assertEquals('bom', $books[1]->getTitle());
     $this->assertEquals(1, BookClubListQuery::create()->count());
     $this->assertEquals(2, BookListRelQuery::create()->count());
     $this->assertEquals(4, BookQuery::create()->count());
 }
Exemple #28
0
 public function testCombineAndFilterBy()
 {
     $params = array();
     $sql = "SELECT  FROM book WHERE ((book.TITLE LIKE :p1 OR book.ISBN LIKE :p2) AND book.TITLE LIKE :p3)";
     $c = BookQuery::create()->condition('u1', 'book.TITLE LIKE ?', '%test1%')->condition('u2', 'book.ISBN LIKE ?', '%test2%')->combine(array('u1', 'u2'), 'or')->filterByTitle('%test3%');
     $result = $c->createSelectSql($params);
     $this->assertEquals($sql, $result);
     $params = array();
     $sql = "SELECT  FROM book WHERE (book.TITLE LIKE :p1 AND (book.TITLE LIKE :p2 OR book.ISBN LIKE :p3))";
     $c = BookQuery::create()->filterByTitle('%test3%')->condition('u1', 'book.TITLE LIKE ?', '%test1%')->condition('u2', 'book.ISBN LIKE ?', '%test2%')->combine(array('u1', 'u2'), 'or');
     $result = $c->createSelectSql($params);
     $this->assertEquals($sql, $result);
 }
 public function testModifiedObjectsRemainInTheCollection()
 {
     $c = new Criteria();
     $c->add(BookTableMap::ID, $this->books[0]->getId());
     $books = BookQuery::create(null, $c)->joinWithAuthor()->find();
     $books[0]->setTitle('Modified');
     $books2 = $books[0]->getAuthor()->getBooks();
     $this->assertEquals(2, count($books2));
     $this->assertEquals(2, $books2[0]->getAuthor()->countBooks());
     $this->assertEquals('Modified', $books2[0]->getTitle());
 }
Exemple #30
0
 public function testSubQueryCount()
 {
     $subCriteria = new BookQuery();
     $c = new BookQuery();
     $c->addSelectQuery($subCriteria, 'subCriteriaAlias');
     $c->filterByPrice(20, Criteria::LESS_THAN);
     $nbBooks = $c->count();
     $query = Propel::getConnection()->getLastExecutedQuery();
     $sql = $this->getSql("SELECT COUNT(*) FROM (SELECT subCriteriaAlias.ID, subCriteriaAlias.TITLE, subCriteriaAlias.ISBN, subCriteriaAlias.PRICE, subCriteriaAlias.PUBLISHER_ID, subCriteriaAlias.AUTHOR_ID FROM (SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID FROM `book`) AS subCriteriaAlias WHERE subCriteriaAlias.PRICE<20) propelmatch4cnt");
     $this->assertEquals($sql, $query, 'addSelectQuery() doCount is defined as complexQuery');
 }