805ed79353a0926461cc86ce53030e369676f5e3
5 use \pq\Query\Writer
as QueryWriter
;
12 public static $defaultConnection;
27 protected $rowset = "\\pq\\Gateway\\Rowset";
31 * @param \pq\Connection $conn
33 function __construct($name, \pq\Connection
$conn = null) {
35 $this->conn
= $conn ?
: static::$defaultConnection ?
: new \pq\Connection
;
39 * Set the rowset prototype
40 * @param mixed $rowset
41 * @return \pq\Gateway\Table
43 function setRowsetPrototype($rowset) {
44 $this->rowset
= $rowset;
49 * @return \pq\Connection
51 function getConnection() {
64 * @param \pq\Query\Writer $query
67 protected function execute(QueryWriter
$query) {
68 $result = $query->exec($this->conn
);
70 if ($result->status
!= \pq\Result
::TUPLES_OK
) {
74 if (is_callable($this->rowset
)) {
75 return call_user_func($this->rowset
, $result);
79 $rowset = $this->rowset
;
80 return new $rowset($this, $result);
87 * Find rows in the table
89 * @param array|string $order
94 function find(array $where = null, $order = null, $limit = 0, $offset = 0) {
95 $query = new QueryWriter("SELECT * FROM ". $this->conn
->quoteName($this->name
));
97 $query->write("WHERE")->criteria($where);
100 $query->write("ORDER BY", $order);
103 $query->write("LIMIT", $limit);
105 $query->write("OFFSET", $offset);
106 return $this->execute($query);
110 * Insert a row into the table
112 * @param string $returning
115 function create(array $data = null, $returning = "*") {
116 $query = new QueryWriter("INSERT INTO ".$this->conn
->quoteName($this->name
));
120 foreach ($data as $key => $val) {
121 $query->write($first ?
"(" : ",", $key);
122 $params[] = $query->param($val);
123 $first and $first = false;
125 $query->write(") VALUES (", $params, ")");
127 $query->write("DEFAULT VALUES");
130 if (strlen($returning)) {
131 $query->write("RETURNING", $returning);
133 return $this->execute($query);
137 * Update rows in the table
138 * @param array $where
140 * @param string $returning
143 function update(array $where, array $data, $returning = "*") {
144 $query = new QueryWriter("UPDATE ".$this->conn
->quoteName($this->name
));
147 foreach ($data as $key => $val) {
148 $query->write($first ?
"SET" : ",", $key, "=", $query->param($val));
149 $first and $first = false;
151 $query->write("WHERE")->criteria($where);
152 if (strlen($returning)) {
153 $query->write("RETURNING", $returning);
155 return $this->execute($query);
159 * Delete rows from the table
160 * @param array $where
161 * @param string $returning
164 function delete(array $where, $returning = null) {
165 $query = new QueryWriter("DELETE FROM ".$this->conn
->quoteName($this->name
));
166 $query->write("WHERE")->criteria($where);
167 if (strlen($returning)) {
168 $query->write("RETURNING", $returning);
170 return $this->execute($query);