function save() { Assert::isFalse($this->isReadonly(), 'cannot save readonly collections'); $getter = $this->referentialProperty->getGetter(); $setter = $this->referentialProperty->getSetter(); if ($this->referentialProperty->getMultiplicity()->isNullable()) { foreach ($this->getLostTracked() as $object) { $object->{$setter}(null); $object->save(); } } else { if (sizeof($this->getLostTracked())) { $query = new EntityQuery($this->getChildren()); $this->fillQuery($query); $query->andWhere(Expression::in($this->getChildren()->getLogicalSchema()->getIdentifier(), $this->getLostTracked())); $query->delete(); } } foreach ($this->getList() as $object) { // avoid useless mutation if ($object->{$getter}() !== $this->getParentObject()) { $object->{$setter}($this->getParentObject()); } $object->save(); } }
public function getListByIds(array $ids) { try { return $this->getListByLogic(Expression::in(new DBField($this->dao->getIdName(), $this->dao->getTable()), $ids)); } catch (ObjectNotFoundException $e) { return array(); } }
public function testDialectStringObjects() { $criteria = Criteria::create(TestUser::dao())->setProjection(Projection::property('id'))->add(Expression::gt('registered', Date::create('2011-01-01'))); $this->assertEquals($criteria->toDialectString(ImaginaryDialect::me()), 'SELECT test_user.id FROM test_user WHERE (test_user.registered > 2011-01-01)'); $criteria = Criteria::create(TestUserWithContactExtended::dao())->setProjection(Projection::property('contactExt.city.id', 'cityId'))->add(Expression::eq('contactExt.city', TestCity::create()->setId(22))); $this->assertEquals($criteria->toDialectString(ImaginaryDialect::me()), 'SELECT test_user_with_contact_extended.city_id AS cityId FROM test_user_with_contact_extended WHERE (test_user_with_contact_extended.city_id = 22)'); $cityList = array(TestCity::create()->setId(3), TestCity::create()->setId(44)); $criteria = Criteria::create(TestUser::dao())->setProjection(Projection::property('id'))->add(Expression::in('city', $cityList)); $this->assertEquals($criteria->toDialectString(ImaginaryDialect::me()), 'SELECT test_user.id FROM test_user WHERE (test_user.city_id IN (3, 44))'); }
/** * @return InExpression **/ public function evaluate($values) { switch ($this->logic) { case InExpression::IN: return Expression::in($this->getParameter(0)->evaluate($values), $this->getParameter(1)->evaluate($values)); case InExpression::NOT_IN: return Expression::notIn($this->getParameter(0)->evaluate($values), $this->getParameter(1)->evaluate($values)); default: throw new UnsupportedMethodException("'{$this->logic}' doesn't supported yet"); } }
public function testBind() { $user = TestUser::create()->setId(1); $bindingsList = array(array(1 => 1.123), array(1 => -1), array(1 => 'test'), array(1 => $user), array(1 => SQLFunction::create('rand'))); foreach ($bindingsList as $bindings) { $value = $bindings[1]; if ($value instanceof Identifiable) { $value = $value->getId(); } $this->assertCriteria('$1 from TestUser', Criteria::create(TestUser::dao())->setProjection(Projection::property($value)), $bindings)->assertCriteria('count($1) from TestUser', Criteria::create(TestUser::dao())->setProjection(Projection::count($value)), $bindings)->assertCriteria('from TestUser where id = $1', Criteria::create(TestUser::dao())->add(Expression::eq('id', $value)), $bindings); // in 'in' expression if (is_scalar($value)) { $this->assertCriteria('from TestUser where id in (1, $1)', Criteria::create(TestUser::dao())->add(Expression::in('id', array(1, $value))), $bindings); } $this->assertCriteria('from TestUser order by $1', Criteria::create(TestUser::dao())->addOrder(OrderBy::create($value)), $bindings)->assertCriteria('from TestUser having id = $1', Criteria::create(TestUser::dao())->setProjection(Projection::having(Expression::eq('id', $value))), $bindings)->assertCriteria('from TestUser group by id = $1', Criteria::create(TestUser::dao())->setProjection(Projection::group(Expression::eq('id', $value))), $bindings); if (is_integer($value) && $value >= 0) { $this->assertCriteria('from TestUser limit $1', Criteria::create(TestUser::dao())->setLimit($value), $bindings)->assertCriteria('from TestUser offset $1', Criteria::create(TestUser::dao())->setOffset($value), $bindings); } } }
/** * @return OneToManyLinkedFull **/ public function sync($insert, $update = array(), $delete) { $uc = $this->container; $dao = $uc->getDao(); if ($delete) { DBPool::getByDao($dao)->queryNull(OSQL::delete()->from($dao->getTable())->where(Expression::eq(new DBField($uc->getParentIdField()), $uc->getParentObject()->getId()))->andWhere(Expression::in($uc->getChildIdField(), ArrayUtils::getIdsArray($delete)))); $dao->uncacheByIds(ArrayUtils::getIdsArray($delete)); } if ($insert) { for ($i = 0, $size = count($insert); $i < $size; ++$i) { $dao->add($insert[$i]); } } if ($update) { for ($i = 0, $size = count($update); $i < $size; ++$i) { $dao->save($update[$i]); } } return $this; }
public function testChainForm() { $form = Form::create()->add(Primitive::string('a'))->add(Primitive::string('b'))->add(Primitive::integer('c'))->add(Primitive::integer('d'))->add(Primitive::boolean('e'))->add(Primitive::string('f'))->import(array('a' => 'true', 'c' => 123, 'd' => 123)); $andChain = Expression::chain()->expAnd(Expression::expOr(new FormField('a'), Expression::notNull(new FormField('b'))))->expAnd(Expression::eq(new FormField('c'), new FormField('d')))->expAnd(Expression::isFalse(new FormField('e'))); $this->assertTrue($andChain->toBoolean($form)); $form->importMore(array('e' => 'on')); $this->assertFalse($andChain->toBoolean($form)); $orChain = Expression::chain()->expOr(Expression::eq(new FormField('a'), new FormField('b')))->expOr(Expression::expOr(new FormField('e'), Expression::gt(new FormField('c'), new FormField('d'))))->expOr(Expression::in(new FormField('f'), array('qwer', 'asdf', 'zxcv'))); $form->import(array()); $this->assertFalse($orChain->toBoolean($form)); $form->import(array('e' => '1')); $this->assertTrue($orChain->toBoolean($form)); $form->import(array('a' => 'asdf', 'b' => 'qwerq', 'c' => '13', 'd' => '1313', 'f' => 'iukj')); $this->assertFalse($orChain->toBoolean($form)); $form->import(array('c' => '13', 'd' => '12')); $this->assertTrue($orChain->toBoolean($form)); $form->import(array('f' => 'asdfwer')); $this->assertFalse($orChain->toBoolean($form)); $form->import(array('f' => 'qwer')); $this->assertTrue($orChain->toBoolean($form)); }
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); }
function save() { Assert::isFalse($this->isReadonly(), 'cannot save readonly collections'); // delete relations if (sizeof($this->getLostTracked())) { EntityQuery::create($this->mtm->getProxy())->where(Expression::in($this->mtm->getEncapsulantProxyProperty(), $this->getLostTracked()))->delete(); } // create new relations $containerSetter = $this->mtm->getContainerProxyProperty()->getSetter(); $encapsulantSetter = $this->mtm->getEncapsulantProxyProperty()->getSetter(); foreach ($this->getUntracked() as $object) { $proxy = $this->mtm->getProxy()->getLogicalSchema()->getNewEntity(); $proxy->{$containerSetter}($this->getParentObject()); $proxy->{$encapsulantSetter}($object); $insertQuery = new InsertQuery($this->mtm->getProxy()->getPhysicalSchema()->getTable()); $insertQuery->setValues($this->mtm->getProxy()->getMap()->disassemble($proxy)); try { $this->mtm->getProxy()->getDao()->executeQuery($insertQuery); } catch (UniqueViolationException $e) { } } }
public function testProperties() { $query = OQL::select('from TestUser'); $criteria = Criteria::create(TestUser::dao()); $this->assertCriteria($query, $criteria); $this->assertCriteria($query->addProperties(OQL::properties('id, count(id) as count')), $criteria->addProjection(Projection::property('id'))->addProjection(Projection::count('id', 'count'))); $this->assertCriteria($query->addProperties(OQL::properties('city.id')), $criteria->addProjection(Projection::property('city.id'))); $properties = OQL::properties('id'); $this->assertFalse($properties->isDistinct()); $this->assertEquals($properties->toProjection(), Projection::chain()->add(Projection::property('id'))); $properties = OQL::properties('id, distinct name'); $this->assertTrue($properties->isDistinct()); $this->assertEquals($properties->toProjection(), Projection::chain()->add(Projection::property('id'))->add(Projection::property('name'))); $properties = OQL::properties('$1')->bind(1, 'foo'); $this->assertEquals($properties->toProjection(), Projection::chain()->add(Projection::property('foo'))); $properties->bind(1, 'bar'); $this->assertEquals($properties->toProjection(), Projection::chain()->add(Projection::property('bar'))); $this->assertCriteria(OQL::select('from TestUser')->addProperties($properties->bind(1, 'foo'))->bind(1, 'bar'), Criteria::create(TestUser::dao())->addProjection(Projection::property('bar'))); $properties = OQL::properties('id, count(distinct city.id + $0), avg(some) as someAverage, ' . 'name not like "%Ы%", foo and (bar or baz), $1 / $2, ' . 'a in ($3, $0)')->bindAll(array(1, 2, 'num', 'test')); $this->assertFalse($properties->isDistinct()); $this->assertEquals($properties->toProjection(), Projection::chain()->add(Projection::property('id'))->add(Projection::distinctCount(Expression::add('city.id', 1)))->add(Projection::avg('some', 'someAverage'))->add(Projection::property(Expression::notLike('name', '%Ы%')))->add(Projection::property(Expression::expAnd('foo', Expression::expOr('bar', 'baz'))))->add(Projection::property(Expression::div(2, 'num')))->add(Projection::property(Expression::in('a', array('test', 1))))); }
/** * @return UpdateQuery **/ private function makeMassUpdateQuery($ids) { $uc = $this->container; return OSQL::update($uc->getDao()->getTable())->set($uc->getParentIdField(), null)->where(Expression::in($uc->getChildIdField(), $ids)); }
/** * only unlinking, we don't want to drop original object * * @return DeleteQuery **/ protected function makeDeleteQuery($delete) { $uc = $this->container; return OSQL::delete()->from($uc->getHelperTable())->where(Expression::eq(new DBField($uc->getParentIdField()), new DBValue($uc->getParentObject()->getId())))->andWhere(Expression::in($uc->getChildIdField(), $delete)); }
echo "</pre>"; // example Chain $queryUnion2 = CombineQuery::chain(); $queryUnion2->union($query1); $queryUnion2->intersect($query2); $queryUnion2->except($query3); echo "<pre>"; print_r($queryUnion2->toDialectString($db->getDialect())); echo "</pre>"; // example Block $queryUnion3 = CombineQuery::exceptBlock($query1, $query2, $query3); echo "<pre>"; print_r($queryUnion3->toDialectString($db->getDialect())); echo "</pre>"; // example composite $queryUnion4 = CombineQuery::union($query1, $queryUnion3); echo "<pre>"; print_r($queryUnion4->toDialectString($db->getDialect())); echo "</pre>"; $query5 = OSQL::select()->get(new DBField('id', 'foo'))->from($queryUnion3, "foo"); echo "<pre>"; print_r($query5->toDialectString($db->getDialect())); echo "</pre>"; $query6 = OSQL::select()->get(new DBField('id', 'messages'))->from('messages')->where(Expression::in('id', $queryUnion3)); echo "<pre>"; print_r($query6->toDialectString($db->getDialect())); echo "</pre>"; $query7 = OSQL::select()->get(new DBField('id', 'messages'))->from(CombineQuery::union($query1, $query2), 'foo'); echo "<pre>"; print_r($query7->toDialectString($db->getDialect())); echo "</pre>";
public function dropByIds(array $ids) { $result = DBPool::getByDao($this->dao)->queryCount(OSQL::delete()->from($this->dao->getTable())->where(Expression::in($this->dao->getIdName(), $ids))); $this->dao->uncacheByIds($ids); return $result; }
function getByIds(array $ids) { $objects = array(); $toFetchIds = array(); foreach ($ids as $id) { $objects[(string) $id] = $entity = $this->getLazyEntityById($id); if (!$entity->isFetched()) { $toFetchIds[] = $id; } } if (!empty($toFetchIds)) { $query = EntityQuery::create($this->entity)->where(Expression::in($this->identifier, $toFetchIds)); $fetched = $this->getList($query); if (sizeof($fetched) < sizeof($toFetchIds)) { // crop missing objects foreach ($toFetchIds as $id) { foreach ($fetched as $object) { if ($object->_getId() == $id) { // found and fetched continue 2; } } unset($objects[$id]); $this->identityMap->drop($id); } } } return array_values($objects); }
public function getListByIds(array $ids, $expires = Cache::EXPIRES_MEDIUM) { $list = array(); // dupes, if any, will be resolved later @ ArrayUtils::regularizeList $ids = array_unique($ids); if ($expires !== Cache::DO_NOT_CACHE) { $toFetch = array(); $prefixed = array(); foreach ($ids as $id) { $prefixed[$id] = $this->makeIdKey($id); } if ($cachedList = Cache::me()->mark($this->className)->getList($prefixed)) { $proto = $this->dao->getProtoClass(); $proto->beginPrefetch(); foreach ($cachedList as $cached) { if ($cached && $cached !== Cache::NOT_FOUND) { $list[] = $this->dao->completeObject($cached); unset($prefixed[$cached->getId()]); } } $proto->endPrefetch($list); } $toFetch += array_keys($prefixed); if ($toFetch) { try { $list = array_merge($list, $this->getListByLogic(Expression::in(new DBField($this->dao->getIdName(), $this->dao->getTable()), $toFetch), Cache::DO_NOT_CACHE)); } catch (ObjectNotFoundException $e) { // nothing to fetch } } } elseif (count($ids)) { try { $list = $this->getListByLogic(Expression::in(new DBField($this->dao->getIdName(), $this->dao->getTable()), $ids), Cache::DO_NOT_CACHE); } catch (ObjectNotFoundException $e) { /*_*/ } } return $list; }
public function fetchCollections(array $collections, array $list) { Assert::isNotEmptyArray($list); $ids = ArrayUtils::getIdsArray($list); $mainId = DBField::create($this->getIdName(), $this->getTable()); foreach ($collections as $path => $info) { $lazy = $info['lazy']; $query = OSQL::select()->get($mainId)->from($this->getTable()); $proto = reset($list)->proto(); $this->processPath($proto, $path, $query, $this->getTable()); if ($criteria = $info['criteria']) { $query = $criteria->setDao($this)->fillSelectQuery($query); } $query->andWhere(Expression::in($mainId, $ids)); $propertyPath = $info['propertyPath']; $property = $propertyPath->getFinalProperty(); $proto = $propertyPath->getFinalProto(); $dao = $propertyPath->getFinalDao(); $selfName = $this->getObjectName(); $self = new $selfName(); $getter = 'get' . ucfirst($property->getName()); Assert::isTrue($property->getRelationId() == MetaRelation::ONE_TO_MANY || $property->getRelationId() == MetaRelation::MANY_TO_MANY); $table = $dao->getJoinName($property->getColumnName()); $id = $this->getIdName(); $collection = array(); if ($lazy) { if ($property->getRelationId() == MetaRelation::MANY_TO_MANY) { $childId = $self->{$getter}()->getChildIdField(); } else { $childId = $dao->getIdName(); } $alias = 'cid'; // childId, collectionId, whatever $field = DBField::create($childId, $self->{$getter}()->getHelperTable()); $query->get($field, $alias); if (!$property->isRequired()) { $query->andWhere(Expression::notNull($field)); } try { $rows = $dao->getCustomList($query); foreach ($rows as $row) { if (!empty($row[$alias])) { $collection[$row[$id]][] = $row[$alias]; } } } catch (ObjectNotFoundException $e) { /*_*/ } } else { $prefix = $table . '_'; foreach ($dao->getFields() as $field) { $query->get(DBField::create($field, $table), $prefix . $field); } if (!$property->isRequired()) { $query->andWhere(Expression::notNull(DBField::create($dao->getIdName(), $table))); } try { // otherwise we don't know which object // belongs to which collection $rows = $dao->getCustomList($query); foreach ($rows as $row) { $collection[$row[$id]][] = $dao->makeObject($row, $prefix); } } catch (ObjectNotFoundException $e) { /*_*/ } } $suffix = ucfirst($property->getName()); $fillMethod = 'fill' . $suffix; $getMethod = 'get' . $suffix; Assert::isTrue(method_exists(reset($list), $fillMethod), 'can not find filler'); Assert::isTrue(method_exists(reset($list), $getMethod), 'can not find getter'); foreach ($list as $object) { if (!empty($collection[$object->getId()])) { $object->{$fillMethod}($collection[$object->getId()], $lazy); } else { $object->{$getMethod}()->mergeList(array()); } } } return $list; }