You are here

function messaging_query_sql in Messaging 6.4

Build the SQL statement from query elements

It will build INSERT + SELECT or SELECT queries from its elements

Parameters

$query: Array of query parameters

$execute: Whether to execute the query right away or return parameters

Return value

mixed If not $execute, list($sql, $args) If execute, query result

1 call to messaging_query_sql()
Messaging_Store::select_query in includes/messaging_store.class.inc
Run select query with given parameters

File

./messaging.module, line 909

Code

function messaging_query_sql($query, $execute = FALSE) {
  $sql = !empty($query['sql']) ? $query['sql'] : '';
  if (!empty($query['insert'])) {
    $sql .= 'INSERT INTO ' . $query['into'] . ' (' . implode(', ', $query['insert']) . ') ';
  }
  if (!empty($query['select'])) {
    $sql .= !empty($query['distinct']) ? 'SELECT DISTINCT ' : 'SELECT ';
    $sql .= implode(', ', $query['select']);
    $sql .= ' FROM ' . implode(', ', $query['from']);
  }
  if (!empty($query['join'])) {
    $sql .= ' ' . implode(' ', $query['join']);
  }
  if (!empty($query['where'])) {
    $sql .= ' WHERE (' . implode(') AND (', $query['where']) . ')';
  }
  if (!empty($query['group'])) {
    $sql .= ' GROUP BY ' . implode(', ', $query['group']);
  }
  if (!empty($query['having'])) {
    $sql .= ' HAVING ' . implode(' AND ', $query['having']);
  }

  // Merge all args, start with generic ones for subscription queries, then other groups
  $args = !empty($query['args']) ? $query['args'] : array();
  foreach (array(
    'select',
    'join',
    'where',
    'having',
  ) as $key) {
    if (!empty($query[$key . ' args'])) {
      $args = array_merge($args, $query[$key . ' args']);
    }
  }

  // Add order by
  if (!empty($query['order'])) {
    $sql .= ' ORDER BY ' . implode(', ', $query['order']);
  }

  // Return parameters or execute query
  if (!$execute) {
    return array(
      $sql,
      $args,
    );
  }
  elseif (!empty($query['pager'])) {
    return pager_query($sql, $query['limit'], $query['pager'], NULL, $args);
  }
  elseif (!empty($query['limit'])) {
    return db_query_range($sql, $args, 0, $query['limit']);
  }
  else {
    return db_query($sql, $args);
  }
}