You are here

function DateSqlHandler::sql_field in Date 8

Helper function to create cross-database SQL dates.

Parameters

string $field: The real table and field name, like 'tablename.fieldname' .

string $offset: The name of a field that holds the timezone offset or an offset value. If NULL, the normal Drupal timezone handling will be used, if $offset = 0 no adjustment will be made.

Return value

string An appropriate SQL string for the db type and field type.

3 calls to DateSqlHandler::sql_field()
DateSqlHandler::sql_where_date in date_api/lib/Drupal/date_api/DateSqlHandler.php
Creates a where clause to compare a complete date field to a date value.
DateSqlHandler::sql_where_extract in date_api/lib/Drupal/date_api/DateSqlHandler.php
Creates a where clause comparing an extracted date part to an integer.
DateSqlHandler::sql_where_format in date_api/lib/Drupal/date_api/DateSqlHandler.php
Create a where clause to compare a formated field to a formated value.

File

date_api/lib/Drupal/date_api/DateSqlHandler.php, line 132

Class

DateSqlHandler
A class to manipulate date SQL.

Namespace

Drupal\date_api

Code

function sql_field($field, $offset = NULL, $comp_date = NULL) {
  if (strtoupper($field) == 'NOW') {

    // NOW() will be in UTC since that is what we set the db timezone to.
    $this->local_timezone = 'UTC';
    return $this
      ->sql_offset('NOW()', $offset);
  }
  switch ($this->db_type) {
    case 'mysql':
    case 'mysqli':
      switch ($this->date_type) {
        case DATE_UNIX:
          $field = "FROM_UNIXTIME({$field})";
          break;
        case DATE_ISO:
          $field = "STR_TO_DATE({$field}, '%Y-%m-%dT%T')";
          break;
      }
      break;
    case 'pgsql':
      switch ($this->date_type) {
        case DATE_UNIX:
          $field = "{$field}::ABSTIME";
          break;
        case DATE_ISO:
          $field = "TO_DATE({$field}, 'FMYYYY-FMMM-FMDDTFMHH24:FMMI:FMSS')";
          break;
      }
      break;
    case 'sqlite':
      switch ($this->date_type) {
        case DATE_UNIX:
          $field = "datetime({$field}, 'unixepoch')";
          break;
        case DATE_ISO:
          $field = "datetime({$field})";
          break;
      }
      break;
    case 'sqlsrv':
      switch ($this->date_type) {
        case DATE_UNIX:
          $field = "DATEADD(s, {$field}, '19700101 00:00:00:000')";
          break;
        case DATE_ISO:
          $field = "CAST({$field} as smalldatetime)";
          break;
      }
      break;
      break;
  }

  // Adjust the resulting value to the right timezone/offset.
  return $this
    ->sql_tz($field, $offset, $comp_date);
}