includes/database.inc, строка 315
- 5 – 6
db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array())
Изменяет первоначальные запросы нод, таксономии и комментариев. Часто используется для формирования списков запросов.
Вместо синтаксиса
FROM table1, table2
используйте
JOIN
Параметры
$query
Запрос, который будет перезаписан.
$primary_table
Имя или псевдоним таблицы, которая имеет первичный ключ для этого запроса. Хотя обычные имена таблиц такие: '{blocks}'
, '{comments}'
, '{forum}'
, '{node}'
, '{menu}'
, '{term_data}'
или '{vocabulary}'
. Но не смотря на это, обычно используются псевдонимы таблиц, например: 'b'
, 'c'
, 'f'
, 'n'
, 'm'
, 't'
или 'v'
.
$primary_field
Имя основного поля.
$args
Массив аргументов, которые передаются реализациями хука hook_db_rewrite_sql()
.
Возвращаемое значение
Исходный запрос с конструкциями JOIN
и WHERE
и со вставками из хука hook_db_rewrite_sql()
.
Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not
use FROM table1, table2 syntax, use JOIN instead.
Parameters
$query
Query to be rewritten.
$primary_table
Name or alias of the table which has the primary key field for this query.
Typical table names would be: {blocks}, {comments}, {forum}, {node},
{menu}, {term_data} or {vocabulary}. However, it is more common to use the
the usual table aliases: b, c, f, n, m, t or v.
$primary_field
Name of the primary field.
$args
An array of arguments, passed to the implementations of hook_db_rewrite_sql.
Return value
The original query with JOIN and WHERE statements inserted from
hook_db_rewrite_sql implementations. nid is rewritten if needed.
Связанные темы
- Уровень абстракции базы данных
- Позволяет выполнять один программный код на разных СУБД.
- block_list in modules/block/block.module
- Возвращает все блоки в заданном регионе для текущего пользователя.
- blogapi_mt_validate_terms in modules/blogapi/blogapi.module
- Blogging API helper - find allowed taxonomy terms for a node type.
- blog_block in modules/blog/blog.module
- Реализация hook_block().
- blog_feed_last in modules/blog/blog.pages.inc
- Menu callback; displays an RSS feed containing recent blog entries of all users.
- blog_feed_user in modules/blog/blog.pages.inc
- Menu callback; displays an RSS feed containing recent blog entries of a given user.
- blog_page_last in modules/blog/blog.pages.inc
- Коллбэк меню. Показывает страницу Друпал с последними записями в блогах пользователей.
- blog_page_user in modules/blog/blog.pages.inc
- Коллбэк меню. Показывает страницу Друпал с последними записями в блоге данного пользователя.
- book_block in modules/book/book.module
- Реализация hook_block().
- book_get_books in modules/book/book.module
- Возвращает массив всех книг.
- comment_get_recent in modules/comment/comment.module
- Find a number of recent comments. This is done in two steps.
1. Find the n (specified by $number) nodes that have the most recent
comments. This is done by querying node_comment_statistics which has
an index on last_comment_timestamp, and is thus a...
- comment_render in modules/comment/comment.module
- Отображает комментарии.
- forum_block in modules/forum/forum.module
- Реализация hook_block().
- forum_get_forums in modules/forum/forum.module
- Returns a list of all forums for a given taxonomy id
- forum_get_topics in modules/forum/forum.module
- forum_term_load in modules/forum/forum.module
- Загружает термин форума из таксономии.
- menu_tree_check_access in includes/menu.inc
- Проверяет доступ и выполняет другие динамические операции для каждой ссылки в дереве меню.
- node_admin_nodes in modules/node/node.admin.inc
- Form builder: Builds the node administration overview.
- node_feed in modules/node/node.module
- A generic function for generating RSS feeds from a set of nodes.
- node_page_default in modules/node/node.module
- Menu callback; Generate a listing of promoted nodes.
- poll_block in modules/poll/poll.module
- Реализация hook_block().
- poll_page in modules/poll/poll.pages.inc
- Menu callback to provide a simple list of all polls available.
- statistics_title_list in modules/statistics/statistics.module
- Returns all time or today top or last viewed node(s).
- taxonomy_autocomplete in modules/taxonomy/taxonomy.pages.inc
- Вспомогательная функция для автозаполнения формы с терминами таксономии
- taxonomy_form_alter in modules/taxonomy/taxonomy.module
- Implementation of hook_form_alter().
Generate a form for selecting terms to associate with a node.
We check for taxonomy_override_selector before loading the full
vocabulary, so contrib modules can intercept before hook_form_alter
and provide scalable...
- taxonomy_get_children in modules/taxonomy/taxonomy.module
- Находит все дочерние термины данного термина.
- taxonomy_get_parents in modules/taxonomy/taxonomy.module
- Находит всех родителей данного идентификатора термина по его ID.
- taxonomy_get_term_by_name in modules/taxonomy/taxonomy.module
- Try to map a string to an existing term, as for glossary use.
- taxonomy_get_tree in modules/taxonomy/taxonomy.module
- Создает иерархическое представление словаря.
- taxonomy_get_vocabularies in modules/taxonomy/taxonomy.module
- Возвращает массив объектов всех словарей.
- taxonomy_node_get_terms in modules/taxonomy/taxonomy.module
- Находит все термины, которые связаны с данной нодой, и сортирует их по словарю и весу термина.
- taxonomy_node_get_terms_by_vocabulary in modules/taxonomy/taxonomy.module
- Находит все термины, которые связаны с данной нодой, в одном словаре.
- taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
- Form builder for the taxonomy terms overview.
- taxonomy_select_nodes in modules/taxonomy/taxonomy.module
- Находит все ноды, которые соответствуют выбранным условиям таксономии.
- taxonomy_term_count_nodes in modules/taxonomy/taxonomy.module
- Считает число опубликованных нод, содержащих терм.
- taxonomy_term_page in modules/taxonomy/taxonomy.pages.inc
- Коллбэк меню; отображает все ноды, связанные с термином таксономии.
- template_preprocess_forum_topic_navigation in modules/forum/forum.module
- Preprocess variables to format the next/previous forum topic navigation links.
- tracker_page in modules/tracker/tracker.pages.inc
- Menu callback. Prints a listing of active nodes on the site.
- translation_node_get_translations in modules/translation/translation.module
- Get all nodes in a translation set, represented by $tnid.
- _blog_post_exists in modules/blog/blog.module
- Helper function to determine if a user has blog posts already.
- _forum_new in modules/forum/forum.module
- Находит первую непрочтённую ноду для заданного форума.
- _forum_topics_unread in modules/forum/forum.module
- Calculate the number of nodes the user has not yet read and are newer
than NODE_NEW_LIMIT.
- _node_types_build in modules/node/node.module
- Builds and returns the list of available node types.
Код
<?php
function db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array()) {
list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table, $primary_field, $args);
if ($distinct) {
$query = db_distinct_field($primary_table, $primary_field, $query);
}
if (!empty($where) || !empty($join)) {
$pattern = '{
# Beginning of the string
^
((?P<anonymous_view>
# Everything within this set of parentheses is named "anonymous view"
(?:
[^()]++ # anything not parentheses
|
\( (?P>anonymous_view) \) # an open parenthesis, more "anonymous view" and finally a close parenthesis.
)*
)[^()]+WHERE)
}x';
preg_match($pattern, $query, $matches);
if (!$where) {
$where = '1 = 1';
}
if ($matches) {
$n = strlen($matches[1]);
$second_part = substr($query, $n);
$first_part = substr($matches[1], 0, $n - 5) ." $join WHERE $where AND ( ";
$haystack_reverse = strrev($second_part);
}
else {
$haystack_reverse = strrev($query);
}
foreach (array('PUORG', 'REDRO', 'TIMIL') as $needle_reverse) {
$pos = strpos($haystack_reverse, $needle_reverse);
if ($pos !== FALSE) {
$pos += 5;
break;
}
}
if ($matches) {
if ($pos === FALSE) {
$query = $first_part . $second_part .')';
}
else {
$query = $first_part . substr($second_part, 0, -$pos) .')'. substr($second_part, -$pos);
}
}
elseif ($pos === FALSE) {
$query .= " $join WHERE $where";
}
else {
$query = substr($query, 0, -$pos) . " $join WHERE $where " . substr($query, -$pos);
}
}
return $query;
}
?>
Пользовательские комментарии
Войдите или
зарегистрируйтесь, чтобы получить возможность отправлять комментарии
Эта функция относится к cissp braindump внутрисайтовой HTTP-переадресации. Функция проверяет, является ли указанный для перехода URL корректно сформированным.Эта функция относится к внутрисайтовой HTTP-переадресации. Функция проверяет, является ли указанный для перехода db2 certification dumps>
URL корректно сформированным.Эта функция относится к внутрисайтовой HTTP-переадресации. Функция проверяет, является ли указанный mcitp certification для перехода URL корректно сформированным.