Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get raw sql from Phalcon query builder

Tags:

phalcon

Is it possible to extract raw sql query from the query builder instance in Phalcon? Something like this?

$queryBuilder = new Phalcon\Mvc\Model\Query\Builder();
$queryBuilder
    ->from(…)
    ->where(…);

$rawSql = $queryBuilder->hypotheticalGetRawQueryMethod();
like image 571
Ian Bytchek Avatar asked Jan 24 '14 17:01

Ian Bytchek


People also ask

How do I get the query builder to output its raw SQL query as a string?

DB::QueryLog() works only after you execute the query using $builder->get() . If you want to get the raw query before or without executing the query, you can use the $builder->toSql() method.

What is a raw query in SQL?

Raw SQL queries are useful if the query you want can't be expressed using LINQ. Raw SQL queries are also used if using a LINQ query is resulting in an inefficient SQL query. Raw SQL queries can return regular entity types or keyless entity types that are part of your model.

What is PHQL?

Phalcon Query Language, PhalconQL or simply PHQL is a high-level, object-oriented SQL dialect that allows you to write queries using a standardized SQL-like language. PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS.


2 Answers

By error and trial the below seems to working. Would be great if someone could confirm if there's a better way.

$queryBuilder = new Builder();
$queryBuilder->from(…)->where(…);

$intermediate = $queryBuilder->getQuery()->parse();
$dialect      = DI::getDefault()->get('db')->getDialect();
$sql          = $dialect->select($intermediate);

Edit: As of 2.0.3 you can do it super simple, see comment for full details:

$modelsManager->createBuilder()
    ->from('Some\Robots')
    ->getQuery()
    ->getSql()
like image 135
Ian Bytchek Avatar answered Sep 28 '22 05:09

Ian Bytchek


you can use getRealSqlStatement() (or similar function name) on the DbAdapter. See http://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter.html

According to documentation you can get this way the resulting sql query.

Or wait, this might not work on querybuilder. Otherwise you can setup low level query logging: http://docs.phalconphp.com/en/latest/reference/models.html#logging-low-level-sql-statements

like image 36
dompie Avatar answered Sep 28 '22 05:09

dompie