function check_tables_empty() { try { print "\nChecking to see that tables are empty\n"; print "-------------------------------------\n\n"; print "Ensuring that there are no records in [author] table: "; $res = AuthorPeer::doSelect(new Criteria()); print boolTest(empty($res)); print "Ensuring that there are no records in [publisher] table: "; $res2 = PublisherPeer::doSelect(new Criteria()); print boolTest(empty($res2)); print "Ensuring that there are no records in [book] table: "; $res3 = AuthorPeer::doSelect(new Criteria()); print boolTest(empty($res3)); print "Ensuring that there are no records in [review] table: "; $res4 = ReviewPeer::doSelect(new Criteria()); print boolTest(empty($res4)); print "Ensuring that there are no records in [media] table: "; $res5 = MediaPeer::doSelect(new Criteria()); print boolTest(empty($res5)); print "Ensuring that there are no records in [book_club_list] table: "; $res6 = BookClubListPeer::doSelect(new Criteria()); print boolTest(empty($res6)); print "Ensuring that there are no records in [book_x_list] table: "; $res7 = BookListRelPeer::doSelect(new Criteria()); print boolTest(empty($res7)); return empty($res) && empty($res2) && empty($res3) && empty($res4) && empty($res5); } catch (Exception $e) { die("Error ensuring tables were empty: " . $e->__toString()); } }
/** * This is run after each unit test. It empties the database. */ protected function tearDown() { BookstoreDataPopulator::depopulate(); $this->assertEquals(0, count(BookPeer::doSelect(new Criteria())), "Expect book table to be empty."); $this->assertEquals(0, count(AuthorPeer::doSelect(new Criteria())), "Expect author table to be empty."); $this->assertEquals(0, count(PublisherPeer::doSelect(new Criteria())), "Expect publisher table to be empty."); $this->assertEquals(0, count(ReviewPeer::doSelect(new Criteria())), "Expect review table to be empty."); $this->assertEquals(0, count(MediaPeer::doSelect(new Criteria())), "Expect media table to be empty."); $this->assertEquals(0, count(BookstoreEmployeePeer::doSelect(new Criteria())), "Expect bookstore_employee table to be empty."); $this->assertEquals(0, count(BookstoreEmployeeAccountPeer::doSelect(new Criteria())), "Expect bookstore_employee_account table to be empty."); $this->assertEquals(0, count(BookstoreSalePeer::doSelect(new Criteria())), "Expect bookstore_sale table to be empty."); BookPeer::clearInstancePool(); $this->assertEquals(0, count(BookPeer::$instances), "Expected 0 Book instances after clearInstancePool()"); AuthorPeer::clearInstancePool(); $this->assertEquals(0, count(AuthorPeer::$instances), "Expected 0 Author instances after clearInstancePool()"); PublisherPeer::clearInstancePool(); $this->assertEquals(0, count(PublisherPeer::$instances), "Expected 0 Publisher instances after clearInstancePool()"); ReviewPeer::clearInstancePool(); $this->assertEquals(0, count(ReviewPeer::$instances), "Expected 0 Review instances after clearInstancePool()"); MediaPeer::clearInstancePool(); $this->assertEquals(0, count(MediaPeer::$instances), "Expected 0 Media instances after clearInstancePool()"); BookstoreEmployeePeer::clearInstancePool(); $this->assertEquals(0, count(BookstoreEmployeePeer::$instances), "Expected 0 BookstoreEmployee instances after clearInstancePool()"); BookstoreEmployeeAccountPeer::clearInstancePool(); $this->assertEquals(0, count(BookstoreEmployeeAccountPeer::$instances), "Expected 0 BookstoreEmployeeAccount instances after clearInstancePool()"); BookstoreSalePeer::clearInstancePool(); $this->assertEquals(0, count(BookstoreSalePeer::$instances), "Expected 0 BookstoreSale instances after clearInstancePool()"); parent::tearDown(); }
/** * Executes index action * * @param sfRequest $request A request object */ public function executeIndex(sfWebRequest $request) { # Recently added $c = new Criteria(); $c->addDescendingOrderByColumn(PluginPeer::CREATED_AT); $c->setLimit(6); $this->recent = PluginPeer::doSelect($c); # Most downloaded $c = new Criteria(); $c->addDescendingOrderByColumn(PluginPeer::DOWNLOADS_COUNT); $c->setLimit(3); $this->hot = PluginPeer::doSelect($c); # Tags $c = new Criteria(); $c->addDescendingOrderByColumn(TermPeer::COUNT); $c->setLimit(10); $this->terms = TermPeer::retrieveTags($c); # Authors $c = new Criteria(); $c->addDescendingOrderByColumn(AuthorPeer::LOGGED_AT); $c->setLimit(6); // if ($this->getUser()->isAuthenticated()) // $c->add(AuthorPeer::ID, $this->getUser()->getId(), Criteria::NOT_EQUAL); $this->authors = AuthorPeer::doSelect($c); }
protected function emptyTables() { $res1 = AuthorPeer::doDeleteAll(); $res2 = PublisherPeer::doDeleteAll(); $res3 = AuthorPeer::doDeleteAll(); $res4 = ReviewPeer::doDeleteAll(); $res5 = MediaPeer::doDeleteAll(); $res6 = BookClubListPeer::doDeleteAll(); $res7 = BookListRelPeer::doDeleteAll(); }
function runComplexQuery($i) { $c = new Criteria(); $cton1 = $c->getNewCriterion(AuthorPeer::ID, $this->authors[array_rand($this->authors)], Criteria::GREATER_THAN); $cton2 = $c->getNewCriterion(AuthorPeer::FIRST_NAME, '(' . AuthorPeer::FIRST_NAME . '||' . AuthorPeer::LAST_NAME . ') =' . $this->con->quote('John Doe'), Criteria::CUSTOM); $cton1->addOr($cton2); $c->add($cton1); $c->setLimit(5); AuthorPeer::doCount($c, $this->con); }
public function testApplyLimitDuplicateColumnName() { Propel::setDb('oracle', new DBOracle()); $c = new Criteria(); $c->setDbName('oracle'); BookPeer::addSelectColumns($c); AuthorPeer::addSelectColumns($c); $c->setLimit(1); $params = array(); $sql = BasePeer::createSelectSql($c, $params); $this->assertEquals('SELECT B.* FROM (SELECT A.*, rownum AS PROPEL_ROWNUM FROM (SELECT book.ID AS book_ID, book.TITLE AS book_TITLE, book.ISBN AS book_ISBN, book.PRICE AS book_PRICE, book.PUBLISHER_ID AS book_PUBLISHER_ID, book.AUTHOR_ID AS book_AUTHOR_ID, author.ID AS author_ID, author.FIRST_NAME AS author_FIRST_NAME, author.LAST_NAME AS author_LAST_NAME, author.EMAIL AS author_EMAIL, author.AGE AS author_AGESELECT book.ID, book.TITLE, book.ISBN, book.PRICE, book.PUBLISHER_ID, book.AUTHOR_ID, author.ID, author.FIRST_NAME, author.LAST_NAME, author.EMAIL, author.AGE 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'); }
public function testApplyLimitDuplicateColumnNameWithColumn() { Propel::setDb('oracle', new DBOracle()); $c = new Criteria(); $c->setDbName('oracle'); BookPeer::addSelectColumns($c); AuthorPeer::addSelectColumns($c); $c->addAsColumn('BOOK_PRICE', BookPeer::PRICE); $c->setLimit(1); $params = array(); $asColumns = $c->getAsColumns(); $sql = BasePeer::createSelectSql($c, $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::setDb('oracle', new DBOracle()); $c = new Criteria(); $c->setDbName('oracle'); BookPeer::addSelectColumns($c); AuthorPeer::addSelectColumns($c); $c->addAsColumn('BOOK_PRICE', BookPeer::PRICE); $c->setLimit(1); $params = array(); $asColumns = $c->getAsColumns(); $sql = BasePeer::createSelectSql($c, $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 getValues() { $map = call_user_func(array($this->peername, 'getPhpNameMap')); $c = new Criteria(); $c->clearSelectColumns(); foreach (array($this->label, $this->value) as $arr) { foreach ($arr['members'] as $member) { if (is_array($member)) { foreach ($member as $member) { $c->addSelectColumn(constant($this->peername . '::' . $map[$member])); } } else { $c->addSelectColumn(constant($this->peername . '::' . $map[$member])); } } } if (isset($this->label['initial']) or isset($this->value['initial'])) { $label = isset($this->label['initial']) ? $this->label['initial'] : ''; $value = isset($this->value['initial']) ? $this->value['initial'] : ''; $result[] = array('value' => $value, 'label' => $label); } $rs = AuthorPeer::doSelectStmt($c); $rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); while ($rs->next()) { $row = $rs->getRow(); foreach (array('label', 'value') as $key) { $arr = $this->{$key}; $params = array($arr['mask']); foreach ($arr['members'] as $member) { if (is_array($member)) { foreach ($member as $member) { $field_name = strtolower($map[$member]); // TODO is this always true? $params[] = $row[$field_name]; } } else { $field_name = strtolower($map[$member]); // TODO is this always true? $params[] = $row[$field_name]; } } ${$key} = call_user_func_array('sprintf', $params); $tmp[$key] = ${$key}; } $result[] = $tmp; } return $result; }
protected function setUp() { parent::setUp(); BookstoreDataPopulator::populate(); $cr = new Criteria(); $cr->add(AuthorPeer::LAST_NAME, "Rowling"); $cr->add(AuthorPeer::FIRST_NAME, "J.K."); $rowling = AuthorPeer::doSelectOne($cr); $this->authorId = $rowling->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Philosopher's Stone"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Chamber of Secrets"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Prisoner of Azkaban"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Goblet of Fire"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Half-Blood Prince"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); $book = new Book(); $book->setTitle("Harry Potter and the Deathly Hallows"); $book->setISBN("1234"); $book->setAuthor($rowling); $book->save(); $this->books[] = $book->getId(); }
/** * @see sfValidatorBase */ protected function doClean($values) { if (is_null($values)) { $values = array(); } if (!is_array($values)) { throw new InvalidArgumentException('You must pass an array parameter to the clean() method'); } $loginValue = isset($values[$this->getOption('login_field')]) ? $values[$this->getOption('login_field')] : null; $passwordValue = isset($values[$this->getOption('password_field')]) ? $values[$this->getOption('password_field')] : null; if (!$loginValue) { return false; } $valid = AuthorPeer::retrieveByEmailAndPassword($loginValue, sha1($passwordValue)); if (!$valid) { $error = new sfValidatorError($this, 'invalid', array('login_field' => $loginValue, 'password_field' => $passwordValue)); if ($this->getOption('throw_global_error')) { throw $error; } throw new sfValidatorErrorSchema($this, array($this->getOption('login_field') => $error)); } return $values; }
/** * Test reload(deep=true) method. */ public function testReloadDeep() { // arbitrary book $b = BookPeer::doSelectOne(new Criteria()); // arbitrary, different author $c = new Criteria(); $c->add(AuthorPeer::ID, $b->getAuthorId(), Criteria::NOT_EQUAL); $a = AuthorPeer::doSelectOne($c); $origAuthor = $b->getAuthor(); $b->setAuthor($a); $this->assertNotEquals($origAuthor, $b->getAuthor(), "Expected just-set object to be different from obj from DB"); $this->assertTrue($b->isModified()); $b->reload($deep = true); $this->assertEquals($origAuthor, $b->getAuthor(), "Expected object in DB to be restored"); $this->assertFalse($a->isModified()); }
public function testUseFkQueryTwiceTwoAliases() { $q = BookQuery::create()->useAuthorQuery('a')->filterByFirstName('Leo')->endUse()->useAuthorQuery('b')->filterByLastName('Tolstoi')->endUse(); $join1 = new ModelJoin(); $join1->setJoinType(Criteria::LEFT_JOIN); $join1->setTableMap(AuthorPeer::getTableMap()); $join1->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'a'); $join1->setRelationAlias('a'); $join2 = new ModelJoin(); $join2->setJoinType(Criteria::LEFT_JOIN); $join2->setTableMap(AuthorPeer::getTableMap()); $join2->setRelationMap(BookPeer::getTableMap()->getRelation('Author'), null, 'b'); $join2->setRelationAlias('b'); $q1 = BookQuery::create()->addAlias('a', AuthorPeer::TABLE_NAME)->addJoinObject($join1, 'a')->add('a.FIRST_NAME', 'Leo', Criteria::EQUAL)->addAlias('b', AuthorPeer::TABLE_NAME)->addJoinObject($join2, 'b')->add('b.LAST_NAME', 'Tolstoi', Criteria::EQUAL); $this->assertTrue($q->equals($q1), 'useFkQuery() called twice on the same relation with two aliases creates two joins'); }
public function testObjectInstances() { $sample = BookPeer::doSelectOne(new Criteria()); $samplePk = $sample->getPrimaryKey(); // 1) make sure consecutive calls to retrieveByPK() return the same object. $b1 = BookPeer::retrieveByPK($samplePk); $b2 = BookPeer::retrieveByPK($samplePk); $sampleval = md5(microtime()); $this->assertTrue($b1 === $b2, "Expected object instances to match for calls with same retrieveByPK() method signature."); // 2) make sure that calls to doSelect also return references to the same objects. $allbooks = BookPeer::doSelect(new Criteria()); foreach ($allbooks as $testb) { if ($testb->getPrimaryKey() == $b1->getPrimaryKey()) { $this->assertTrue($testb === $b1, "Expected same object instance from doSelect() as from retrieveByPK()"); } } // 3) test fetching related objects $book = BookPeer::retrieveByPK($samplePk); $bookauthor = $book->getAuthor(); $author = AuthorPeer::retrieveByPK($bookauthor->getId()); $this->assertTrue($bookauthor === $author, "Expected same object instance when calling fk object accessor as retrieveByPK()"); // 4) test a doSelectJoin() $morebooks = BookPeer::doSelectJoinAuthor(new Criteria()); for ($i = 0, $j = 0; $j < count($morebooks); $i++, $j++) { $testb1 = $allbooks[$i]; $testb2 = $allbooks[$j]; $this->assertTrue($testb1 === $testb2, "Expected the same objects from consecutive doSelect() calls."); // we could probably also test this by just verifying that $book & $testb are the same if ($testb1->getPrimaryKey() === $book) { $this->assertTrue($book->getAuthor() === $testb1->getAuthor(), "Expected same author object in calls to pkey-matching books."); } } // 5) test creating a new object, saving it, and then retrieving that object (should all be same instance) $b = new BookstoreEmployee(); $b->setName("Testing"); $b->setJobTitle("Testing"); $b->save(); $empId = $b->getId(); $this->assertSame($b, BookstoreEmployeePeer::retrieveByPK($empId), "Expected newly saved object to be same instance as pooled."); }
function clearCache() { BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); }
public function testFindPkWithOneToMany() { BookstoreDataPopulator::populate(); BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); ReviewPeer::clearInstancePool(); $con = Propel::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 testFindPkWithOneToMany() { BookstoreDataPopulator::populate(); BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); ReviewPeer::clearInstancePool(); $con = Propel::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()->joinWith('Review')->findPk($pk, $con); $count = $con->getQueryCount(); $reviews = $book->getReviews(); $this->assertEquals($count, $con->getQueryCount(), 'with() hydrates the related objects to save a query '); $this->assertEquals(2, count($reviews), 'Related objects are correctly hydrated'); }
public function testToArrayIncludeForeignObjects() { 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, 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, 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'); }
The tests expect a model similar to this one: propel: article: id: ~ title: varchar(255) Beware that the tables for these models will be emptied by the tests, so use a test database connection. */ include dirname(__FILE__).'/../../bootstrap.php'; $con = Propel::getConnection(); // cleanup database AuthorPeer::doDeleteAll(); CommentPeer::doDeleteAll(); CategoryPeer::doDeleteAll(); ArticlePeer::doDeleteAll(); $t = new lime_test(33, new lime_output_color()); $article1 = new Article(); $article1->setTitle('tt1'); $article1->save(); $article2 = new Article(); $article2->setTitle('tt2'); $article2->save(); $article3 = new Article(); $article3->setTitle('tt3'); $article3->save();
public function testWithOneToManyAddsSelectColumns() { $c = new TestableModelCriteria('bookstore', 'Author'); AuthorPeer::addSelectColumns($c); $c->leftJoin('Author.Book'); $c->with('Book'); $expectedColumns = array(AuthorPeer::ID, AuthorPeer::FIRST_NAME, AuthorPeer::LAST_NAME, AuthorPeer::EMAIL, AuthorPeer::AGE, BookPeer::ID, BookPeer::TITLE, BookPeer::ISBN, BookPeer::PRICE, BookPeer::PUBLISHER_ID, BookPeer::AUTHOR_ID); $this->assertEquals($expectedColumns, $c->getSelectColumns(), 'with() adds the columns of the related table even in a one-to-many relationship'); }
/** * Selects a collection of AuthorArticle objects pre-filled with all related objects except Article. * * @param Criteria $criteria * @param PropelPDO $con * @param String $join_behavior the type of joins to use, defaults to Criteria::LEFT_JOIN * @return array Array of AuthorArticle objects. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ public static function doSelectJoinAllExceptArticle(Criteria $criteria, $con = null, $join_behavior = Criteria::LEFT_JOIN) { $criteria = clone $criteria; // Set the correct dbName if it has not been overridden // $criteria->getDbName() will return the same object if not set to another value // so == check is okay and faster if ($criteria->getDbName() == Propel::getDefaultDB()) { $criteria->setDbName(self::DATABASE_NAME); } AuthorArticlePeer::addSelectColumns($criteria); $startcol2 = AuthorArticlePeer::NUM_COLUMNS - AuthorArticlePeer::NUM_LAZY_LOAD_COLUMNS; AuthorPeer::addSelectColumns($criteria); $startcol3 = $startcol2 + (AuthorPeer::NUM_COLUMNS - AuthorPeer::NUM_LAZY_LOAD_COLUMNS); $criteria->addJoin(AuthorArticlePeer::AUTHOR_ID, AuthorPeer::ID, $join_behavior); // symfony_behaviors behavior foreach (sfMixer::getCallables(self::getMixerPreSelectHook(__FUNCTION__)) as $sf_hook) { call_user_func($sf_hook, 'BaseAuthorArticlePeer', $criteria, $con); } $stmt = BasePeer::doSelect($criteria, $con); $results = array(); while ($row = $stmt->fetch(PDO::FETCH_NUM)) { $key1 = AuthorArticlePeer::getPrimaryKeyHashFromRow($row, 0); if (null !== ($obj1 = AuthorArticlePeer::getInstanceFromPool($key1))) { // We no longer rehydrate the object, since this can cause data loss. // See http://propel.phpdb.org/trac/ticket/509 // $obj1->hydrate($row, 0, true); // rehydrate } else { $cls = AuthorArticlePeer::getOMClass(false); $obj1 = new $cls(); $obj1->hydrate($row); AuthorArticlePeer::addInstanceToPool($obj1, $key1); } // if obj1 already loaded // Add objects for joined Author rows $key2 = AuthorPeer::getPrimaryKeyHashFromRow($row, $startcol2); if ($key2 !== null) { $obj2 = AuthorPeer::getInstanceFromPool($key2); if (!$obj2) { $cls = AuthorPeer::getOMClass(false); $obj2 = new $cls(); $obj2->hydrate($row, $startcol2); AuthorPeer::addInstanceToPool($obj2, $key2); } // if $obj2 already loaded // Add the $obj1 (AuthorArticle) to the collection in $obj2 (Author) $obj2->addAuthorArticle($obj1); } // if joined row is not null $results[] = $obj1; } $stmt->closeCursor(); return $results; }
public function testPopulateRelationManyToOne() { $con = Propel::getConnection(); AuthorPeer::clearInstancePool(); BookPeer::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 testFindOneWithClassAndColumn() { BookstoreDataPopulator::populate(); BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); ReviewPeer::clearInstancePool(); $c = new ModelCriteria('bookstore', 'Book'); $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); $c->filterByTitle('The Tin Drum'); $c->join('Book.Author'); $c->withColumn('Author.FirstName', 'AuthorName'); $c->withColumn('Author.LastName', 'AuthorName2'); $c->with('Author'); $c->limit(1); $con = Propel::getConnection(BookPeer::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, 'PropelObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'PropelObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'PropelObjectFormatter adds withColumns as virtual columns'); $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'PropelObjectFormatter correctly hydrates all virtual columns'); }
public function getAuthor($con = null) { include_once 'lib/model/om/BaseAuthorPeer.php'; if ($this->aAuthor === null && $this->author_id !== null) { $this->aAuthor = AuthorPeer::retrieveByPK($this->author_id, $con); } return $this->aAuthor; }
public function testNestedTransactionForceRollBack() { $con = Propel::getConnection(BookPeer::DATABASE_NAME); $driver = $con->getAttribute(PDO::ATTR_DRIVER_NAME); // main transaction $con->beginTransaction(); $a = new Author(); $a->setFirstName('Test'); $a->setLastName('User'); $a->save($con); $authorId = $a->getId(); // nested transaction $con->beginTransaction(); $a2 = new Author(); $a2->setFirstName('Test2'); $a2->setLastName('User2'); $a2->save($con); $authorId2 = $a2->getId(); // force rollback $con->forceRollback(); $this->assertEquals(0, $con->getNestedTransactionCount(), 'nested transaction is null after nested transaction forced rollback'); $this->assertFalse($con->isInTransaction(), 'PropelPDO is not in transaction after nested transaction force rollback'); AuthorPeer::clearInstancePool(); $at = AuthorPeer::retrieveByPK($authorId); $this->assertNull($at, "Rolled back transaction is not persisted in database"); $at2 = AuthorPeer::retrieveByPK($authorId2); $this->assertNull($at2, "Forced Rolled back nested transaction is not persisted in database"); }
public function testRefFKGetJoin() { BookstoreDataPopulator::populate(); BookPeer::clearInstancePool(); AuthorPeer::clearInstancePool(); PublisherPeer::clearInstancePool(); $con = Propel::getConnection(BookPeer::DATABASE_NAME); $author = AuthorPeer::doSelectOne(new Criteria(), $con); // populate book instance pool $books = $author->getBooksJoinPublisher(null, $con); $sql = $con->getLastExecutedQuery(); $publisher = $books[0]->getPublisher($con); $this->assertEquals($sql, $con->getLastExecutedQuery(), 'refFK getter uses instance pool if possible'); }
/** * Populates the object using an array. * * This is particularly useful when populating an object from one of the * request arrays (e.g. $_POST). This method goes through the column * names, checking to see whether a matching key exists in populated * array. If so the setByName() method is called for that column. * * You can specify the key type of the array by additionally passing one * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME, * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM. * The default key type is the column's phpname (e.g. 'AuthorId') * * @param array $arr An array to populate the object from. * @param string $keyType The type of keys the array uses. * @return void */ public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = AuthorPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) { $this->setId($arr[$keys[0]]); } if (array_key_exists($keys[1], $arr)) { $this->setName($arr[$keys[1]]); } }
/** * Test the doDeleteAll() method when onDelete="SETNULL". */ public function testDoDeleteAll_SetNull() { $c = new Criteria(); $c->add(BookPeer::AUTHOR_ID, null, Criteria::NOT_EQUAL); // 1) make sure there are some books with valid authors $this->assertTrue(count(BookPeer::doSelect($c)) > 0, "Expect some book.author_id columns that are not NULL."); // 2) delete all the authors AuthorPeer::doDeleteAll(); // 3) now verify that the book.author_id columns are all nul $this->assertEquals(0, count(BookPeer::doSelect($c)), "Expect all book.author_id columns to be NULL."); }
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 = dirname(__FILE__) . '/../../etc/lob/tin_drum.gif'; $blob2_path = dirname(__FILE__) . '/../../etc/lob/propel.gif'; $clob_path = dirname(__FILE__) . '/../../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 // --------------- require_once 'tools/helpers/bookstore/validator/ISBNValidator.php'; $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'); }
/** * Get the associated Author object * * @param PropelPDO Optional Connection object. * @return Author The associated Author object. * @throws PropelException */ public function getAuthor(PropelPDO $con = null) { if ($this->aAuthor === null && $this->author_id !== null) { $this->aAuthor = AuthorPeer::retrieveByPk($this->author_id); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aAuthor->addAuthorArticles($this); */ } return $this->aAuthor; }