Kohana 3.1 ORM DB Query - php

I have app in Kohana 3.1 and it was woring fine on PHP 5.4
But after migration this DB query is not working:
DB::select(array('MAX("art_nr")', 'art_nr'))->from('wi_artykuly')->execute()->get('art_nr');
If any function is depricated or something?
EDIT
Here's full function:
public function create(Validation $validation = NULL)
{
if(! isset($this->art_nr))
{
$intMax = DB::select(array('MAX("art_nr")', 'art_nr'))->from('wi_artykuly')->execute()->get('art_nr');
$this->art_nr = $intMax+1;
}
return parent::create($validation);
}

I've changed DB:query to PDO prepare and fetch.
If anyone wants a code please write.

Related

PHPUnit 4.8 Mock mysql database interface

Good afternoon,
I have a bunch of legacy code that uses the old mysql library (mysql_query($sql) for example) and am trying to test it with PHPUnit (4.8 is the latest that will run on the server for various reasons).
Does anyone know how to mock this database connection so that it can return predetermined results when predetermined queries are run? I have tried using getConnection() (as per the docs here: http://devdocs.io/phpunit~4/database) to no avail.
For example I have this class:
class Raffle {
...
public static function loadAll($filter=""){
//$filter = mysql_real_escape_string($filter); // protect against SQL injection
$raffles = []; // the array to return
$sql = "SELECT * FROM raffles $filter;"; // include the user filter in the query
$query = mysql_query($sql);
//echo mysql_error();
while($row = mysql_fetch_assoc($query)){
$raffles[] = Raffle::loadFromRow($row); // generate the raffe instance and add it to the array
}
return $raffles; // return the array
}
...
}
(The mysql_connect() call is done in a file called db.php which is loaded on every page that it is needed and not in the class file itself.)
Thanks in advance.
For anyone else stuck in this situation I found that building a mock for PDO that contains a fallback to the functional api allowed me to migrate the code to a Testable OO based model while still using the old mysql library under the hood.
For example:
// the basic interfaces (function names taken from PDO
interface DBConnAdapter {
public function query($sql);
}
// since PDO splits connections and statements the adapter should do the same
interface DBQueryAdapter {
public function num_rows();
public function fetch_assoc();
}
...
class DBAdapter implements DBConnAdapter {
public function query($sql){
$query = mysql_query($sql); // run the query using the legacy api
return $query ? new QueryAdapter($query) : false; // return a new query adapter or false.
}
}
...
// an example of a basic mock object to test sql queries being sent to the server (inspired by mockjax :-) )
class DBMock implements DBConnAdapter {
public $queries = []; // array of queries already executed
public $results = []; // array of precomputed results. (key is SQL and value is the returned result (nested array))
public function query($sql) {
if($this->results[$sql]){
$query = new DBQueryMock($sql, $this->results[$sql]); // a mock of PDOStatement that takes the sql it ran and the results to return
$queries[] = $query; // add the query to the array
return $query; // return the query
}
return false; // we do not know the statement so lets pretend it failed
}
// add a result to the list
public function add_single_result($sql, $result){
// check if the index was set, if not make an array there
if(!isset($this->results[$sql])) $this->results[$sql] = [];
// add the result to the end of the array
$this->results[$sql][] = $result;
// return its index
return count($this->results[$sql]) - 1;
}
}
Admittedly this is not an ideal solution as it requires modifying the code to support the adapter objects and removes some functionality (such as mysql_real_escape_string), but it worked....
If you have a better solution please share :-) Thanks!

Elasticsearch doesn't index something in a php application

I've a problem using elasticsearch in a php application. The application is built with zend and uses a .env to hold the following configuration:
ELASTICSEARCH_MAX_DOCUMENTS=250
ELASTICSEARCH_MAX_BULK_SIZE=3M
ELASTICSEARCH_HOST=my-elasticsearch.intern.rz
ELASTICSEARCH_PORT=80
ELASTICSEARCH_USER=user
ELASTICSEARCH_PASSWORD=pw
The call to index the new files is part of a import service class and looks like this: 
public function flush(FlushInterface $flushInterface = null) {
$bulk = $this->getSearchDocumentBulk();
if (!empty($bulk->getActions())) {
$response = $bulk->send();
$this->resetSearchDocumentBulk();
if (0 === $response->count()) {
$data = $response->getData();
throw new BulkException(isset($data['message']) ? strip_tags($data['message']) : '');
}
}
$this->documentCache = [];
if ($flushInterface instanceof FlushInterface) {
$flushInterface->flush();
}
return $this;
}
protected function getSearchDocumentBulk() {
if (!($this->searchDocumentBulk instanceof Bulk)) {
$this->searchDocumentBulk = new Bulk($this->getSearchClient()->getClient());
$this->searchDocumentBulk->setIndex(self::INDEX);
}
return $this->searchDocumentBulk;
}
I know it's only a short snippet but it's quite difficult to pull out the relevant code. So please let me know if I have to post some more methods. 
The application is started by a symfony command and I'm able to curl to elasticsearch (version 5.1) without any errors.
My problem is that no document is indexed. If I check elasticsearch-head I see that there was no data transfer anymore. 
But there's also no error, no exception or something like that. The process is completed with 100% (100,000 of 100,000 files imported). So I've no idea what happens or how to find out the bug.

Context Help for EWZ_SEARCH bundle Symfony Jobeet 2.3 to 2.8 upgrade

A while back I completed this series of tutorials and converted the jobeet from symfony 1 to symfony 2.
http://intelligentbee.com/blog/2013/08/07/symfony2-jobeet-day-1-starting-up-the-project/
I am now trying to upgrade it to 2.8
Everything works except for the lucene search.
I am attempting to implement EWZSearchBundle as a solution.
config.yml
ewz_search:
indices:
indexJob:
path: %kernel.root_dir%/EwzLuceneIndices/%kernel.environment%/myIndexJob
analyzer: Zend\Search\Lucene\Analysis\Analyzer\Common\Utf8\CaseInsensitive
# deprecated
analyzer: Zend\Search\Lucene\Analysis\Analyzer\Common\TextNum\CaseInsensitive
path: %kernel.root_dir%/cache/%kernel.environment%/lucene/index
search action in controller
public function searchAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $this->getRequest()->get('query');
if(!$query) {
if(!$request->isXmlHttpRequest()) {
return $this->redirect($this->generateUrl('ibw_job'));
} else {
return new Response('No results.');
}
}
$jobs = $em->getRepository('AcmeJobeetBundle:Job')->getForLuceneQuery($query);
if($request->isXmlHttpRequest()) {
if('*' == $query || !$jobs || $query == '') {
return new Response('No results.');
}
return $this->render('AcmeJobeetBundle:Job:list.html.twig', array('jobs' => $jobs));
}
}
function in entity repository
static public function getLuceneIndex()
{
$luceneSearchForFooIndex = $this->get('ewz_search.lucene.manager')->getIndex('indexJob');
return $luceneSearchForFooIndex ;
}
The error that I get in app_dev.php
Error: Using $this when not in object context
500 Internal Server Error - FatalErrorException
I know that "$this" is out of context and that is why I am getting the error but I have absolutely no id on how to fix it.
Any help/links to docs/ideas for a solution is greatly appreciated.
Thanks in advance.
Composer Saved the Day
"sonata-project/doctrine-orm-admin-bundle": "2.3.*",
"zf1/zend-search-lucene": "~1.12"
After a day or so of trying to make the other search functions work. I was able to the the zend framework work by adding the specific framework component through composer.
It now all works in 2.8.

Empty resultset when using Phalcon\Mvc\Model\Query\Builder

Good day, eveyrone!
I'm trying to fetch data from Oracle database via Phalcon\Mvc\Model\Query\Builder, but resultset allways empty.
// APPLICATION_ROOT/app/models/Package.php
<?php
use Phalcon\MVC\Model;
class Package extends Model
{
public function getSource()
{
return 'RADIO_PACKAGE';
}
}
The controller class:
public function indexAction()
{
$packages = Package::find();
var_dump($packages->toArray()); // null
$query = $this->modelsManager->createBuilder()->from('Package')->getQuery();
var_dump($query->execute()->toArray()); // null
// But the direct access to database returns rows
$PDO = $this->getDI()->get('db')->getInternalHandler();
var_dump($PDO->query('SELECT * FROM RADIO_PACKAGE')->fetchAll()); // returns 23 rows
}
Does anyone know what the problem is?
I tried Phalcon 1.1.0 and 1.2.0.
PDO_OCI driver has been installed from PHP 5.4.16 source.
PHP version is 5.4.11.
Oracle version is "Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit"
Fixed in 1.2.0 branch, discussion about the problem: http://forum.phalconphp.com/discussion/464/empty-resultset-when-using-phalcon-mvc-model-query-builder
Do you have in public/index.php a setup for Loader ?
Something like
$loader = new \Phalcon\Loader();
$loader->registerDirs(
array(
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->pluginsDir
)
)->register();

access to extended class in symfony 1.4

so... I basically follow the practical symfony book, and encountered following problem.
I have properly (i guess) installed sfGuardPlugin, built the models, sqls etc, created user and tried to log in with the username and password entered.
i got the following error message:
Fatal error: Call to undefined method sfGuardUserPeer::retrieveByUsername() in /***/plugins/sfGuardPlugin/lib/validator/sfGuardValidatorUser.class.php on line 53
it looks quite weird to me, because the problematic part of sfGuardValidatorUser class looks like this:
// user exists?
if ($user = sfGuardUserPeer::retrieveByUsername($username))
{
// password is ok?
if ($user->getIsActive() && $user->checkPassword($password))
{
return array_merge($values, array('user' => $user));
}
}
while sfGuardUserPeer has just the empty class:
class sfGuardUserPeer extends PluginsfGuardUserPeer
{
}
that extends PluginsfGuardUserPeer, so i checked it out too:
class PluginsfGuardUserPeer extends BasesfGuardUserPeer
{
public static function retrieveByUsername($username, $isActive = true)
{
$c = new Criteria();
$c->add(self::USERNAME, $username);
$c->add(self::IS_ACTIVE, $isActive);
return self::doSelectOne($c);
}
}
that's the missing function!
so - what is wrong? why doesn't it work?
i have already tried all the solutions found with google, but none of them work :/
finally found it!
the
symfony propel:build-model
task unnecessarily generated the sfGuard classes in the model directory from the schema file located in the plugin directory, while all the classes were already present in the sfGuard folder.
geez, that shouldn't happen in such a well-developed framework and plugin...
Simply put that
public static function retrieveByUsername($username, $isActive = true)
{
$c = new Criteria();
$c->add(self::USERNAME, $username);
$c->add(self::IS_ACTIVE, $isActive);
return self::doSelectOne($c);
}
Code into your sfGuardUserPeer class, this will sort out the issue, I did the same when I got this error, it worked for me..

Categories