public function testWithObjects()
 {
     $criteria = Criteria::create(TestUser::dao())->add(Expression::containsIp(IpRange::create('192.168.1.1-192.168.1.255'), 'ip'))->addProjection(Projection::property('id'));
     $this->assertEquals($criteria->toDialectString(PostgresDialect::me()), 'SELECT "test_user"."id" FROM "test_user" WHERE "test_user"."ip" <<= \'192.168.1.1-192.168.1.255\'');
     $criteria = Criteria::create(TestInternetProvider::dao())->add(Expression::containsIp('range', IpAddress::create('42.42.42.42')))->addProjection(Projection::property('id'));
     $this->assertEquals($criteria->toDialectString(PostgresDialect::me()), 'SELECT "test_internet_provider"."id" FROM "test_internet_provider" WHERE \'42.42.42.42\' <<= "test_internet_provider"."range"');
 }
 public function testBoolean()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         //creating moscow
         $moscow = TestCity::create()->setName('Moscow');
         $moscow = $moscow->dao()->add($moscow);
         $moscowId = $moscow->getId();
         /* @var $moscow TestCity */
         //now moscow capital
         $moscow->dao()->merge($moscow->setCapital(true));
         TestCity::dao()->dropIdentityMap();
         Criteria::create(TestCity::dao())->setSilent(false)->add(Expression::isTrue('capital'))->get();
         TestCity::dao()->dropIdentityMap();
         $moscow = Criteria::create(TestCity::dao())->setSilent(false)->add(Expression::isNull('large'))->get();
         TestCity::dao()->dropIdentityMap();
         //now moscow large
         $moscow = $moscow->dao()->merge($moscow->setLarge(true));
         TestCity::dao()->dropIdentityMap();
         $moscow = TestCity::dao()->getById($moscowId);
         $this->assertTrue($moscow->getCapital());
         $this->assertTrue($moscow->getLarge());
         Criteria::create(TestCity::dao())->setSilent(false)->add(Expression::not(Expression::isFalse('large')))->get();
         TestCity::dao()->dropIdentityMap();
     }
 }
 public function testCriteria()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         /* @var $db DB */
         DBPool::me()->setDefault($db);
         $this->getDBCreator()->fillDB();
         $queryResult = Criteria::create(TestCity::dao())->getResult();
         $this->assertEquals(2, $queryResult->getCount());
         Cache::me()->clean();
     }
 }
 public function testLazy()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $parent = TestParentObject::create();
         $child = TestChildObject::create()->setParent($parent);
         $parent->dao()->add($parent);
         $child->dao()->add($child);
         $this->assertEquals($parent->getId(), Criteria::create(TestChildObject::dao())->setProjection(Projection::property('parent.id', 'parentId'))->add(Expression::eq('id', $child->getId()))->getCustom('parentId'));
     }
 }
 public function testIpRangeProperty()
 {
     foreach (DBTestPool::me()->getPool() as $db) {
         DBPool::me()->setDefault($db);
         $akado = TestInternetProvider::create()->setName('Akada')->setRange(IpRange::create(IpAddress::create('192.168.1.1'), IpAddress::create('192.168.1.42')));
         TestInternetProvider::dao()->add($akado);
         $plainRange = Criteria::create(TestInternetProvider::dao())->addProjection(Projection::property('range'))->add(Expression::eq('name', 'Akada'))->getCustom();
         $this->assertEquals($plainRange['range'], '192.168.1.1-192.168.1.42');
         TestInternetProvider::dao()->add(TestInternetProvider::create()->setName('DomRu')->setRange(IpRange::create('192.168.2.0/24')));
         $list = Criteria::create(TestInternetProvider::dao())->addOrder('id')->getList();
         $this->assertEquals(count($list), 2);
     }
 }
 public static function down(DAOConnected $object, LogicalObject $exp = null)
 {
     $getMethod = 'get' . ucfirst(self::$property);
     Assert::isTrue(method_exists($object, $getMethod));
     $oldPosition = $object->{$getMethod}();
     $criteria = Criteria::create($object->dao())->add(Expression::gt(self::$property, $oldPosition))->addOrder(OrderBy::create(self::$property)->asc())->setLimit(1);
     if ($exp) {
         $criteria->add($exp);
     }
     if ($lowerObject = $criteria->get()) {
         DaoUtils::setNullValue(self::$nullValue);
         DaoUtils::swap($lowerObject, $object, self::$property);
     }
 }
 public function testForgottenDao()
 {
     $criteria = Criteria::create()->add(Expression::eq('id', 42));
     $listCriteria = clone $criteria;
     try {
         $listCriteria->getList();
         $this->fail();
     } catch (WrongStateException $e) {
         /*it's good*/
     }
     $customCriteria = clone $criteria;
     try {
         $customCriteria->addProjection(Projection::property('id'))->getCustomList();
         $this->fail();
     } catch (WrongStateException $e) {
         /*it's good*/
     }
 }
 public function unified()
 {
     $user = TestUser::dao()->getById(1);
     $encapsulant = TestEncapsulant::dao()->getPlainList();
     $collectionDao = $user->getEncapsulants();
     $collectionDao->fetch()->setList($encapsulant);
     $collectionDao->save();
     unset($collectionDao);
     // fetch
     $encapsulantsList = $user->getEncapsulants()->getList();
     $piter = TestCity::dao()->getById(1);
     $moscow = TestCity::dao()->getById(2);
     for ($i = 0; $i < 10; $i++) {
         $this->assertEquals($encapsulantsList[$i]->getId(), $i + 1);
         $this->assertEquals($encapsulantsList[$i]->getName(), $i);
         $cityList = $encapsulantsList[$i]->getCities()->getList();
         $this->assertEquals($cityList[0], $piter);
         $this->assertEquals($cityList[1], $moscow);
     }
     unset($encapsulantsList);
     // lazy fetch
     $encapsulantsList = $user->getEncapsulants(true)->getList();
     for ($i = 1; $i < 11; $i++) {
         $this->assertEquals($encapsulantsList[$i], $i);
     }
     // count
     $user->getEncapsulants()->clean();
     $this->assertEquals($user->getEncapsulants()->getCount(), 10);
     $criteria = Criteria::create(TestEncapsulant::dao())->add(Expression::in('cities.id', array($piter->getId(), $moscow->getId())));
     $user->getEncapsulants()->setCriteria($criteria);
     $this->assertEquals($user->getEncapsulants()->getCount(), 20);
     // distinct count
     $user->getEncapsulants()->clean();
     $user->getEncapsulants()->setCriteria($criteria->setDistinct(true));
     if (DBPool::me()->getLink() instanceof SQLite) {
         // TODO: sqlite does not support such queries yet
         return null;
     }
     $this->assertEquals($user->getEncapsulants()->getCount(), 10);
 }
Example #9
0
 public function getLatestActivities($type = Activity::ACTIVITY_TYPE_COMMIT)
 {
     if (!in_array($type, array(Activity::ACTIVITY_TYPE_COMMIT, Activity::ACTIVITY_TYPE_RECOMMEND))) {
         throw new \InvalidArgumentException();
     }
     $criteria = Criteria::create()->where(Criteria::expr()->eq('type', $type))->orderBy(array("createdAt" => "DESC"))->setFirstResult(0)->setMaxResults(30);
     return $this->activities->matching($criteria);
 }
 public function testQuery()
 {
     $criteria = Criteria::create(TestUser::dao())->setProjection(Projection::property('id'))->add(Expression::isTrue('id'));
     $this->assertCriteria('id from TestUser where id is true', $criteria)->assertCriteria('id from TestUser where id is true order by id asc', $criteria->addOrder(OrderBy::create('id')->asc()))->assertCriteria('id from TestUser where id is true order by id asc limit 10 offset 1', $criteria->setLimit(10)->setOffset(1))->assertCriteria('id from TestUser where id is true group by id order by id asc limit 10 offset 1', $criteria->setProjection(Projection::chain()->add(Projection::property('id'))->add(Projection::group('id'))))->assertCriteria('id from TestUser where id is true group by id order by id asc having id = 1 limit 10 offset 1', $criteria->setProjection(Projection::chain()->add(Projection::property('id'))->add(Projection::group('id'))->add(Projection::having(Expression::eq('id', 1)))))->assertCriteria('count(id) as count from TestUser group by id having count = 2', Criteria::create(TestUser::dao())->setProjection(Projection::chain()->add(Projection::count('id', 'count'))->add(Projection::group('id'))->add(Projection::having(Expression::eq('count', 2)))));
 }
 public function testHaving()
 {
     $query = OQL::select('from TestUser');
     $criteria = Criteria::create(TestUser::dao());
     $this->assertCriteria($query->addHaving(OQL::having('id > 0')), $criteria->addProjection(Projection::having(Expression::gt('id', 0))));
     $this->assertCriteria($query->addHaving(OQL::having('name is not null and (id <> $1 or id != $2)')->bindNext(4)->bindNext(8)), $criteria->addProjection(Projection::having(Expression::expAnd(Expression::notNull('name'), Expression::expOr(Expression::notEq('id', 4), Expression::notEq('id', 8))))));
     $this->assertEquals(OQL::having('id + $15')->bind(15, 16)->toProjection(), Projection::having(Expression::add('id', 16)));
     $this->assertCriteria(OQL::select('from TestUser')->addHaving(OQL::having('id = $1')->bindNext(23))->bindNext(42), Criteria::create(TestUser::dao())->addProjection(Projection::having(Expression::eq('id', 42))));
 }
 /**
  * @param string $name
  * @return TestCity
  */
 public static function getCityByName($name)
 {
     return Criteria::create(TestCity::dao())->add(Expression::eq('name', DBValue::create($name)))->get();
 }
Example #13
0
 public function allocate($object)
 {
     if (!$object->getPkStaffid()) {
         $staff = new \Application\Entity\Staff();
     } else {
         $criteria = Criteria::create()->where(Criteria::expr()->eq("pkStaffid", $object->getPkStaffid()));
         $staff = $this->getEntity("\\Application\\Entity\\Staff", $criteria);
     }
     //Set user object values to be saved
     $staff->setFkUserid($object->getFkUserid());
     $staff->setFkDeptid($object->getFkDeptid());
     $staff->setMode($object->getMode());
     try {
         //Commit values set to the object
         if (!$object->getPkStaffid()) {
             $this->em->persist($staff);
         }
         //Save values if just updating record
         $this->em->flush($staff);
         return $staff;
     } catch (Exception $e) {
         throw $e->getMessages();
     }
 }
 private function loadNextChunk($id)
 {
     Assert::isNotNull($this->dao);
     $this->offset = 0;
     $criteria = Criteria::create($this->dao);
     if ($this->projection) {
         $criteria->setProjection($this->projection);
     }
     $criteria->addOrder($this->keyProperty)->setLimit($this->chunkSize);
     if ($id !== null) {
         $criteria->add(Expression::gt($this->keyProperty, $id));
     }
     // preserving memory bloat
     $this->dao->dropIdentityMap();
     $this->chunk = $criteria->getList();
     return $this->chunk;
 }
 /**
  * @param TestCase $test
  * @return DBTestCreator
  */
 public function fillDB(TestCase $test = null)
 {
     $moscow = TestCity::create()->setName('Moscow');
     $piter = TestCity::create()->setName('Saint-Peterburg');
     $mysqler = TestUser::create()->setCity($moscow)->setCredentials(Credentials::create()->setNickname('mysqler')->setPassword(sha1('mysqler')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'));
     $postgreser = clone $mysqler;
     $postgreser->setCredentials(Credentials::create()->setNickName('postgreser')->setPassword(sha1('postgreser')))->setCity($piter)->setUrl(HttpUrl::create()->parse('http://postgresql.org/'));
     $piter = TestCity::dao()->add($piter);
     $moscow = TestCity::dao()->add($moscow);
     if ($test) {
         $test->assertEquals($piter->getId(), 1);
         $test->assertEquals($moscow->getId(), 2);
     }
     $postgreser = TestUser::dao()->add($postgreser);
     for ($i = 0; $i < 10; $i++) {
         $encapsulant = TestEncapsulant::dao()->add(TestEncapsulant::create()->setName($i));
         $encapsulant->getCities()->fetch()->setList(array($piter, $moscow))->save();
     }
     $mysqler = TestUser::dao()->add($mysqler);
     if ($test) {
         $test->assertEquals($postgreser->getId(), 1);
         $test->assertEquals($mysqler->getId(), 2);
     }
     if ($test) {
         // put them in cache now
         TestUser::dao()->dropIdentityMap();
         TestUser::dao()->getById(1);
         TestUser::dao()->getById(2);
         if ($test instanceof DBDataTest) {
             $test->getListByIdsTest();
         }
         Cache::me()->clean();
         $test->assertTrue($postgreser == TestUser::dao()->getById(1));
         $test->assertTrue($mysqler == TestUser::dao()->getById(2));
     }
     $firstClone = clone $postgreser;
     $secondClone = clone $mysqler;
     $firstCount = TestUser::dao()->dropById($postgreser->getId());
     $secondCount = TestUser::dao()->dropByIds(array($mysqler->getId()));
     if ($test) {
         $test->assertEquals($firstCount, 1);
         $test->assertEquals($secondCount, 1);
         try {
             TestUser::dao()->getById(1);
             $test->fail();
         } catch (ObjectNotFoundException $e) {
             /* pass */
         }
         $result = Criteria::create(TestUser::dao())->add(Expression::eq(1, 2))->getResult();
         $test->assertEquals($result->getCount(), 0);
         $test->assertEquals($result->getList(), array());
     }
     TestUser::dao()->import($firstClone);
     TestUser::dao()->import($secondClone);
     if ($test && $test instanceof DBDataTest) {
         // cache multi-get
         $test->getListByIdsTest();
         $test->getListByIdsTest();
     }
     return $this;
 }
Example #16
0
 public function saveEmployment($studentobject)
 {
     if (!$studentobject->getPkEmploymentid()) {
         $student = new \Application\Entity\Employment();
     } else {
         $criteria = Criteria::create()->where(Criteria::expr()->eq("pkEmploymentid", $studentobject->getPkEmploymentid()));
         $student = $this->getEntity("\\Application\\Entity\\Employment", $criteria);
     }
     //Set user object values to be saved
     $student->setFkStudentid($studentobject->getFkStudentid());
     $student->setDesignation($studentobject->getDesignation());
     $student->setOrganization($studentobject->getOrganization());
     $student->setEndYear($studentobject->getEndYear());
     $student->setStartYear($studentobject->getStartYear());
     $student->setIsCurrent($studentobject->getIsCurrent());
     try {
         //Commit values set to the object
         if (!$studentobject->getPkEmploymentid()) {
             $this->em->persist($student);
         }
         //Save values if just updating record
         $this->em->flush($student);
         return $student;
     } catch (Doctrine\ORM\ORMException $e) {
         throw $e->getMessage();
     }
 }
 /**
  * @return MetaConfiguration
  **/
 public function checkIntegrity()
 {
     $out = $this->getOutput()->newLine()->infoLine('Checking sanity of generated files: ')->newLine();
     set_include_path(get_include_path() . PATH_SEPARATOR . ONPHP_META_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_DAO_DIR . PATH_SEPARATOR . ONPHP_META_PROTO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_DAO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_PROTO_DIR . PATH_SEPARATOR);
     $out->info("\t");
     $formErrors = array();
     foreach ($this->classes as $name => $class) {
         if (!($class->getPattern() instanceof SpookedClassPattern || $class->getPattern() instanceof SpookedEnumerationPattern || $class->getPattern() instanceof InternalClassPattern) && class_exists($class->getName(), true)) {
             $out->info($name, true);
             $info = new ReflectionClass($name);
             $this->checkClassSanity($class, $info);
             if ($info->implementsInterface('Prototyped')) {
                 $this->checkClassSanity($class, new ReflectionClass('Proto' . $name));
             }
             if ($info->implementsInterface('DAOConnected')) {
                 $this->checkClassSanity($class, new ReflectionClass($name . 'DAO'));
             }
             foreach ($class->getInterfaces() as $interface) {
                 Assert::isTrue($info->implementsInterface($interface), 'class ' . $class->getName() . ' expected to implement interface ' . $interface);
             }
             // special handling for Enumeration instances
             if ($class->getPattern() instanceof EnumerationClassPattern) {
                 $object = new $name(call_user_func(array($name, 'getAnyId')));
                 Assert::isTrue(unserialize(serialize($object)) == $object);
                 $out->info(', ');
                 if ($this->checkEnumerationRefIntegrity) {
                     $this->checkEnumerationReferentialIntegrity($object, $class->getTableName());
                 }
                 continue;
             }
             if ($class->getPattern() instanceof AbstractClassPattern) {
                 $out->info(', ');
                 continue;
             }
             $object = new $name();
             $proto = $object->proto();
             $form = $proto->makeForm();
             foreach ($class->getProperties() as $name => $property) {
                 Assert::isTrue($property->toLightProperty($class) == $proto->getPropertyByName($name), 'defined property does not match autogenerated one - ' . $class->getName() . '::' . $property->getName());
             }
             if (!$object instanceof DAOConnected) {
                 $out->info(', ');
                 continue;
             }
             $dao = $object->dao();
             Assert::isEqual($dao->getIdName(), $class->getIdentifier()->getColumnName(), 'identifier name mismatch in ' . $class->getName() . ' class');
             try {
                 DBPool::getByDao($dao);
             } catch (MissingElementException $e) {
                 // skipping
                 $out->info(', ');
                 continue;
             }
             $query = Criteria::create($dao)->setLimit(1)->add(Expression::notNull($class->getIdentifier()->getName()))->addOrder($class->getIdentifier()->getName())->toSelectQuery();
             $out->warning(' (' . $query->getFieldsCount() . '/' . $query->getTablesCount() . '/');
             $clone = clone $object;
             if (serialize($clone) == serialize($object)) {
                 $out->info('C', true);
             } else {
                 $out->error('C', true);
             }
             $out->warning('/');
             try {
                 $object = $dao->getByQuery($query);
                 $form = $object->proto()->makeForm();
                 FormUtils::object2form($object, $form);
                 if ($errors = $form->getErrors()) {
                     $formErrors[$class->getName()] = $errors;
                     $out->error('F', true);
                 } else {
                     $out->info('F', true);
                 }
             } catch (ObjectNotFoundException $e) {
                 $out->warning('F');
             }
             $out->warning('/');
             if (Criteria::create($dao)->setFetchStrategy(FetchStrategy::cascade())->toSelectQuery() == $dao->makeSelectHead()) {
                 $out->info('H', true);
             } else {
                 $out->error('H', true);
             }
             $out->warning('/');
             // cloning once again
             $clone = clone $object;
             FormUtils::object2form($object, $form);
             FormUtils::form2object($form, $object);
             if ($object != $clone) {
                 $out->error('T', true);
             } else {
                 $out->info('T', true);
             }
             $out->warning(')')->info(', ');
         }
     }
     $out->infoLine('done.');
     if ($formErrors) {
         $out->newLine()->errorLine('Errors found:')->newLine();
         foreach ($formErrors as $class => $errors) {
             $out->errorLine("\t" . $class . ':', true);
             foreach ($errors as $name => $error) {
                 $out->errorLine("\t\t" . $name . ' - ' . ($error == Form::WRONG ? ' wrong' : ' missing'));
             }
             $out->newLine();
         }
     }
     return $this;
 }
 /**
  * @return Criteria
  **/
 public function toCriteria()
 {
     $criteria = Criteria::create($this->dao)->setDistinct($this->distinct);
     $projections = array_merge($this->properties, $this->groupChain, $this->havingChain);
     foreach ($projections as $clause) {
         $criteria->addProjection($clause->bindAll($this->parameters)->toProjection());
     }
     if ($this->where) {
         if (count($this->where) == 1) {
             $clause = reset($this->where);
             $criteria->add($clause->bindAll($this->parameters)->toLogic());
         } else {
             $logic = Expression::chain();
             foreach ($this->where as $key => $clause) {
                 $expression = $clause->bindAll($this->parameters)->toLogic();
                 if ($this->whereLogic[$key] == BinaryExpression::EXPRESSION_AND) {
                     $logic->expAnd($expression);
                 } else {
                     $logic->expOr($expression);
                 }
             }
             $criteria->add($logic);
         }
     }
     foreach ($this->orderChain as $clause) {
         $criteria->addOrder($clause->bindAll($this->parameters)->toOrder());
     }
     if ($this->limit) {
         $criteria->setLimit($this->limit->evaluate($this->parameters));
     }
     if ($this->offset) {
         $criteria->setOffset($this->offset->evaluate($this->parameters));
     }
     return $criteria;
 }