/**
* A very simple query writer used by \pq\Gateway
*/
-class Writer
+class Writer implements WriterInterface
{
/**
* @var string
* @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;
}
/**
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
* @return \pq\Query\Writer
*/
function reset() {
- $this->query = "";
+ $this->query = "";
$this->params = array();
- $this->types = array();
+ $this->types = array();
return $this;
}
* @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;
}
* @return string
*/
function param($param, $type = null) {
+ if ($param instanceof ExpressibleInterface) {
+ $param = $param->get();
+ }
if ($param instanceof Expr) {
return (string) $param;
}
+
$this->params[] = $param;
- $this->types[] = $type;
+ $this->types[] = $type;
+
return "\$".count($this->params);
}
-
+
/**
- * Execute the query through \pq\Connection::execParams($this, $this->params, $this->types)
- * @param \pq\Connection $c
- * @return \pq\Result
+ * Write nested AND/OR criteria
+ * @param array $criteria
+ * @return \pq\Query\Writer
*/
- function exec(\pq\Connection $c) {
- return $c->execParams($this, $this->params, $this->types);
+ function criteria(array $criteria) {
+ if ((list($left, $right) = each($criteria))) {
+ $this->write("(");
+ if (is_array($right)) {
+ $this->criteria($right);
+ } else {
+ $this->write("(", $left, $this->param($right), ")");
+ }
+ while ((list($left, $right) = each($criteria))) {
+ $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;
}
}