Make NULL-safe MySQL query
http://stackoverflow.com/a/19778341/59160

@param  string $comparison
@param  Builder $query
@param  string $field
@param  string $input
@return Builder
489373
protected function applyMysqlEquality($comparison, $query, $field, $input) {
		switch($comparison)
		{
			case '=':
				$sql = sprintf('%s <=> %s', $field, $input);
				return $query->whereRaw($sql);
			case '!=':
				$sql = sprintf('NOT(%s <=> %s)', $field, $input);
				return $query->whereRaw($sql);
		}
	}
97618
public function query($query, $type = '')
    {
        try {
            if ($type === 'SELECT') {
                return $this->conn->query($query);
            }

            return $this->conn->exec($query);
        } catch (\PDOException $e) {
            $this->error = $e->getMessage();

            return null;
        }
    }
1134404
public function where($column, $comp = '=', $value = null, $boolean = 'and')
    {
        if (!static::isComporaisonOperator($comp) || is_null($value)) {
            $value = $comp;

            $comp = '=';
        }

        if ($value === null) {
            throw new QueryBuilderException('Valeur de comparaison non définie', E_ERROR);
        }

        if (!in_array(Str::lower($boolean), ['and', 'or'])) {
            throw new QueryBuilderException(
                'Le booléen '. $boolean . ' non accepté',
                E_ERROR
            );
        }

        $this->where_data_binding[$column] = $value;

        if ($this->where == null) {
            $this->where = '('. $column . ' ' . $comp . ' :' . $column . ')';
        } else {
            $this->where .= ' ' . $boolean . ' ('. $column . ' '. $comp .' :'. $column. ')';
        }

        return $this;
    }
1189720
public function query($query=null, $params = [])
    {
        $result = false;
        $result_key = [];
        
        if ($query && static::isSql($query)) {
            $sql = $query;
        } else {
            $result_key = $this->getQuery()->set($query)->get('result_key');
            
            $queryType = $this->getQuery()->type();
            
            // limit select count
            if ((!$queryType || $queryType === 'select') 
                && !isset($this->getQuery()['count']) 
                && !isset($this->getQuery()['limit'])
                && !isset($this->getQuery()['pagesize'])) 
            {
                $this->getQuery()->set('limit', 1000);
            }
            
            // update must set where
            if (($queryType === 'update' || $queryType === 'delete') && !$this->getQuery()->get('where')) {
                Ioc::logger('db')->error('query no set where: ' . json_encode($this->getQuery()->all()));
                return false;
            }
            
            $sql = $this->parse();
        }
        
        if ($params) {
            $this->bindParams($params);
        }
        
        $this->lastSql = $this->formatSql($sql);
        
        // sql log
        Ioc::logger('db')->debug($sql);
        
        try {
            $this->getAdapter()->prepare($sql);
            if (!empty($this->binds)) {
                $this->getAdapter()->bindParams($this->binds);
            }
            $bool = $this->getAdapter()->execute();
            
            if (!$bool) {
                throw new Exception($this->getAdapter()->getErrorMessage());
            }
        } catch (Exception $e) {
            
            $this->getAdapter()->rollback();
            throw new Exception('Excute sql error: ' . $e->getMessage() . ', sql:' . $sql);
        }
        
        $rawStatement = explode(" ", $sql);
        $statement = strtolower(trim($rawStatement[0]));
        
        if ($statement === 'show') {
            $result = $this->getAdapter()->fetchAll($fetchmode);
        } elseif ($statement === 'select') {
            $rkeys = $result_key ? StringHelper::toArray($result_key, ',\s') : null;
            
            while($rs = $this->getAdapter()->fetch()) {
                // 如果指定返回结果集的key，则按key重组数据
                if ($rkeys) {
                    if (count($rkeys) == 1) {
                        $rk1 = trim($rkeys[0]);
                        if (isset($rs[$rk1])) {
                            $result[$rs[$rk1]] = $rs;
                        } else {
                            $result[] = $rs;
                        }
                    } elseif (count($rkeys) == 2) {
                        $rk1 = trim($rkeys[0]);
                        $rk2 = trim($rkeys[1]);
                        if (!empty($rk2)) {
                            $result[$rs[$rk1]][$rs[$rk2]] = $rs;
                        } else {
                            $result[$rs[$rk1]][] = $rs;
                        }
                    }
                } else {
                    $result[] = $rs;
                }
            }
        } elseif ($statement === 'update' || $statement === 'delete') {
            $result = $this->getAdapter()->numberOfRows();
        } elseif ($statement === 'insert') {
            $result = $this->getAdapter()->lastId();
        } else {
            return null;
        }
        
        return $result;
    }
57323
function _query($sql,$inputarr=false)
	{
		if (is_array($sql)) {
			$stmt = $sql[1];
		} else {
			$stmt = $this->_connectionID->prepare($sql);
		}
		#adodb_backtrace();
		#var_dump($this->_bindInputArray);
		if ($stmt) {
			$this->_driver->debug = $this->debug;
			if ($inputarr) {
				$ok = $stmt->execute($inputarr);
			}
			else {
				$ok = $stmt->execute();
			}
		}


		$this->_errormsg = false;
		$this->_errorno = false;

		if ($ok) {
			$this->_stmt = $stmt;
			return $stmt;
		}

		if ($stmt) {

			$arr = $stmt->errorinfo();
			if ((integer)$arr[1]) {
				$this->_errormsg = $arr[2];
				$this->_errorno = $arr[1];
			}

		} else {
			$this->_errormsg = false;
			$this->_errorno = false;
		}
		return false;
	}
652457
public function search( $query ) {
		$marshaler = new Marshaler();

		$args = [
			'TableName' => 'wpsnapshots-' . $this->repository,
		];

		if ( '*' !== $query ) {
			$args['ConditionalOperator'] = 'OR';

			$args['ScanFilter'] = [
				'project' => [
					'AttributeValueList' => [
						[ 'S' => strtolower( $query ) ],
					],
					'ComparisonOperator' => 'CONTAINS',
				],
				'id'      => [
					'AttributeValueList' => [
						[ 'S' => strtolower( $query ) ],
					],
					'ComparisonOperator' => 'EQ',
				],
			];
		}

		try {
			$search_scan = $this->client->getIterator( 'Scan', $args );
		} catch ( \Exception $e ) {
			Log::instance()->write( 'Error Message: ' . $e->getMessage(), 1, 'error' );
			Log::instance()->write( 'AWS Request ID: ' . $e->getAwsRequestId(), 1, 'error' );
			Log::instance()->write( 'AWS Error Type: ' . $e->getAwsErrorType(), 1, 'error' );
			Log::instance()->write( 'AWS Error Code: ' . $e->getAwsErrorCode(), 1, 'error' );

			return false;
		}

		$instances = [];

		foreach ( $search_scan as $item ) {
			$instances[] = $marshaler->unmarshalItem( $item );
		}

		return $instances;
	}
731432
public function setComparison($comparison)
    {
        if (!in_array($comparison, $this->getAvailableComparisons())) {
            throw new FieldException(sprintf('Comparison "%s" not allowed for this type of field ("%s").', $comparison, $this->getType()));
        }

        $this->comparison = $comparison;
    }
1117469
public function gte($field, $value)
    {
        if(!$value instanceof Expr\ConditionalExpression) {
            $value = $this->buildPart($value);
        }
        return new Expr\ComparisonExpression($field, $value, Expr\ComparisonExpression::GTE);
    }
193714
public static function getPairsBy($key, $val, $compare = '=', $args = array())
    {
        $instance = Post\Factory::create(get_called_class());

        global $wpdb;
        if (in_array($key, static::getCoreFieldKeys())) {
            // Using a core field
            $sql = sprintf(
                "SELECT p.ID, p.post_title
                FROM $wpdb->posts p
                WHERE p.post_type = %s
                AND (p.post_status = 'publish')
                AND %s %s %s
                ORDER BY p.ID ASC",
                '%s',
                $key,
                $compare,
                '%s'
            );
            $prepared_sql = $wpdb->prepare($sql, $instance->getPostType(), $val);
        } else {
            // Number fields should be compared numerically, not alphabetically
            // Of course, this currently requires you to use type=number to achieve numeric sorting
            $fields = $instance->getFields();
            $field_is_numeric = ($fields[$key]['type'] === 'number');

            // Using a meta field
            $sql = sprintf(
                "
                SELECT p.ID, p.post_title
                FROM $wpdb->postmeta pm
                INNER JOIN $wpdb->posts p
                ON p.ID = pm.post_id
                WHERE p.post_type = %s
                AND (p.post_status = 'publish')
                AND pm.meta_key = %s
                AND %s %s %s
                ORDER BY p.ID ASC
                ",
                '%s',
                '%s',
                ($field_is_numeric) ? 'CAST(pm.meta_value AS DECIMAL)' : 'pm.meta_value',
                $compare,
                '%s'
            );
            $prepared_sql = $wpdb->prepare($sql, $instance->getPostType(), $key, $val);
        }
        $results = $wpdb->get_results($prepared_sql);
        $post_ids = Collection::pluck($results, 'ID');
        if (!Arr::iterable($args)) {
            if (!Arr::iterable($results)) {
                return array();
            }
            
            return array_combine(
                $post_ids,
                Collection::pluck($results, 'post_title')
            );
        }

        if (array_key_exists('post__in', $args)) {
            $args = (is_array($args)) ? $args : array_map('trim', explode(',', $args));
            $args['post__in'] = array_merge($args['post__in'], $post_ids);
        } else {
            $args['post__in'] = $post_ids;
        }

        // Need to use args? Call getBy.
        $records = static::getBy($key, $val, $compare, $args, false);
        if (!Arr::iterable($records)) {
            return array();
        }
    
        return array_combine(
            Collection::pluck($records, 'ID'),
            Collection::pluck($records, 'post_title')
        );
    }
716708
protected function setKeysForSaveQuery(Builder $query)
    {
        $keys = $this->getKeyName();

        if (!is_array($keys)) {
            return parent::setKeysForSaveQuery($query);
        }

        foreach ($keys as $key) {
            $query->where($key, '=', $this->getKeyForSaveQuery($key));
        }

        return $query;
    }
1033662
protected function performJoins(Builder $query = null)
    {
        $query = $query ?: $this->query;

        foreach ($this->throughParents as $i => $model) {
            $table = $model->getTable();

            $predecessor = $i > 0 ? $this->throughParents[$i - 1] : $this->related;

            $first = $table.'.'.$this->getForeignKeyName($predecessor);

            $second = $predecessor->getQualifiedKeyName();

            $query->join($table, $first, '=', $second);

            if ($this->hasSoftDeletes($model)) {
                $this->query->whereNull($model->getQualifiedDeletedAtColumn());
            }
        }
    }
936764
protected function setupBasicQueryFilter($query, array $input = [])
    {
        $orderBy = $this->getBasicQueryOrderBy($input);

        $direction = $this->getBasicQueryDirection($input);

        $columns = $input['columns'] ?? null;

        if (\is_array($columns) && $this->isColumnExcludedFromFilterable($orderBy, $columns)) {
            return $query;
        }

        ! empty($orderBy) && $query->orderBy($orderBy, $direction);

        return $query;
    }
1202667
public function lt($field, $value)
    {
        if(!$value instanceof Part) {
            $value = $this->buildPart($value);
        }
        return new Expr\ComparisonExpression($field, $value, Expr\ComparisonExpression::LT);
    }
847940
public function gt($field, $value)
    {
        if(!$value instanceof Expr\ConditionalExpression) {
            $value = $this->buildPart($value);
        }
        return new Expr\ComparisonExpression($field, $value, Expr\ComparisonExpression::GT);
    }
614148
protected function applySqlServerEquality($comparison, $query, $field, $input) {
		switch($comparison)
		{
			case '=':
				$sql = sprintf("COALESCE(%s, '') = COALESCE(%s, '')", $field, $input);
				return $query->whereRaw($sql);
			case '!=':
				$sql = sprintf("COALESCE(%s, '') != COALESCE(%s, '')", $field, $input);
				return $query->whereRaw($sql);
		}
	}
1134691
public static function neq($field, $value, $dqlAlias = null)
    {
        return new Comparison(Comparison::NEQ, $field, $value, $dqlAlias);
    }
115319
protected function search(Builder $query)
    {
        $q = request('q');

        if (!$q || strlen($q) < $this->minimumSearchInputLength)
            return $query;

        return $this->searchQuery($query, $q);
    }