You are here

class DataQuery in Data 6

Builds and executes a query, only delete queries are supported at the moment.

Hierarchy

Expanded class hierarchy of DataQuery

File

includes/DataHandler.inc, line 182
Definition of DataHandler class.

View source
class DataQuery {
  public $subject, $table, $from, $join, $where;

  /**
   * Creates an empty query.
   *
   * @param $table
   *   Base table to operate on, also the subject table to delete
   *   from.
   */
  public function __construct($table) {
    $this->table = db_escape_table($table);
    $this->subject = array(
      $this->table => $this->table,
    );
    $this->from = $this->table;
    $this->join = array();
    $this->where = array();
  }

  /**
   * Add a subject table.
   */
  public function addSubject($table) {
    $this->subject[$table] = $table;
  }

  /**
   * Add a join.
   *
   * @param $table
   *   The table to join to.
   * @param $join
   *   The columns to join on.
   */
  public function addJoin($table, $join, $type = 'INNER JOIN') {
    $this->join[$table] = array(
      $join,
      $type,
    );
  }

  /**
   * Add a where clause.
   *
   * @param $clause
   *   The actual clause. Caller is responsible for referring to existing fields
   *   and supplying correct placeholder for value.
   * @param $value
   *   The value the clause compares against.
   */
  public function addWhere($clause, $value = NULL) {
    $this->where[$clause] = $value;
  }

  /**
   * Build and execute a query.
   */
  public function execute() {
    $table = db_escape_table($this->table);
    $query = "DELETE " . implode(', ', $this->subject);
    $query .= " FROM {{$table}} {$table}";
    if (!empty($this->join)) {
      foreach ($this->join as $table => $join) {
        $table = db_escape_table($table);
        $clause = array_shift($join);
        $join = array_shift($join);
        $query .= " {$join} {{$table}} {$table} ON {$clause}";
      }
    }
    $where = $values = array();
    foreach ($this->where as $k => $v) {
      $where[] = $k;
      if ($v !== NULL) {
        $values[] = $v;
      }
    }
    if (!empty($where)) {
      $query .= " WHERE " . implode(' AND ', $where);
    }
    return db_query($query, $values);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DataQuery::$subject public property
DataQuery::addJoin public function Add a join.
DataQuery::addSubject public function Add a subject table.
DataQuery::addWhere public function Add a where clause.
DataQuery::execute public function Build and execute a query.
DataQuery::__construct public function Creates an empty query.