/** * _get_clause 從 $search 條件中,回傳 ORDER BY ... LIMIT ... * * @param Pix_Table_Search $search * @access protected * @return string */ protected function _get_clause($search) { $sql = ''; if ($order = $search->order()) { if (is_array($order)) { // 如果指定 before 的話,順序要調過來 if ($search->before()) { $order = Pix_Table_Search::reverseOrder($order); } $order_term = array(); foreach ($order as $column => $way) { $order_term[] = $this->column_quote($column) . ' ' . $way; } $sql .= ' ORDER BY ' . implode(', ', $order_term); } else { $sql .= ' ORDER BY ' . $order; } } $limit = $search->limit(); if (!is_null($limit)) { $offset = $search->offset(); if (!is_null($offset)) { $sql .= ' LIMIT ' . $offset . ', ' . $limit; } else { $sql .= ' LIMIT ' . $limit; } } return $sql; }
/** * fetch 取得符合 $search 條件的資料 * * @param Pix_Table $table * @param Pix_Table_Search $search * @param string|array $select_columns * @access public * @return void */ public function fetch($table, $search, $select_columns = '*') { $db = $this->_getDb(); $condictions = $search->getSearchCondictions(); if (count($condictions) == 0) { // 完全沒有條件就是 scan table $options = array(); $options['TableName'] = $table->getTableName(); // 加上指定 column if ('*' != $select_columns) { $options['AttributesToGet'] = $select_columns; } $response = $db->scan($options); } elseif (count($condictions) == 1) { // 只給一個條件的話只能是 HashKey $primary_keys = $table->getPrimaryColumns(); // 只能是 map if ('map' != $condictions[0][0]) { throw new Pix_Table_Exception("不支援的 search 條件"); } // 只能是 Primary Key 的第一個 if ($primary_keys[0] != $condictions[0][1]) { throw new Pix_Table_Exception("不支援的 search 條件"); } $options = array(); $options['TableName'] = $table->getTableName(); $options['HashKeyValue'] = array($this->_getColumnType($table, $primary_keys[0]) => $condictions[0][2]); // 加上 Limit if (!is_null($limit = $search->limit())) { $options['Limit'] = $limit; } // 加上 after or before if ($row = $search->after()) { $options['RangeKeyCondition'] = array('ComparisonOperator' => AmazonDynamoDB::CONDITION_GREATER_THAN, 'AttributeValueList' => array(array($this->_getColumnType($table, $primary_keys[1]) => $row->{$primary_keys[1]}))); } elseif ($row = $search->before()) { $options['RangeKeyCondition'] = array('ComparisonOperator' => AmazonDynamoDB::CONDITION_LESS_THAN, 'AttributeValueList' => array(array($this->_getColumnType($table, $primary_keys[1]) => $row->{$primary_keys[1]}))); $options['ScanIndexForward'] = false; } // 加上指定 column if ('*' != $select_columns) { $options['AttributesToGet'] = $select_columns; } $response = $db->query($options); } else { throw new Pix_Table_Exception("不支援的 search 條件"); } if (200 != $response->status) { throw new Pix_Table_Exception("AmazonDynamoDB: " . $get_response->body->Message); } $ret = array(); foreach ($response->body->Items[0] as $item) { $row = array(); foreach ($table->_columns as $name => $col) { if ($item->{$name}) { $row[$name] = strval($item->{$name}->S); } } $ret[] = $row; } return $ret; }