Skip to content

Commit 65f3252

Browse files
committed
First MagicQuery commit with new MagicQuery class
1 parent 253bb65 commit 65f3252

27 files changed

+254
-476
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
vendor/

README.md

Lines changed: 40 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
What is QueryWritter?
2-
=====================
1+
What is Magic-query?
2+
====================
33

4-
QueryWritter is a PHP library that parses SQL queries, transforms those into an object representation, stores them in a
5-
dependency injection container, and returns them as string. It is a [Mouf plugin](http://mouf-php.com).
4+
Magic-query is a PHP library that helps you work with complex queries that require
5+
a variable number of parameters.
66

7-
Ok, but why would I use QueryWritter?
8-
-------------------------------------
7+
Why should I care?
8+
------------------
99

10-
Because it is **the most effecient way to deal with queries that can have a variable number of parameters**!
10+
Because it is **the most efficient way to deal with queries that can have a variable number of parameters**!
1111
Think about a typical datagrid with a bunch of filter (for instance a list of products filtered by name, company, price, ...).
1212
If you have the very common idea to generate the SQL query using no PHP library, your code will look like this:
1313

@@ -23,50 +23,53 @@ if (isset($params['name'])) {
2323
if (isset($params['company'])) {
2424
$sql .= "AND c.name LIKE '".addslashes($params['company'])."%'";
2525
}
26+
if (isset($params['country'])) {
27+
$sql .= "AND c.country LIKE '".addslashes($params['country'])."%'";
28+
}
2629
// And so on... for each parameter, we have a "if" statement
2730
```
2831

29-
30-
31-
Concatenating SQL queries is dangerous (especially if you forget to protect parameters).
32+
Concatenating SQL queries is **dangerous** (especially if you forget to protect parameters).
3233
You can always use parameterized SQL queries, but you will still have to concatenate the filters.
3334

3435
To avoid concatenating strings, frameworks and libraries have used different strategies. Building a full ORM (like
3536
Doctrine or Propel) is a good idea, but it makes writing complex queries even more complex. Other frameworks like
3637
Zend are building queries using function calls. These are valid strategies, but you are no more typing SQL queries
3738
directly, and let's face it, it is always useful to use a query directly.
3839

39-
This is where QueryWritter becomes helpful.
40+
This is where Magic-query becomes helpful.
4041

4142
How does it work?
4243
-----------------
43-
// TODO: schema... or even better... video!
44-
45-
###1- Write your query
46-
You start by writing your query, **in plain SQL**. No ORM, no special query language (DQL or HQL anyone?), just plain and simple SQL.
47-
This is cool because everybody knows SQL. In your query, you put absolutely all the parameters you can imagine.
48-
49-
###2- Store your query in Mouf
50-
In Mouf UI, go to **DB** > **SQL queries** > **Create SQL query**.
51-
Here, you can **copy and paste your query**. Since this is Mouf, every query is an "instance", and you have to pick
52-
a name for your query.
5344

54-
Behind the scenes, QueryWritter will parse your query and make sure every piece of the query (each table, each column, each filter...) is transformed
55-
into an object. But you really don't have to care about that right now.
45+
Easy! You write the query with all possible parameters.
5646

57-
###3- Test your query
58-
Right from Mouf UI, you can test your query! And lo and behold! Because the query was parsed, **QueryWritter will dynamically
59-
add parts of the query depending on the parameters you decide to use**.
60-
61-
###4- Use it in your code
62-
If you are not a Mouf user (if you are using Drupal, Symfony, Zend Framework...), you can directly use the query by fetching the instance from Mouf and calling the <code>toSql</code> method, passing
63-
parameters in... parameter :)
64-
65-
```
66-
$mySelect = Mouf::getMySelectStatement();
67-
$sql = $mySelect->toSql(array("status"=>1, "search"=>"hello"));
47+
```php
48+
$sql = "SELECT * FROM
49+
products p JOIN companies c
50+
ON p.company_id = c.id
51+
WHERE
52+
p.name LIKE :name
53+
AND c.name LIKE :company
54+
AND c.country LIKE :country";
55+
56+
// Get a MagicQuery object.
57+
$magicQuery = new MagicQuery();
58+
59+
// Here, we pass only the "name" parameter
60+
$generatedSql = $magicQuery->build($sql, [ "name" => "%John%" ]);
61+
// $generatedSql will not include the "c.name" filter!
62+
63+
// Here we pass no parameters
64+
$generatedSql2 = $magicQuery->build($sql, []);
65+
// The WHERE statement will be completely removed!
6866
```
6967

70-
If you are a Mouf user, you can even directly run the query using the **QueryResult** class that executes
71-
the query directly. Or even better, use the **Evolugrid** module, and display your query result in an HTML
72-
datagrid, directly!
68+
How does it work under the hood?
69+
--------------------------------
70+
71+
A lot happens to your SQL query. It is actually parsed (thanks to a modified
72+
version of the php-sql-parser library) and then changed into a tree.
73+
The magic happens on the tree where the node containing unused parameters
74+
are simply discarded. When it's done, the tree is changed back to SQL and
75+
"shazam!", your SQL query is purged of useless parameters!

composer.json

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
{
2-
"name": "mouf/database.querywriter",
3-
"description": "This package contains classes useful to generate SQL statements such as SELECT queries, etc...",
2+
"name": "mouf/magic-query",
3+
"description": "A very clever library to generate PHP prepared statement with a variable number of parameters... and much more!",
44
"keywords": ["database", "query", "mouf"],
5-
"homepage": "https://github.com/thecodingmachine/database.querywriter",
6-
"type": "mouf-library",
5+
"homepage": "http://mouf-php.com/packages/mouf/magic-query",
6+
"type": "library",
77
"license": "MIT",
88
"authors": [
99
{
@@ -14,25 +14,35 @@
1414
],
1515
"require": {
1616
"php": ">=5.3.0",
17-
"mouf/database.doctrine-dbal-wrapper": "~1.1",
1817
"mouf/utils.common.conditioninterface": "~2.0",
1918
"mouf/utils.value.value-interface": "~1.0",
2019
"mouf/utils.common.paginable-interface": "~1.0",
21-
"mouf/utils.common.sortable-interface": "~1.0",
22-
"mouf/html.widgets.evolugrid": "~3.0"
20+
"mouf/utils.common.sortable-interface": "~1.0"
21+
},
22+
"require-dev": {
23+
"phpunit/phpunit": "~4.0"
24+
},
25+
"suggest": {
26+
"doctrine/dbal": "To support more databases than just MySQL",
27+
"mouf/database.querywriter": "To get a nice user interface to edit your SQL queries",
28+
"mouf/mouf": "To get a nice user interface to edit your SQL queries"
2329
},
2430
"autoload": {
25-
"psr-0": {
26-
"Mouf\\Database\\QueryWriter": "src/",
27-
"SQLParser": "src/"
31+
"psr-4": {
32+
"Mouf\\Database\\": "src/Mouf/Database/",
33+
"SQLParser\\": "src/SQLParser/"
34+
}
35+
},
36+
"autoload-dev": {
37+
"psr-4": {
38+
"Mouf\\Database\\": "tests/Mouf/Database/"
2839
}
2940
},
3041
"extra": {
31-
"mouf": {
32-
"require-admin": [
33-
"src/QueryWriterAdmin.php"
34-
],
42+
"mouf": {
3543
"logo": "database.png"
3644
}
37-
}
45+
},
46+
"minimum-stability": "dev",
47+
"prefer-stable": true
3848
}

icons/database_go.png

-698 Bytes
Binary file not shown.

icons/database_query.png

-767 Bytes
Binary file not shown.

phpunit.xml.dist

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
3+
<phpunit backupGlobals="false"
4+
backupStaticAttributes="false"
5+
colors="true"
6+
convertErrorsToExceptions="true"
7+
convertNoticesToExceptions="true"
8+
convertWarningsToExceptions="true"
9+
processIsolation="false"
10+
stopOnFailure="false"
11+
syntaxCheck="false"
12+
bootstrap="tests/bootstrap.php"
13+
>
14+
<testsuites>
15+
<testsuite name="Mouf Test Suite">
16+
<directory>./tests/</directory>
17+
</testsuite>
18+
</testsuites>
19+
</phpunit>

src/Mouf/Database/MagicQuery.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
namespace Mouf\Database;
3+
use SQLParser\Query\StatementFactory;
4+
use SQLParser\SQLParser;
5+
use SQLParser\SqlRenderInterface;
6+
7+
/**
8+
* The class MagicQuery offers special SQL voodoo methods to automatically strip down unused parameters
9+
* from parameterized SQL statements.
10+
*/
11+
class MagicQuery
12+
{
13+
private $connection;
14+
15+
/**
16+
* @param Doctrine\DBAL\Connection $connection
17+
*/
18+
public function __construct($connection = null) {
19+
$this->connection = $connection;
20+
}
21+
22+
/**
23+
* Returns merged SQL from $sql and $parameters. Any parameters not available will be striped down
24+
* from the SQL.
25+
*
26+
* @param string $sql
27+
* @param array $parameters
28+
* @return string
29+
*/
30+
public function build($sql, array $parameters = array()) {
31+
$parser = new SQLParser();
32+
$parsed = $parser->parse($sql);
33+
34+
if ($parsed == false) {
35+
throw new MagicQueryParserException('Unable to parse query "'.$sql.'"');
36+
}
37+
38+
$select = StatementFactory::toObject($parsed);
39+
40+
$sql = $select->toSql($parameters, $this->connection, 0, SqlRenderInterface::CONDITION_GUESS);
41+
return $sql;
42+
}
43+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
namespace Mouf\Database;
3+
4+
5+
class MagicQueryParserException extends \Exception
6+
{
7+
8+
}

0 commit comments

Comments
 (0)