/** * Install hstore * /usr/share/postgresql/contrib # cat hstore.sql | psql -U pgsql -d onphp **/ public function testHstore() { foreach (DBTestPool::me()->getPool() as $connector => $db) { DBPool::me()->setDefault($db); $properties = array('age' => '23', 'weight' => 80, 'comment' => null); $user = TestUser::create()->setCity($moscow = TestCity::create()->setName('Moscow'))->setCredentials(Credentials::create()->setNickname('fake')->setPassword(sha1('passwd')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'))->setProperties(Hstore::make($properties)); $moscow = TestCity::dao()->add($moscow); $user = TestUser::dao()->add($user); Cache::me()->clean(); TestUser::dao()->dropIdentityMap(); $user = TestUser::dao()->getById('1'); $this->assertInstanceOf('Hstore', $user->getProperties()); $this->assertEquals($properties, $user->getProperties()->getList()); $form = TestUser::proto()->makeForm(); $form->get('properties')->setFormMapping(array(Primitive::string('age'), Primitive::integer('weight'), Primitive::string('comment'))); $form->import(array('id' => $user->getId())); $this->assertNotNull($form->getValue('id')); $object = $user; FormUtils::object2form($object, $form); $this->assertInstanceOf('Hstore', $form->getValue('properties')); $this->assertEquals(array_filter($properties), $form->getValue('properties')->getList()); $subform = $form->get('properties')->getInnerForm(); $this->assertEquals($subform->getValue('age'), '23'); $this->assertEquals($subform->getValue('weight'), 80); $this->assertNull($subform->getValue('comment')); $user = new TestUser(); FormUtils::form2object($form, $user, false); $this->assertEquals($user->getProperties()->getList(), array_filter($properties)); } }
/** * @group pi */ public function testCustomImportExport() { $dbs = DBTestPool::me()->getPool(); if (empty($dbs)) { $this->fail('For test required at least one DB in config'); } DBPool::me()->setDefault(reset($dbs)); $moscow = TestCity::create()->setCapital(true)->setName('Moscow'); $moscow->dao()->add($moscow); $stalingrad = TestCity::create()->setCapital(false)->setName('Stalingrad'); $stalingrad->dao()->add($stalingrad); $prms = array(); $prms[] = Primitive::identifier('city')->setScalar(true)->of('TestCity')->setMethodName('PrimitiveIdentifierTest::getCityByName')->setExtractMethod('PrimitiveIdentifierTest::getCityName'); $prms[] = Primitive::identifier('city')->setScalar(true)->of('TestCity')->setMethodName(array(get_class($this), 'getCityByName'))->setExtractMethod(function (TestCity $city) { return $city->getName(); }); foreach ($prms as $prm) { $prm->import(array('city' => 'Moscow')); $this->assertEquals($moscow, $prm->getValue()); $this->assertEquals('Moscow', $prm->exportValue()); $prm->importValue($stalingrad); $this->assertequals($stalingrad, $prm->getValue()); $this->assertequals('Stalingrad', $prm->exportValue()); $prm->import(array('city' => $moscow)); $this->assertEquals($moscow, $prm->getValue()); $this->assertEquals('Moscow', $prm->exportValue()); } }
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 static function swap(DAOConnected $first, DAOConnected $second, $property = 'position') { Assert::isTrue(get_class($first) === get_class($second)); $setMethod = 'set' . ucfirst($property); $getMethod = 'get' . ucfirst($property); Assert::isTrue(method_exists($first, $setMethod) && method_exists($first, $getMethod)); $dao = $first->dao(); $db = DBPool::me()->getByDao($dao); $oldPosition = $first->{$getMethod}(); $newPosition = $second->{$getMethod}(); $db->begin(); $e = null; try { $dao->save($first->{$setMethod}(self::$nullValue)); $dao->save($second->{$setMethod}($oldPosition)); $dao->save($first->{$setMethod}($newPosition)); $db->commit(); } catch (DatabaseException $e) { $db->rollback(); } $dao->uncacheByIds(array($first->getId(), $second->getId())); if ($e) { throw $e; } }
public static function eq(Query $query, $prefix = null) { if ($prefix === null) { $trace = debug_backtrace(); $prefix = basename($trace[0]['file']) . ':' . $trace[0]['line']; } error_log($prefix . ": " . $query->toDialectString(DBPool::me()->getLink()->getDialect())); }
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 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 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 function testRecursionObjects() { foreach (DBTestPool::me()->getPool() as $db) { DBPool::me()->setDefault($db); $parentProperties = Singleton::getInstance('ProtoTestParentObject')->getPropertyList(); $resultRoot = $parentProperties['root']->getFetchStrategyId() == FetchStrategy::LAZY; $childProperties = Singleton::getInstance('ProtoTestChildObject')->getPropertyList(); $resultParent = $childProperties['parent']->getFetchStrategyId() == FetchStrategy::LAZY; $selfRecursiveProperties = Singleton::getInstance('ProtoTestSelfRecursion')->getPropertyList(); $resultSelfRecursive = $selfRecursiveProperties['parent']->getFetchStrategyId() == FetchStrategy::LAZY; $this->assertTrue($resultRoot); $this->assertTrue($resultParent); $this->assertTrue($resultSelfRecursive); } }
public function testGetByEmptyId() { foreach (DBTestPool::me()->getPool() as $db) { DBPool::me()->setDefault($db); $this->getByEmptyIdTest(0); $this->getByEmptyIdTest(null); $this->getByEmptyIdTest(''); $this->getByEmptyIdTest('0'); $this->getByEmptyIdTest(false); $empty = TestLazy::create(); $this->assertNull($empty->getCity()); $this->assertNull($empty->getCityOptional()); $this->assertNull($empty->getEnum()); $this->assertNull($empty->getStaticEnum()); } }
public static function suite() { $suite = new TestSuite('onPHP-' . ONPHP_VERSION); // meta, DB and DAOs ordered tests portion if (self::$dbs) { try { /** * @todo fail - constructor with argument, but static method 'me' - without */ Singleton::getInstance('DBTestPool', self::$dbs)->connect(); } catch (Exception $e) { Singleton::dropInstance('DBTestPool'); Singleton::getInstance('DBTestPool'); } // build stuff from meta $metaDir = ONPHP_TEST_PATH . 'meta' . DIRECTORY_SEPARATOR; $path = ONPHP_META_PATH . 'bin' . DIRECTORY_SEPARATOR . 'build.php'; $_SERVER['argv'] = array(); $_SERVER['argv'][0] = $path; $_SERVER['argv'][1] = $metaDir . 'config.inc.php'; $_SERVER['argv'][2] = $metaDir . 'config.meta.xml'; $_SERVER['argv'][] = '--force'; $_SERVER['argv'][] = '--no-schema-check'; $_SERVER['argv'][] = '--drop-stale-files'; include $path; AutoloaderPool::get('onPHP')->addPaths(array(ONPHP_META_AUTO_BUSINESS_DIR, ONPHP_META_AUTO_DAO_DIR, ONPHP_META_AUTO_PROTO_DIR, ONPHP_META_DAO_DIR, ONPHP_META_BUSINESS_DIR, ONPHP_META_PROTO_DIR)); $dBCreator = DBTestCreator::create()->setSchemaPath(ONPHP_META_AUTO_DIR . 'schema.php')->setTestPool(DBTestPool::me()); $out = MetaConfiguration::me()->getOutput(); foreach (DBTestPool::me()->getPool() as $connector => $db) { DBPool::me()->setDefault($db); $out->info('Using ')->info(get_class($db), true)->infoLine(' connector.'); $dBCreator->dropDB(true); $dBCreator->createDB()->fillDB(); MetaConfiguration::me()->checkIntegrity(); $out->newLine(); $dBCreator->dropDB(); } DBPool::me()->dropDefault(); } foreach (self::$paths as $testPath) { foreach (glob($testPath . '*Test' . EXT_CLASS, GLOB_BRACE) as $file) { $suite->addTestFile($file); } } return $suite; }
public function testInnerTransaction() { foreach (DBTestPool::me()->getPool() as $connector => $db) { DBPool::me()->setDefault($db); $this->getDBCreator()->fillDB(); $moscow = TestCity::dao()->getByLogic(Expression::eq('name', 'Moscow')); $piter = TestCity::dao()->getByLogic(Expression::eq('name', 'Saint-Peterburg')); $cityNewer = function (TestCity $city) { $city->dao()->merge($city->setName('New ' . $city->getName())); }; $citiesNewer = function ($moscow, $piter) use($cityNewer, $db) { $cityNewer($moscow); InnerTransactionWrapper::create()->setDB($db)->setFunction($cityNewer)->run($piter); }; InnerTransactionWrapper::create()->setDao($moscow->dao())->setFunction($citiesNewer)->run($moscow, $piter); $this->assertNotNull(TestCity::dao()->getByLogic(Expression::eq('name', 'New Moscow'))); $this->assertNotNull(TestCity::dao()->getByLogic(Expression::eq('name', 'New Saint-Peterburg'))); } }
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); }
public function tearDown() { DBPool::me()->dropLink('badLink'); }
<?php /*************************************************************************** * Copyright (C) 2005-2007 by Sergey S. Sergeev * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation; either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ require dirname(__FILE__) . '/../../global.inc.php.tpl'; $db = DBPool::me()->getLink(); // example queries $query1 = OSQL::select()->from('message1')->get(new DBField('id', 'message1')); $query2 = OSQL::select()->from('message2')->get(new DBField('id', 'message2')); $query3 = OSQL::select()->from('message3')->get(new DBField('id', 'message3')); // example Factory $queryUnion1 = CombineQuery::union($query1, $query2); $queryUnion1 = CombineQuery::union($queryUnion1, $query3); echo "<pre>"; print_r($queryUnion1->toDialectString($db->getDialect())); 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>";
private function checkEnumerationReferentialIntegrity($enumeration, $tableName) { Assert::isTrue($enumeration instanceof Enumeration || $enumeration instanceof Enum, 'argument enumeation must be instacne of Enumeration or Enum! gived, "' . gettype($enumeration) . '"'); $updateQueries = null; $db = DBPool::me()->getLink(); $class = get_class($enumeration); $ids = array(); if ($enumeration instanceof Enumeration) { $list = $enumeration->getList(); } elseif ($enumeration instanceof Enum) { $list = ClassUtils::callStaticMethod($class . '::getList'); } foreach ($list as $enumerationObject) { $ids[$enumerationObject->getId()] = $enumerationObject->getName(); } $rows = $db->querySet(OSQL::select()->from($tableName)->multiGet('id', 'name')); echo "\n"; foreach ($rows as $row) { if (!isset($ids[$row['id']])) { echo "Class '{$class}', strange id: {$row['id']} found. \n"; } else { if ($ids[$row['id']] != $row['name']) { echo "Class '{$class}',id: {$row['id']} sync names. \n"; $updateQueries .= OSQL::update($tableName)->set('name', $ids[$row['id']])->where(Expression::eq('id', $row['id']))->toDialectString($db->getDialect()) . ";\n"; } unset($ids[$row['id']]); } } foreach ($ids as $id => $name) { echo "Class '{$class}', id: {$id} not present in database. \n"; } echo $updateQueries; return $this; }
private function checkEnumerationReferentialIntegrity(Enumeration $enumeration, $tableName) { $updateQueries = null; $db = DBPool::me()->getLink(); $class = get_class($enumeration); $ids = array(); $list = $enumeration->getObjectList(); foreach ($list as $enumerationObject) { $ids[$enumerationObject->getId()] = $enumerationObject->getName(); } $rows = $db->querySet(OSQL::select()->from($tableName)->multiGet('id', 'name')); echo "\n"; foreach ($rows as $row) { if (!isset($ids[$row['id']])) { echo "Class '{$class}', strange id: {$row['id']} found. \n"; } else { if ($ids[$row['id']] != $row['name']) { echo "Class '{$class}',id: {$row['id']} sync names. \n"; $updateQueries .= OSQL::update($tableName)->set('name', $ids[$row['id']])->where(Expression::eq('id', $row['id']))->toDialectString($db->getDialect()) . ";\n"; } unset($ids[$row['id']]); } } foreach ($ids as $id => $name) { echo "Class '{$class}', id: {$id} not present in database. \n"; } echo $updateQueries; return $this; }
public static function suite() { $suite = new TestSuite('onPHP-' . ONPHP_VERSION); foreach (self::$paths as $testPath) { foreach (glob($testPath . '*Test' . EXT_CLASS, GLOB_BRACE) as $file) { $suite->addTestFile($file); } } // meta, DB and DAOs ordered tests portion if (self::$dbs) { try { Singleton::getInstance('DBTestPool', self::$dbs)->connect(); } catch (Exception $e) { Singleton::dropInstance('DBTestPool'); Singleton::getInstance('DBTestPool'); } // build stuff from meta $metaDir = ONPHP_TEST_PATH . 'meta' . DIRECTORY_SEPARATOR; $path = ONPHP_META_PATH . 'bin' . DIRECTORY_SEPARATOR . 'build.php'; $_SERVER['argv'] = array(); $_SERVER['argv'][0] = $path; $_SERVER['argv'][1] = $metaDir . 'config.inc.php'; $_SERVER['argv'][2] = $metaDir . 'config.meta.xml'; $_SERVER['argv'][] = '--force'; $_SERVER['argv'][] = '--no-schema-check'; $_SERVER['argv'][] = '--drop-stale-files'; include $path; // provide paths to autogenerated stuff set_include_path(get_include_path() . PATH_SEPARATOR . ONPHP_META_AUTO_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_DAO_DIR . PATH_SEPARATOR . ONPHP_META_AUTO_PROTO_DIR . PATH_SEPARATOR . ONPHP_META_DAO_DIR . PATH_SEPARATOR . ONPHP_META_BUSINESS_DIR . PATH_SEPARATOR . ONPHP_META_PROTO_DIR); $daoTest = new DAOTest(); $out = MetaConfiguration::me()->getOutput(); foreach (DBTestPool::me()->getPool() as $connector => $db) { DBPool::me()->setDefault($db); $out->info('Using ')->info(get_class($db), true)->infoLine(' connector.'); try { $daoTest->drop(); } catch (DatabaseException $e) { // previous shutdown was clean } $daoTest->create()->fill(false); MetaConfiguration::me()->checkIntegrity(); $out->newLine(); $daoTest->drop(); } DBPool::me()->dropDefault(); } $suite->addTestSuite('DAOTest'); return $suite; }
public function quoteBinary($data) { return mysqli_real_escape_string(DBPool::me()->getLink()->getLink(), $data); }
public function getCustomRowList(SelectQuery $query, $expires = Cache::DO_NOT_CACHE) { if ($query->getFieldsCount() !== 1) { throw new WrongArgumentException('you should select only one row when using this method'); } if ($expires !== Cache::DO_NOT_CACHE && ($list = $this->getCachedByQuery($query))) { if ($list === Cache::NOT_FOUND) { throw new CachedObjectNotFoundException(); } return $list; } elseif ($list = DBPool::getByDao($this->dao)->queryColumn($query)) { if (Cache::DO_NOT_CACHE === $expires) { return $list; } else { return $this->cacheByQuery($query, $list, $expires); } } else { throw new ObjectNotFoundException("empty list" . (defined('__LOCAL_DEBUG__') ? " for such query - " . $query->toDialectString(DBPool::me()->getByDao($this->dao)->getDialect()) : null)); } }
public function testIpAddressProperty() { $this->create(); $city = TestCity::create()->setName('Khimki'); TestCity::dao()->add($city); $userWithIp = TestUser::create()->setCredentials(Credentials::create()->setNickName('postgreser')->setPassword(sha1('postgreser')))->setLastLogin(Timestamp::makeNow())->setRegistered(Timestamp::makeNow())->setCity($city)->setIp(IpAddress::create('127.0.0.1')); TestUser::dao()->add($userWithIp); $this->assertTrue($userWithIp->getId() >= 1); $this->assertTrue($userWithIp->getIp() instanceof IpAddress); $plainIp = DBPool::me()->getByDao(TestUser::dao())->queryColumn(OSQL::select()->get('ip')->from(TestUser::dao()->getTable())->where(Expression::eq('id', $userWithIp->getId()))); $this->assertEquals($plainIp[0], $userWithIp->getIp()->toString()); $count = Criteria::create(TestUser::dao())->add(Expression::eq('ip', IpAddress::create('127.0.0.1')))->addProjection(Projection::count('*', 'count'))->getCustom('count'); $this->assertEquals($count, 1); $this->drop(); }