5 use \pq\Query\Writer
as QueryWriter
;
12 protected $connection;
25 * @param \pq\Connection $c
28 function __construct(\pq\Connection
$c, $name, $rowset = "\\pq\\Gateway\\Rowset") {
29 $this->connection
= $c;
31 $this->rowset
= $rowset;
35 * Accessor to read-only properties
43 * @param \pq\Query\Writer $query
44 * @param array $criteria
47 protected function criteria(QueryWriter
$query, array $criteria, $join = "AND") {
50 foreach ($criteria as $lop => $rop) {
53 $query->write(")", $join, "(");
55 $this->criteria($query, $rop, is_int($lop) ?
"AND" : $lop);
58 $query->write(")", $join, "(");
63 $query->write($query->param($rop));
65 $joinable or $joinable = true;
71 * Find rows in the table
73 * @param array|string $order
78 function find(array $where = null, $order = null, $limit = 0, $offset = 0) {
79 $query = new QueryWriter("SELECT * FROM ". $this->connection
->quoteName($this->name
));
81 $this->criteria($query->write("WHERE"), $where);
84 $query->write("ORDER BY", $order);
87 $query->write("LIMIT", $limit);
89 $query->write("OFFSET", $offset);
90 return new Rowset($this, $query->exec($this->connection
));
94 * Insert a row into the table
96 * @param string $returning
99 function create(array $data, $returning = "*") {
101 $query = new QueryWriter("INSERT INTO ".$this->connection
->quoteName($this->name
)." (");
102 foreach ($data as $key => $val) {
104 $params[] = $query->param($val);
106 $query->write(") VALUES (", $params, ")");
107 if (strlen($returning)) {
108 $query->write("RETURNING", $returning);
110 $result = $query->exec($this->connection
);
111 if ($result->status
== \pq\Result
::TUPLES_OK
) {
112 $rowset = $this->rowset
;
113 return new $rowset($this, $result);
119 * Update rows in the table
120 * @param array $where
122 * @param string $returning
125 function update(array $where, array $data, $returning = "*") {
126 $query = new QueryWriter("UPDATE ".$this->connection
->quoteName($this->name
)." SET");
127 foreach ($data as $key => $val) {
128 $query->write($key, "=", $query->param($val));
130 $this->criteria($query->write("WHERE"), $where);
131 if (strlen($returning)) {
132 $query->write("RETURNING", $returning);
134 $result = $query->exec($this->connection
);
135 if ($result->status
== \pq\Result
::TUPLES_OK
) {
136 $rowset = $this->rowset
;
137 return new $rowset($this, $result);
143 * Delete rows from the table
144 * @param array $where
145 * @param string $returning
148 function delete(array $where, $returning = null) {
149 $query = new QueryWriter("DELETE FROM ".$this->connection
->quoteName($this->name
));
150 $this->criteria($query->write("WHERE"), $where);
151 if (strlen($returning)) {
152 $query->write("RETURNING", $returning);
154 $result = $query->exec($this->connection
);
155 if ($result->status
== \pq\Result
::TUPLES_OK
) {
156 $rowset = $this->rowset
;
157 return new $rowset($this, $result);