retrieve sql query from cakephp finder method - php

I'm creating a behavior that log to a table the sql query executed by a particular Model in a controller. Looking for a method to return me the sql query executed for a particular finder method (like $this->MyModel->find('all') ) I found on the bakery that I can use $this->MyModel->find('sql'), but doesn't work for me. Someone knows how can I achieve this?
Thanks in advance

You can put this function in your app_model.php:
function getLastQueries()
{
$dbo = $this->getDatasource();
$logs = $dbo->_queriesLog;
return $logs;
}
And call it from any model ($this->getLastQueries()) or controller ($this->Model->getLastQueries()) to get them.

$this->Model->find('sql') is not supported natively by Cake. You have to follow the rest of the instructions in the Bakery article for installing a new DBO driver, and adding support for the find('sql') method in your AppModel. Once you do this, it should be able to get you what you're looking for.
http://bakery.cakephp.org/articles/grant_cox/2008/06/23/get-the-find-query-sql-rather-than-query-result

Related

FOSElasticaBundle: Is it possible to change "query_builder_method" in controller?

According to FOSElasticaBundle documentation it is possible to configure application to use custom query builder method like this:
user:
persistence:
elastica_to_model_transformer:
query_builder_method: createSearchQueryBuilder
But is it possible to choose QB method live, e.g. in controller action?
I'd like to be able to control what's being fetched from DB while transforming Elastica results to Doctrine entities. E.g. sometimes I'll want to do eager fetch on some relations, but can't do that by default.
Since FOSElasticaBundle documentation is not very precise, I went through its code and found it impossible to control what query builder is used on controller level.
It is possible to change whole elastica_to_model_transformer to a custom service, but still it's statically defined in configuration. Maybe with some dirty solution it would be possible going this way, but I don't think it's worth it.
I decided to just not using this feature of FOSElasticaBundle. The main problem I had was that when you use fos_elastica.index instead of fos_elastica.finder or elastica repository (in order to get plain not transformed results Elastica\Resultset), there's no findPaginated method with returns Pagerfanta paginator object, which is very helpful in my case.
Fortunately although it's not mentioned in documentation it's possible to create the Pagerfanta this way too, but a little bit more manually.
Here's a code snippet:
//generate ElaticaQuery somehow.
$browseQuery = $browseData->getBrowseQuery();
$search = $this->container->get('fos_elastica.index.indexName.typName');
//create pagerfanta's adapter manually
$adapter = new \Pagerfanta\Adapter\ElasticaAdapterElasticaAdapter($search, $browseQuery);
// now you can create the paginator too.
$pager = new Pagerfanta($adapter);
//do some paging work on it...
$pager->setMaxPerPage($browseData->getPerPage());
try {
$pager->setCurrentPage($browseData->getPage());
} catch(OutOfRangeCurrentPageException $e) {
$pager->setCurrentPage(1);
}
//and get current page results.
/** #var Result[] $elasticaResults */
$elasticaResults = $pager->getCurrentPageResults();
// we have to grab ids manyally, but it's done the same way inside FOSElasticaBundle with previous approach
$ids = array();
foreach($elasticaResults as $elasticaResult) {
$ids[] = $elasticaResult->getId();
}
//use regular Doctrine's repository to fetch Entities any way you want.
$entities = $this->getDoctrine()->getRepository(MyEntity::class)->findByIdentifiers($ids);
This actually has a few advantages. In general it gives you back control over your data and doesn't tie ElasticSearch with Doctrine. Therefore you can resign on fetching data from Doctrine if you have all needed data in ElasticSearch (if they are read only data of course). This lets you optimize your application performance but reducing amount of SQL queries.
The code above may be wrapped with some kind of service in order to prevent making mess in controllers.

ZF2 Cron Job call to Model

I am looking for help on ZF2 cron jobs. I will try to explain this the best I can. I am Fairly new with ZF2, sorry.
As a basic example, I have a cron job that runs through a list of active users. Currently the only way that works is recreating calls from my user model class, instead of reusing code already in place.
Example of work works
$this->usersTableGateway = new \Zend\Db\TableGateway\TableGateway('users', $dbAdapterTemp);
$users = $this->usersTableGateway->select(array('active' => 1));
This provides my users.
Why am I unable to use
if (!$this->usersTable) {
$sm = $this->getServiceLocator();
$this->usersTable = $sm->get('UserManagement\Model\UsersTable');
}
$this -> usersTable() -> getActiveUsers();
Is there a workaround for this for me to be able to call functions within my users model class? I am probably missing something really basic. I thought it had something to do with getServiceLocator but this statement works.
$this->getServiceLocator()->get('Config');
Thanks for the help in advance. Please let me know if you need more information.

How to connect multiple db connection in ZF2 using PDO? [duplicate]

How to configure Zend Framework 2 project to work with multiple databases?
I have followed the answer in configure multiple databases in zf2
I created my own factory as MyProject/module/MyModuleName/src/MyModuleName/Classes/MyAdapterFactory.php. Is this a correct path to create the file?
I couldn't figure out where should I call:
$adapter1=$serviceManager->get('myadapter1');
$adapter2=$serviceManager->get('myadapter2');
And also I cant ask for more clarifications since the question is 'protected' and I'm a noob.
Thank you in advance and please save my day.
First of all, a better path would be modules/$Module/src/$Module/Db/Adapter/MyAdapterFactory.php, in conjuction with the namespace $Module\Db\Adapter (of course not "$Module".. ;) )
The examples of $serviceManager->get('myadapterX') are merely examples. Anywhere you have access to the ServiceManager you can call these adapter. On the controller level you'd do it this way:
$this->getServiceLocator()->get('myadapterX');
On configuration level when defining a TableGateway or such, it'd probably look something like this:
'my\Table\Gateway' => function ($sm) {
$dbAdapter = $sm->get('myadapterX');
$gateway = new Gateway($dbAdapter);
return $gateway;
}

Phalcon pdo excpetion model first

I have problem with phalcon framework namely with models methods...
As you know models has included methods find() and findFirst()
I have generated model with phalcon-dev tools and now I am trying to do Model::find on it but I am getting an exception but dont know why...
There is some more informations (e.g stacktrace) :
http://exception.mateuszmarzecki.pl/
You can try change methods in model file
public static function find($parameters = array())
{
return self::find($parameters);
}
Does not look like your passing it the right parms.
SELECT FROM `nacionality`
Notice that your not selecting any fields from the database, and that is why your getting the Exception.
So... after some time of debugging I've found the problem...
For the next generation... if you don't want to lose a week as I did. Just read carefully your application config.
Problems occurs because I missed table and column annotations as well.
In my application config I have something like:
$metaData->setStrategy(new \Engine\Db\Model\Annotations\Metadata());
so Phalcon was looking for annotations in my model files, more info about this you can find there:
https://forum.phalconphp.com/discussion/1933/column-types-for-model-annotations
Happy New Year

Yii sql query bindings, with params, do not work properly

I'm new to Yii and everything seems good, but the problem is, when I`m using the binding params, like (DAO stile):
$command = $this->conn->createCommand($sql);
$command->bindColumn("title", "test_title");
$result = $command->query();
or (Active Record):
$row = Movies::model()->find("m_id=:m_id", array(":m_id"=>27));
or
$row = Movies::model()->findByPk(24);
I've tried everything:
1) added a config param to mysql config. in main.php - 'enableParamLogging' => true
2) changed strings from ' to "
3) added another param just in case of mysql versions - 'emulatePrepare'=>true
Nothing works for me.
I thought that the problem is in params, but bindColumn method doesn't use it, so my presumption is that some module of Yii hasn't been include in config file or something like that.
My model looks like this (created in /models dir):
class Movies extends CActiveRecord {
public static function model($className = __CLASS__) {
parent::model($className);
}
}
Just for everybody to avoid unnecessary questions: the database is configured properly in main.php conf file, there is a table movies, there is a PKs 24 and 27 also.
All native SQL works fine, except using in DAO special methods to bind some params and if in AR using findByPk or find. I hope that this is clear, guys don't bother me with obvious simple technical possibilities, that I can (as U presume) did wrong.
PS Another helpful info - when calling
$command->bindColumn("title", "test_title");
FW's throwing an Exception - CDbCommand and its behaviors do not have a method or closure named "bindColumn". So, as mentioned above, I think that Yii don't see those special methods and this is certain. How can I repair it?
Ok, why this code don't work either? There is no Exceptions, just blank page.
$sql = "SELECT title, year_made FROM movies WHERE year_made=':ym'";
$command = $this->conn->createCommand($sql);
$command->bindParam(":ym", "2012", PDO::PARAM_STR);
$result = $command->query();
The DAO binding isn't working because there is no bindColumn. You only have bindParam, that binds a variable to a column, or bindValue, that binds a value.
I don't know what's wrong with the AR query though.
Edit: Your DAO code should look like this:
$sql = "SELECT * FROM sometable WHERE title = :title";
$command = $this->conn->createCommand($sql);
$command->bindParam(":title", $tile_var);
$result = $command->query();
Have you generated movie model by Gii generator or you wrote it by yourself?
Edit:
As I know you have to add tableName
public function tableName() {
return 'movies';
}
You may have two separate issues. At least your DAO code (if that is what you actually have in your code) is binding wrong.
Binding needs to occur before the query is done (and it's done on the command object), not on the result object. See more info here: http://www.yiiframework.com/doc/guide/1.1/en/database.dao#binding-parameters
As far as your AR queries go, those could also be problematic. You can use findByAttributes instead of this line (although your line should work):
$row = Movies::model()->find("m_id=:m_id", array(":m_id"=>27));
The below should work if you have a standard id key. If you don't (and are using m_id, have you set your model's primaryKey() function up?
$row = Movies::model()->findByPk(24);
Also, you'll be getting a model object back, not a row if that changes how you are handling the results ...

Categories