Created
March 20, 2014 20:12
-
-
Save jdp/9672793 to your computer and use it in GitHub Desktop.
sketch of a DSL for generating SQL in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$emp = Relation('emp'); | |
$dept = Relation('dept'); | |
/* | |
* SELECT * | |
* FROM emp | |
* WHERE rownum <= 5; | |
*/ | |
select($emp, $emp->field('rownum')->lte(5)) | |
/* | |
* SELECT * | |
* FROM dept | |
* WHERE deptno NOT IN | |
* (SELECT deptno | |
* FROM emp) | |
*/ | |
select($dept, $dept->field('deptno')->notIn(project($emp, 'deptno'))) | |
/* | |
* SELECT * | |
* FROM emp MINUS | |
* SELECT * | |
* FROM emp | |
* WHERE rownum <= | |
* (SELECT COUNT(*) - 5 | |
* FROM emp) | |
*/ | |
difference($emp, select($emp, $emp->field('rownum')->lte(select(project($emp, Count(All())->sub(5)))))) | |
/* | |
* SELECT DISTINCT sal | |
* FROM emp a | |
* WHERE 3 >= | |
* (SELECT count(DISTINCT sal) | |
* FROM emp b | |
* WHERE a.sal <= b.sal) | |
* ORDER BY a.sal DESC; | |
*/ | |
$a = rename($emp, 'a') | |
$b = rename($emp, 'b') | |
$a_sal = $a->field('sal'); | |
$b_sal = $b->field('sal'); | |
$expr = select(project($a, Distinct($a_sal)), select(project($b, Count(Distinct($b_sal))), $a_sal->lte($b_sal))->lte(3)) | |
// Alternatively, use GTE directly | |
// $expr = select(project($a, Distinct($a_sal)), GTE(3, select(project($b, Count(Distinct($b_sal))), $a_sal->lte($b_sal)))) | |
$expr = Ordering($expr, $a_sal, Ordering::DESC) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment