[NFR] PHQL: User-Defined Functions
I think this functional (Custom functions) is very important because all RDBMS have a lot of custom functions/extensions which help decide a lot of issues and give very good performance.
Simple way
This case uses simple way to define a user query function. Function registered as pattern.
$di->modelsManager->registerSimpleQueryFunction('GET_MONTH', 'MONTH(?0)');
How to use?
$phql = "SELECT GET_MONTH(p.createdAt) month_created FROM Store\Products p WHERE p.status = :status:"
Expected SQL:
SELECT MONTH(p.createdAt) AS month_created FROM products AS p WHERE p.status = :status:
Class way
When uses class then you can parse functions with more heavy logic by your logic.
class TimestampDiffClassName
{
public $firstDatetimeExpression = null;
public $secondDatetimeExpression = null;
public $unit = null;
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$parser->match(Lexer::T_IDENTIFIER);
$lexer = $parser->getLexer();
$this->unit = $lexer->token['value'];
$parser->match(Lexer::T_COMMA);
$this->firstDatetimeExpression = $parser->getArithmetic();
$parser->match(Lexer::T_COMMA);
$this->secondDatetimeExpression = $parser->getArithmetic();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql()
{
return sprintf('TIMESTAMPDIFF(%s, %s, %s)',
$this->unit,
$this->firstDatetimeExpression->dispatch(),
$this->secondDatetimeExpression->dispatch()
);
}
}
$di->modelsManager->registerQueryFunction('GET_MYSQL_TIMESTAMPDIFF', 'TimestampDiffClassName');
Usage:
$phql = "SELECT GET_MYSQL_TIMESTAMPDIFF(DAY, p.createdAt, p.updatedAt) day_diff FROM Store\Products p WHERE p.status = :status:";
Expected SQL:
SELECT TIMESTAMPDIFF(DAY, p.createdAt, p.updatedAt) AS day_diff FROM products AS p WHERE p.status = :status:
Whete it implemented?
Doctrine: http://www.doctrine-project.org/blog/doctrine2-custom-dql-udfs.html and many examples for mysql + doctine: https://github.com/beberlei/DoctrineExtensions/tree/master/lib/DoctrineExtensions/Query/Mysql
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
+++ Good idea!
+1
+1
:+1:
@golovanov This is now a feature in phalcon 2.0.3. https://github.com/phalcon/cphalcon/commit/081331ab210e7568c3a6570bd5c6b612a4dc696a
@phalcon @andresgutierrez Please close.
@Green-Cat The implemented feature is not what he asked here
Oups, my bad. What does it do?
This: https://gist.github.com/andresgutierrez/2a729903f4b189e3ce75
Isn't that what this NFR asks for? I mean the "Simple Way" from the OP.
Yeah, it's the same, I thought he was asking the Hibernate style of doing this