X-Git-Url: https://git.m6w6.name/?p=m6w6%2Fpq-gateway;a=blobdiff_plain;f=lib%2Fpq%2FQuery%2FWriter.php;h=e25a1fc7d15c71b991b05de81339771b4f531e36;hp=61589c3a1cce081006e4b23793cf4b0d9b0bdfde;hb=01bd45d05ce58796db7540d60671b8cff5d46bff;hpb=caa2499169b61c7dc6254886e73dcfc000737ed6 diff --git a/lib/pq/Query/Writer.php b/lib/pq/Query/Writer.php index 61589c3..e25a1fc 100644 --- a/lib/pq/Query/Writer.php +++ b/lib/pq/Query/Writer.php @@ -28,9 +28,9 @@ class Writer * @param array $types the types of the params */ function __construct($query = "", array $params = array(), array $types = array()) { - $this->query = $query; + $this->query = $query; $this->params = $params; - $this->types = $types; + $this->types = $types; } /** @@ -40,6 +40,16 @@ class Writer function __toString() { return $this->query; } + + /** + * Reduce arguments to write() + * @param string $q + * @param mixed $v + * @return string + */ + protected function reduce($q, $v) { + return $q . " " . (is_array($v) ? implode(", ", $v) : $v); + } /** * Get the query params @@ -62,9 +72,9 @@ class Writer * @return \pq\Query\Writer */ function reset() { - $this->query = ""; + $this->query = ""; $this->params = array(); - $this->types = array(); + $this->types = array(); return $this; } @@ -73,9 +83,7 @@ class Writer * @return \pq\Query\Writer */ function write() { - $this->query .= array_reduce(func_get_args(), function($q, $v) { - return $q . " " . (is_array($v) ? implode(", ", $v) : $v); - }); + $this->query .= array_reduce(func_get_args(), array($this, "reduce")); return $this; } @@ -89,10 +97,39 @@ class Writer if ($param instanceof Expr) { return (string) $param; } + $this->params[] = $param; - $this->types[] = $type; + $this->types[] = $type; + return "\$".count($this->params); } + + /** + * Write nested AND/OR criteria + * @param array $criteria + * @return \pq\Query\Writer + */ + function criteria(array $criteria) { + if ((list($left, $right) = each($criteria))) { + array_shift($criteria); + $this->write("("); + if (is_array($right)) { + $this->criteria($right); + } else { + $this->write("(", $left, $this->param($right), ")"); + } + foreach ($criteria as $left => $right) { + $this->write(is_int($left) && is_array($right) ? "OR" : "AND"); + if (is_array($right)) { + $this->criteria($right); + } else { + $this->write("(", $left, $this->param($right), ")"); + } + } + $this->write(")"); + } + return $this; + } /** * Execute the query through \pq\Connection::execParams($this, $this->params, $this->types) @@ -100,6 +137,8 @@ class Writer * @return \pq\Result */ function exec(\pq\Connection $c) { + fprintf(STDERR, "Q: %s\n", $this); + fprintf(STDERR, "P: %s\n", implode(", ", $this->params)); return $c->execParams($this, $this->params, $this->types); } }