public function testAddSelectColumnsAlias() { $c = new Criteria(); BookTableMap::addSelectColumns($c, 'foo'); $expected = array('foo.ID', 'foo.TITLE', 'foo.ISBN', 'foo.PRICE', 'foo.PUBLISHER_ID', 'foo.AUTHOR_ID'); $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() uses the second parameter as a table alias'); }
public function testAddSelectColumnsAlias() { $c = new Criteria(); BookTableMap::addSelectColumns($c, 'foo'); $expected = array('foo.id', 'foo.title', 'foo.isbn', 'foo.price', 'foo.publisher_id', 'foo.author_id'); $this->assertEquals($expected, $c->getSelectColumns(), 'addSelectColumns() uses the second parameter as a table alias'); }
public function testSetRelationMapRightAlias() { $bookTable = BookTableMap::getTableMap(); $join = new ModelJoin(); $join->setTableMap($bookTable); $join->setRelationMap($bookTable->getRelation('Author'), null, 'a'); $this->assertEquals(array(BookTableMap::COL_AUTHOR_ID), $join->getLeftColumns(), 'setRelationMap() automatically sets the left columns'); $this->assertEquals(array('a.id'), $join->getRightColumns(), 'setRelationMap() automatically sets the right columns using the right table alias'); }
public function testDelete() { $books = PropelQuery::from('Propel\\Tests\\Bookstore\\Book')->setFormatter(ModelCriteria::FORMAT_ARRAY)->find(); $books->delete(); // check that the modifications are persisted BookTableMap::clearInstancePool(); $books = PropelQuery::from('Propel\\Tests\\Bookstore\\Book')->find(); $this->assertEquals(0, count($books)); }
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 testDoCount() { try { $c = new Criteria(); $c->add(BookTableMap::ID, 12, ' BAD SQL'); BookTableMap::addSelectColumns($c); $c->doCount(); $this->fail('Missing expected exception on BAD SQL'); } catch (PropelException $e) { $this->assertContains($this->getSql('[SELECT COUNT(*) FROM `book` WHERE book.ID BAD SQL:p1]'), $e->getMessage(), 'SQL query is written in the exception message'); } }
/** * Tests the Base[Object]TableMap::translateFieldName() method */ public function testTranslateFieldName() { $types = array(TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM); $expecteds = array(TableMap::TYPE_PHPNAME => 'AuthorId', TableMap::TYPE_STUDLYPHPNAME => 'authorId', TableMap::TYPE_COLNAME => 'book.AUTHOR_ID', TableMap::TYPE_FIELDNAME => 'author_id', TableMap::TYPE_NUM => 5); foreach ($types as $fromType) { foreach ($types as $toType) { $name = $expecteds[$fromType]; $expected = $expecteds[$toType]; $result = BookTableMap::translateFieldName($name, $fromType, $toType); $this->assertEquals($expected, $result); } } }
public function testApplyLimitDuplicateColumnNameWithColumn() { Propel::getServiceContainer()->setAdapter('oracle', new OracleAdapter()); $c = new Criteria(); $c->setDbName('oracle'); BookTableMap::addSelectColumns($c); AuthorTableMap::addSelectColumns($c); $c->addAsColumn('BOOK_PRICE', BookTableMap::COL_PRICE); $c->setLimit(1); $params = []; $asColumns = $c->getAsColumns(); $sql = $c->createSelectSql($params); $this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.id AS ORA_COL_ALIAS_0, book.title AS ORA_COL_ALIAS_1, book.isbn AS ORA_COL_ALIAS_2, book.price AS ORA_COL_ALIAS_3, book.publisher_id AS ORA_COL_ALIAS_4, book.author_id AS ORA_COL_ALIAS_5, author.id AS ORA_COL_ALIAS_6, author.first_name AS ORA_COL_ALIAS_7, author.last_name AS ORA_COL_ALIAS_8, author.email AS ORA_COL_ALIAS_9, author.age AS ORA_COL_ALIAS_10, book.price AS BOOK_PRICE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found'); $this->assertEquals($asColumns, $c->getAsColumns(), 'createSelectSql supplementary add alias column'); }
public function testApplyLimitDuplicateColumnNameWithColumn() { Propel::getServiceContainer()->setAdapter('oracle', new OracleAdapter()); $c = new Criteria(); $c->setDbName('oracle'); BookTableMap::addSelectColumns($c); AuthorTableMap::addSelectColumns($c); $c->addAsColumn('BOOK_PRICE', BookTableMap::PRICE); $c->setLimit(1); $params = array(); $asColumns = $c->getAsColumns(); $sql = $c->createSelectSql($params); $this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS ORA_COL_ALIAS_0, book.TITLE AS ORA_COL_ALIAS_1, book.ISBN AS ORA_COL_ALIAS_2, book.PRICE AS ORA_COL_ALIAS_3, book.PUBLISHER_ID AS ORA_COL_ALIAS_4, book.AUTHOR_ID AS ORA_COL_ALIAS_5, author.ID AS ORA_COL_ALIAS_6, author.FIRST_NAME AS ORA_COL_ALIAS_7, author.LAST_NAME AS ORA_COL_ALIAS_8, author.EMAIL AS ORA_COL_ALIAS_9, author.AGE AS ORA_COL_ALIAS_10, book.PRICE AS BOOK_PRICE FROM book, author) A ) B WHERE B.PROPEL_ROWNUM <= 1', $sql, 'applyLimit() creates a subselect with aliased column names when a duplicate column name is found'); $this->assertEquals($asColumns, $c->getAsColumns(), 'createSelectSql supplementary add alias column'); }
public function testNeedsSelectAliases() { $c = new Criteria(); $this->assertFalse($c->needsSelectAliases(), 'Empty Criterias don\'t need aliases'); $c = new Criteria(); $c->addSelectColumn(BookTableMap::COL_ID); $c->addSelectColumn(BookTableMap::COL_TITLE); $this->assertFalse($c->needsSelectAliases(), 'Criterias with distinct column names don\'t need aliases'); $c = new Criteria(); BookTableMap::addSelectColumns($c); $this->assertFalse($c->needsSelectAliases(), 'Criterias with only the columns of a model don\'t need aliases'); $c = new Criteria(); $c->addSelectColumn(BookTableMap::COL_ID); $c->addSelectColumn(AuthorTableMap::COL_ID); $this->assertTrue($c->needsSelectAliases(), 'Criterias with common column names do need aliases'); }
public function testSubQueryExplicit() { $subCriteria = new BookQuery(); BookTableMap::addSelectColumns($subCriteria); $subCriteria->orderByTitle(Criteria::ASC); $c = new BookQuery(); BookTableMap::addSelectColumns($c, 'subCriteriaAlias'); $c->addSelectQuery($subCriteria, 'subCriteriaAlias', false); $c->groupBy('subCriteriaAlias.AuthorId'); if ($this->isDb('pgsql')) { $sql = $this->getSql("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 ORDER BY book.title ASC) AS subCriteriaAlias GROUP BY subCriteriaAlias.author_id,subCriteriaAlias.id,subCriteriaAlias.title,subCriteriaAlias.isbn,subCriteriaAlias.price,subCriteriaAlias.publisher_id"); } else { $sql = $this->getSql("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 ORDER BY book.title ASC) AS subCriteriaAlias GROUP BY subCriteriaAlias.author_id"); } $params = array(); $this->assertCriteriaTranslation($c, $sql, $params, 'addSubQueryCriteriaInFrom() combines two queries successfully'); }
public function testSubQueryExplicit() { $subCriteria = new BookQuery(); BookTableMap::addSelectColumns($subCriteria); $subCriteria->orderByTitle(Criteria::ASC); $c = new BookQuery(); BookTableMap::addSelectColumns($c, 'subCriteriaAlias'); $c->addSelectQuery($subCriteria, 'subCriteriaAlias', false); $c->groupBy('subCriteriaAlias.AuthorId'); if (in_array($this->getDriver(), array('mysql'))) { $sql = "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` ORDER BY book.TITLE ASC) AS subCriteriaAlias GROUP BY subCriteriaAlias.AUTHOR_ID"; } else { $sql = "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 ORDER BY book.TITLE ASC) AS subCriteriaAlias GROUP BY subCriteriaAlias.AUTHOR_ID"; } $params = array(); $this->assertCriteriaTranslation($c, $sql, $params, 'addSubQueryCriteriaInFrom() combines two queries successfully'); }
public function testSetterOneToManyWithExistingObjects() { // Ensure no data BookQuery::create()->deleteAll(); AuthorQuery::create()->deleteAll(); for ($i = 0; $i < 3; $i++) { $b = new Book(); $b->setTitle('Book ' . $i); $b->setISBN('FA404-' . $i); $b->save(); } BookTableMap::clearInstancePool(); $books = BookQuery::create()->find(); $a = new Author(); $a->setFirstName('Chuck'); $a->setLastName('Norris'); $a->setBooks($books); $a->save(); $this->assertEquals(3, count($a->getBooks())); $this->assertEquals(1, AuthorQuery::create()->count()); $this->assertEquals(3, BookQuery::create()->count()); $i = 0; foreach ($a->getBooks() as $book) { $this->assertEquals('Book ' . $i++, $book->getTitle()); } }
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 testSetterCollectionWithExistingObjects() { // Ensure no data BookQuery::create()->deleteAll(); BookClubListQuery::create()->deleteAll(); BookListRelQuery::create()->deleteAll(); for ($i = 0; $i < 3; $i++) { $b = new Book(); $b->setTitle('Book ' . $i); $b->setIsbn($i); $b->save(); } BookTableMap::clearInstancePool(); $books = BookQuery::create()->find(); $bookClubList = new BookClubList(); $bookClubList->setGroupLeader('fabpot'); $bookClubList->setBooks($books); $bookClubList->save(); $this->assertEquals(3, count($bookClubList->getBooks())); $this->assertEquals(3, BookQuery::create()->count()); $this->assertEquals(1, BookClubListQuery::create()->count()); $this->assertEquals(3, BookListRelQuery::create()->count()); $i = 0; foreach ($bookClubList->getBooks() as $book) { $this->assertEquals('Book ' . $i++, $book->getTitle()); } }
public function testPruneCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\\Propel\\Tests\\Bookstore\\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); $nbBookListRel = BookListRelQuery::create()->prune()->count(); $this->assertEquals(2, $nbBookListRel, 'prune() does nothing when passed a null object'); $testBookListRel = BookListRelQuery::create()->findOne(); $nbBookListRel = BookListRelQuery::create()->prune($testBookListRel)->count(); $this->assertEquals(1, $nbBookListRel, 'prune() removes an object from the result'); }
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 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%', Criteria::LIKE)->find(); $this->assertEquals(1, count($results)); $results = BookQuery::create()->where('Book.ISBN IN ?', ["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'); // Testing count() functionality // ------------------------------- $records = BookQuery::create()->find(); $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(BookTableMap::COL_ID, $phoenix->getId()); $phoenix = BookQuery::create(null, $crit)->findOne(); $this->assertNotNull($phoenix, "book 'phoenix' has been re-fetched from db"); $crit = new Criteria(); $crit->add(BookClubListTableMap::COL_ID, $blc1->getId()); $blc1 = BookClubListQuery::create(null, $crit)->findOne(); $this->assertNotNull($blc1, 'BookClubList 1 has been re-fetched from db'); $crit = new Criteria(); $crit->add(BookClubListTableMap::COL_ID, $blc2->getId()); $blc2 = BookClubListQuery::create(null, $crit)->findOne(); $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(BookTableMap::COL_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(AuthorTableMap::COL_ID, $hp->getAuthor()->getId()); $c->add(PublisherTableMap::COL_ID, $hp->getPublisher()->getId()); $c->setSingleRecord(true); BookTableMap::doDelete($c); // Checking to make sure correct records were removed. $this->assertEquals(3, AuthorQuery::create()->count(), 'Correct records were removed from author table'); $this->assertEquals(3, PublisherQuery::create()->count(), 'Correct records were removed from publisher table'); $this->assertEquals(3, BookQuery::create()->count(), 'Correct records were removed from book table'); // Attempting to delete books by complex criteria BookQuery::create()->filterByISBN("043935806X")->_or()->where('Book.ISBN = ?', "0380977427")->_or()->where('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->assertCount(0, AuthorQuery::create()->find(), 'no records in [author] table'); $this->assertCount(0, PublisherQuery::create()->find(), 'no records in [publisher] table'); $this->assertCount(0, BookQuery::create()->find(), 'no records in [book] table'); $this->assertCount(0, ReviewQuery::create()->find(), 'no records in [review] table'); $this->assertCount(0, MediaQuery::create()->find(), 'no records in [media] table'); $this->assertCount(0, BookClubListQuery::create()->find(), 'no records in [book_club_list] table'); $this->assertCount(0, BookListRelQuery::create()->find(), 'no records in [book_x_list] table'); }
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 testPopulateRelationOneToManyWithEmptyCollection() { $author = new Author(); $author->setFirstName('Chuck'); $author->setLastName('Norris'); $author->save($this->con); AuthorTableMap::clearInstancePool(); BookTableMap::clearInstancePool(); $coll = new ObjectCollection(); $coll->setFormatter(new ObjectFormatter(new ModelCriteria(null, '\\Propel\\Tests\\Bookstore\\Author'))); $coll[] = $author; $books = $coll->populateRelation('Book', null, $this->con); $this->assertEquals(0, $books->count()); $count = $this->con->getQueryCount(); $this->assertEquals(0, $author->countBooks()); $this->assertEquals($count, $this->con->getQueryCount()); }
public function testOrderByIgnoreCase() { $originalDB = Propel::getServiceContainer()->getAdapter(); Propel::getServiceContainer()->setAdapter(Propel::getServiceContainer()->getDefaultDatasource(), new MysqlAdapter()); Propel::getServiceContainer()->setDefaultDatasource('bookstore'); $criteria = new Criteria(); $criteria->setIgnoreCase(true); $criteria->addAscendingOrderByColumn(BookTableMap::COL_TITLE); BookTableMap::addSelectColumns($criteria); $params = []; $sql = $criteria->createSelectSql($params); $expectedSQL = 'SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id, UPPER(book.title) FROM book ORDER BY UPPER(book.title) ASC'; $this->assertEquals($expectedSQL, $sql); Propel::getServiceContainer()->setAdapter(Propel::getServiceContainer()->getDefaultDatasource(), $originalDB); }
public function testIsPrimaryString() { $bookTable = BookTableMap::getTableMap(); $idColumn = $bookTable->getColumn('ID'); $titleColumn = $bookTable->getColumn('TITLE'); $isbnColumn = $bookTable->getColumn('ISBN'); $this->assertFalse($idColumn->isPrimaryString(), 'isPrimaryString() returns false by default.'); $this->assertTrue($titleColumn->isPrimaryString(), 'isPrimaryString() returns true if set in schema.'); $this->assertFalse($isbnColumn->isPrimaryString(), 'isPrimaryString() returns false if not set in schema.'); $titleColumn->setPrimaryString(false); $this->assertFalse($titleColumn->isPrimaryString(), 'isPrimaryString() returns false if unset.'); $titleColumn->setPrimaryString(true); $this->assertTrue($titleColumn->isPrimaryString(), 'isPrimaryString() returns true if set.'); }
public function testFindOneWithClassAndColumn() { BookstoreDataPopulator::populate(); BookTableMap::clearInstancePool(); AuthorTableMap::clearInstancePool(); ReviewTableMap::clearInstancePool(); $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); $c->filterByTitle('The Tin Drum'); $c->join('Propel\\Tests\\Bookstore\\Book.Author'); $c->withColumn('Author.FirstName', 'AuthorName'); $c->withColumn('Author.LastName', 'AuthorName2'); $c->with('Author'); $c->limit(1); $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME); $books = $c->find($con); foreach ($books as $book) { break; } $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); $this->assertEquals('The Tin Drum', $book->getTitle()); $this->assertTrue($book->getAuthor() instanceof Author, 'ObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'ObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'ObjectFormatter adds withColumns as virtual columns'); $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'ObjectFormatter correctly hydrates all virtual columns'); }
public function testFindPkWithOneToMany() { BookstoreDataPopulator::populate(); BookTableMap::clearInstancePool(); AuthorTableMap::clearInstancePool(); ReviewTableMap::clearInstancePool(); $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME); $book = BookQuery::create()->findOneByTitle('Harry Potter and the Order of the Phoenix', $con); $pk = $book->getPrimaryKey(); BookTableMap::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 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 testWithAliasAddsSelectColumns() { $c = new TestableModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); BookTableMap::addSelectColumns($c); $c->join('Propel\\Tests\\Bookstore\\Book.Author a'); $c->with('a'); $expectedColumns = array(BookTableMap::ID, BookTableMap::TITLE, BookTableMap::ISBN, BookTableMap::PRICE, BookTableMap::PUBLISHER_ID, BookTableMap::AUTHOR_ID, 'a.ID', 'a.FIRST_NAME', 'a.LAST_NAME', 'a.EMAIL', 'a.AGE'); $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table'); }
public function testWithAliasAddsSelectColumns() { $c = new TestableModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); BookTableMap::addSelectColumns($c); $c->join('Propel\\Tests\\Bookstore\\Book.Author a'); $c->with('a'); $expectedColumns = array(BookTableMap::COL_ID, BookTableMap::COL_TITLE, BookTableMap::COL_ISBN, BookTableMap::COL_PRICE, BookTableMap::COL_PUBLISHER_ID, BookTableMap::COL_AUTHOR_ID, 'a.id', 'a.first_name', 'a.last_name', 'a.email', 'a.age'); $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table'); }
/** * Test passing null values to removeInstanceFromPool(). */ public function testRemoveInstanceFromPool_Null() { // if it throws an exception, then it's broken. try { BookTableMap::removeInstanceFromPool(null); } catch (Exception $x) { $this->fail("Expected to get no exception when removing an instance from the pool."); } }
public function testOrderByIgnoreCase() { $originalDB = Propel::getServiceContainer()->getAdapter(); Propel::getServiceContainer()->setAdapter(Propel::getServiceContainer()->getDefaultDatasource(), new MysqlAdapter()); $criteria = new Criteria(); $criteria->setIgnoreCase(true); $criteria->addAscendingOrderByColumn(BookTableMap::TITLE); BookTableMap::addSelectColumns($criteria); $params = array(); $sql = $criteria->createSelectSql($params); $expectedSQL = 'SELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, UPPER(book.TITLE) FROM `book` ORDER BY UPPER(book.TITLE) ASC'; $this->assertEquals($expectedSQL, $sql); Propel::getServiceContainer()->setAdapter(Propel::getServiceContainer()->getDefaultDatasource(), $originalDB); }
public function testQueryFilter() { $book = new Book(); $book->setTitle('Book 1'); $book->setISBN('12313'); $book->save(); $author = new Author(); $author->setFirstName('Steve'); $author->setLastName('Bla'); $author->save(); $bookLog = new PolymorphicRelationLog(); $bookLog->setMessage('book added'); $bookLog->setBook($book); $bookLog->save(); $authorLog = new PolymorphicRelationLog(); $authorLog->setMessage('author added'); $authorLog->setAuthor($author); $authorLog->save(); PolymorphicRelationLogTableMap::clearInstancePool(); $foundLog = PolymorphicRelationLogQuery::create()->filterByBook($book)->findOne(); $this->assertEquals($bookLog->getId(), $foundLog->getId()); $this->assertEquals('book', $foundLog->getTargetType()); $this->assertEquals($book, $foundLog->getBook()); $this->assertNull($foundLog->getAuthor()); PolymorphicRelationLogTableMap::clearInstancePool(); $foundLog = PolymorphicRelationLogQuery::create()->filterByAuthor($author)->findOne(); $this->assertEquals($authorLog->getId(), $foundLog->getId()); $this->assertEquals('author', $foundLog->getTargetType()); $this->assertEquals($author, $foundLog->getAuthor()); $this->assertNull($foundLog->getBook()); // ref methods BookTableMap::clearInstancePool(); $foundBook = BookQuery::create()->filterByPolymorphicRelationLog($bookLog)->findOne(); $this->assertEquals($book->getId(), $foundBook->getId()); BookTableMap::clearInstancePool(); $foundAuthor = AuthorQuery::create()->filterByPolymorphicRelationLog($bookLog)->findOne(); $this->assertNull($foundAuthor); $foundAuthor = AuthorQuery::create()->filterByPolymorphicRelationLog($authorLog)->findOne(); $this->assertEquals($author->getId(), $foundAuthor->getId()); }