public function afterSave() { $query = Query::build()->from('itemTags')->where('item', '=', 'item', true)->bind('item', $this->id)->delete(); foreach ($this->tagIds as $tag) { $query = Query::build()->from('itemTags')->set('item', 'item', true)->set('tag', 'tag', true)->bind('item', $this->id)->bind('tag', $tag)->insert(); } }
function getQuery(RelationshipLoader $loader) { //TODO: IF JOINT TABLE DOESNT EXIST, THEN CREATE IT if ($loader instanceof DeferredLoader) { $joinTable = $this->getJoinTable(); $query = Query::build(Query::SQL, $loader->Relation->Entity)->select()->from($loader->Relation->Entity)->join($joinTable, $loader->Relation->Association); if ($loader->Relation->isLocalReference()) { foreach ($this->_joinAttributes as $joinAttribute) { $query->where($joinTable->Attributes[$joinAttribute->Name], $loader->Source->Data[$joinAttribute->ReferencedAttribute]); } } else { foreach ($this->_inverseJoinAttributes as $joinAttribute) { //echo $joinAttribute->Name; //echo "\n"; //var_dump( $joinTable ); //echo $joinTable->Attributes[$joinAttribute->Name]->InnerName; //$query->where( $joinTable->Attributes[$joinAttribute->Name], $loader->Source->Data[ $joinAttribute->ReferencedAttribute ]); } } //->where( $joinTable->Attributes[$this->_joinColumns->Name]->InnerName, $loader->Source->Data[$loader->Relation->Association->PrimaryKey->OuterName]); //echo (string)$query; } if (isset($query)) { return $query; } return null; }
/** * @mcms_message ru.molinos.cms.cron */ public static function taskRun(Context $ctx) { $types = $ctx->config->get('modules/subscription/types', array()); $xsl = $ctx->config->get('modules/subscription/stylesheet', os::path('lib', 'modules', 'subscription', 'message.xsl')); $sub = $ctx->config->get('modules/subscription/subject', 'Новости сайта %host'); if (empty($types)) { return; } $ctx->db->beginTransaction(); $users = Node::find(array('class' => 'subscription', 'deleted' => 0, 'published' => 1, '#sort' => 'name'), $ctx->db); // Обрабатываем активных пользователей. foreach ($users as $user) { $olast = $last = intval($user->last); if ($sections = (array) $user->tags) { list($sql, $params) = Query::build(array('class' => $types, 'tags' => $sections, 'published' => 1, 'deleted' => 0, 'id' => array('>' . ($olast + 1))))->getSelect(array('id', 'xml')); $nodes = $ctx->db->getResultsKV('id', 'xml', $sql, $params); // Отправляем документы. foreach ($nodes as $nid => $node) { $xml = html::em('message', array('mode' => 'regular', 'unsubscribe' => 'subscription.rpc?action=remove&name=' . urlencode($user->name) . '&id=' . $user->id, 'base' => $ctx->url()->getBase($ctx), 'host' => MCMS_HOST_NAME), $node); $body = xslt::transform($xml, $xsl, null); $subject = t($sub, array('%host' => $ctx->url()->host())); BebopMimeMail::send(null, $user->name, $subject, $body); $last = max($last, $nid); } // Запоминаем последнее отправленное сообщение. $user->last = $last; $user->save(); } } $ctx->db->commit(); }
/** * Build the query to a string * * @return string */ public function build() { // Some task's like clearing the query parameters // are handeld by the parent build function. parent::build(); // Lets run the Builder by passing the current query object return $this->handler->builder()->compile_update($this); }
public function test() { $pdo = new DummyPDO(); $orig = "string: :a@string\nint :b@int\nstring: :a@string\nint :b@int"; $stmt = Query::build($pdo, $orig, [':a' => 'AAAA', ':b' => '2222']); $expected = 'string: @AAAA@ int 2222 string: @AAAA@ int 2222'; $this->assertSame($expected, $stmt->queryString); }
/** * Добавляет в XML нод информацию о разделах. * @mcms_message ru.molinos.cms.node.xml */ public static function on_node_xml(Node $node) { list($sql, $params) = Query::build(array('class' => 'tag', 'deleted' => 0, 'tagged' => $node->id))->getSelect(array('id', 'published', 'name', 'class')); $data = $node->getDB()->getResults($sql, $params); $result = ''; foreach ($data as $row) { $result .= html::em('node', $row); } return html::wrap('taxonomy', $result); }
/** * Queries the google analytics service. * * @param \Widop\GoogleAnalytics\Query $query The google analytics query. * * @throws \Widop\GoogleAnalytics\GoogleAnalyticsException If an error occured when querying the google analytics service. * * @return \Widop\GoogleAnalytics\Response The google analytics response. */ public function query(Query $query) { $accessToken = $this->getClient()->getAccessToken(); $uri = $query->build($accessToken); $content = $this->getClient()->getHttpAdapter()->getContent($uri); $json = json_decode($content, true); if (!is_array($json) || isset($json['error'])) { throw GoogleAnalyticsException::invalidQuery(isset($json['error']) ? $json['error']['message'] : 'Invalid json'); } return new Response($json); }
/** * Returns the values + original path as a complete URI * * @param $newvalues * @param $queryvalues * @param $removevalues * @return unknown_type */ function build($newvalues=null, $removevalues=null, $queryvalues=null, $removequeryvalues=null) { $segs=$this->segments; // remove any values or key=>value pairs first if ($removevalues!=null) foreach($removevalues as $key=>$value) { $this->remove_value($key, $value); } if ($newvalues!=null) foreach($newvalues as $key=>$value) { if (is_array($value)) foreach ($value as $val) $values[] = strtolower($val); else $values[] = strtolower($value); $added=false; foreach($values as $val) { if (is_numeric($key) && count($segs)>=$key) { // allows segment to be added at a specific index (or in front of the current value) //$segs[]=$value; array_splice($segs,$key,0,$val); $added=true; } else for($i=0; $i<count($segs); $i++) if ($segs[$i]==$key) { array_splice($segs,$i+1,1,$val); $added=true; break; } if (!$added) array_splice($segs,count($segs),0,array($key,$val)); } } for($i=0; $i<count($segs); $i++) $segs[$i] = rawurlencode($segs[$i]); return rtrim($this->root."/".implode('/',$segs).$this->query->build($queryvalues,$removequeryvalues), '/'); }
/** * @param Query $query * @return Response * @throws XitiException */ public function query(Query $query, $clientRequestId = null) { $headers = $this->getClient()->getHeaders($clientRequestId); $uri = $query->build(); $content = $this->getClient()->getHttpAdapter()->getContent($uri, $headers); if (is_object($content)) { $content = $content->getBody(); } $json = json_decode($content, true); if (!is_array($json) || isset($json['ErrorCode'])) { throw XitiException::invalidQuery(isset($json['ErrorCode']) ? $json['ErrorMessage'] : 'Invalid json'); } return new Response($json); }
public static function on_find_xml(Context $ctx) { if (null === ($search = $ctx->get('search'))) { throw new BadRequestException(t('Не указана подстрока для поиска (GET-параметр search).')); } if (!($limit = intval($ctx->get('limit', 5)))) { throw new BadRequestException(t('Не указано количество возовращаемых меток (GET-параметр limit).')); } list($sql, $params) = Query::build(array('class' => 'label', 'deleted' => 0, 'published' => 1, 'name?|' => '%' . $search . '%', '#sort' => 'name'))->getSelect(null, null, 'name'); $result = ''; foreach ((array) $ctx->db->getResultsV("name", $sql, $params) as $name) { $result .= html::em('label', html::cdata($name)); } return new Response(html::em('labels', array('search' => $search, 'limit' => $limit), $result), 'text/xml'); }
function getQuery(RelationshipLoader $loader) { if ($loader instanceof DeferredLoader) { if ($loader->Relation->inversedBy !== null) { $keyColumn = $loader->Relation->inversedBy; } else { $keyColumn = $loader->Relation->Entity->PrimaryKey->InnerName; } $query = Query::build(Query::SQL, Query::HYDRATE_SCALAR)->select()->from($loader->Relation->Entity)->where($keyColumn, $loader->Source->Data[$this->Name]); $query->DataType = $loader->Relation->Entity->InnerName; return $query; } elseif ($loader instanceof ImmediateLoader) { // JOIN } return null; }
/** * @param Query $query * @return Response * @throws EstatException */ public function query(Query $query) { $tokenId = $this->getClient()->getAccessToken(); $uri = Query::URL; $headers = array('Content-Type' => 'application/json'); $content = $query->build($tokenId); $content = $this->getClient()->getHttpAdapter()->postContent($uri, $headers, $content); if ($content === null) { throw EstatException::invalidResponse('No content'); } $json = json_decode($content, true); if (!is_array($json) || isset($json['gosuResponse']['errorCode'])) { throw EstatException::invalidQuery(isset($json['gosuResponse']['errorCode']) ? $json['gosuResponse']['errorMessage'] : 'Invalid json'); } return new Response($json); }
private static function write_nodes(Context $ctx, $f) { $filter = array('class' => $ctx->db->getResultsV("name", "SELECT `name` FROM `node` WHERE `class` = 'type' AND `deleted` = 0 AND `published` = 1"), 'published' => 1, 'deleted' => 0, '#sort' => '-id'); list($sql, $params) = Query::build($filter)->getSelect(array('id', 'updated')); if ($nodes = $ctx->db->getResults($sql, $params)) { fwrite($f, "<!-- documents -->\n"); foreach ($nodes as $node) { $line = "<url>" . "<loc>http://" . MCMS_HOST_NAME . "/node/{$node['id']}</loc>"; if (!empty($node['updated'])) { $date = gmdate('c', strtotime($node['updated'])); $line .= "<lastmod>{$date}</lastmod>"; } $line .= "</url>\n"; fwrite($f, $line); } } }
/** * Обработка ссылок в формате [[текст]]. * @mcms_message ru.molinos.cms.format.text */ public static function on_format_text(Context $ctx, $fieldName, &$text) { if ($map = self::map($text)) { $names = array(); foreach ($map as $v) { $names[] = $v[0]; } list($sql, $params) = Query::build(array('class' => array('story', 'label'), 'published' => 1, 'deleted' => 0, 'name' => $names))->getSelect(array("id", "name")); $data = (array) $ctx->db->getResultsKV("name", "id", $sql, $params); $replacement = array(); foreach ($map as $k => $v) { $link = $v[1]; if (isset($data[$v[0]])) { $link = t("<a href='@url'>%text</a>", array('@url' => 'node/' . $data[$v[0]], '%text' => $v[1])); } $replacement[$k] = $link; } $text = str_replace(array_keys($replacement), array_values($replacement), $text); } }
public function setColumns($columns) { if (!is_array($columns)) { $columns = explode(',', $columns); } $query = Query::build()->from('userColumns')->where('user', '=', 'user', true)->bind('user', $this->id)->delete(); foreach ($columns as $column) { $column = trim($column); $query = Query::build()->from('userColumns')->set('user', 'user', true)->set('column', 'column', true)->bind('user', $this->id)->bind('column', $column)->insert(); } }
/** * Gets a record matching primary key value * @param mixed $pk string or numeric value to search for in primary key * @return model matching the search or null if not found */ public function getByPK($pk) { $query = Query::build()->select('*')->from($this->name)->where($this->pk, '=', $this->pk, true)->bind($this->pk, $pk); if ($this->filterByUser) { $query = $query->where('user', '=', Auth::User()->id); } $attributes = $query->getOne(); if ($attributes) { $model = new static($attributes, $this->deep); $model->setIsNew(false); return $model; } else { return null; } }
/** * Возвращает количество нод, удовлетворяющих запросу. */ public static function count($query, Database $db = null) { if (is_array($query)) { $query = Query::build($query); } elseif (!$query instanceof Query) { throw new InvalidArgumentException(t('Запрос должен быть массивом или объектом Query.')); } if (null === $db) { $db = Context::last()->db; } list($sql, $params) = $query->getCount(); $sth = $db->prepare($sql); $sth->execute($params); return intval($sth->fetchColumn(0)); }
function batchUpdate($maxRows = 500) { $db = new DataBase(); $db->connect(); $query = new Query($this->__table__, "update"); $query->batchMode = TRUE; $firstElement = $this->__elements__[0]; $query->keys = array_keys($firstElement->__buildVars__()); $e = 0; $query->extendedtype = "IGNORE"; $query->values = array(); foreach ($this->__elements__ as $elmnt) { //$elmnt->__buildVars__(); $executed = false; $query->values[] = $elmnt; //echo join(",",$elmnt->__class_vars__)."<br/>"; if ($e > 0 && $e % $maxRows == 0) { echo $query->build(); // $res = $db->execute($query); $query->values = array(); $executed = true; } $e++; } //echo $query->build(); if (!$executed) { $res = $db->execute($query); } //echo $elmnt->save(); }
function getQuery(RelationshipLoader $loader) { return Query::build($this->Entity->InnerName, Query::HYDRATE_SCALAR)->select()->from($this->Entity)->where($this->Entity->PrimaryKey->InnerName, $loader->Source->Data[$this->Name]); }
function getSelectCommand() { $this->Command = Query::build(Query::SQL)->entities($this->Database, true); return $this->Command; }
/** * Build SQL query and execute * * @param \PDO|PDOInterface|PDOAggregate $pdo * @param string $sql * @param array $params */ public static function executeAndReturnInsertId($pdo, $sql, array $params, $name = null) { $stmt = Query::build($pdo instanceof PDOAggregate ? $pdo->getPDO() : $pdo, $sql, $params); $stmt->execute(); return $pdo->lastInsertId($name); }
function __update__() { $this->__buildVars__(); $query = new Query($this->__table__, "update"); $query->keys = array_keys($this->__class_vars__); $query->values = $this->__class_vars__; $query->where = "id = " . $this->id; echo $query->build(); return $this->__execute__($query); }