@function selectByIdWhereSql

build SQL for WHERE for select by id

@returns {string}
328774
function selectByIdWhereSql () {
    // get id column
    var idColumn = this.model.columnName('id')
    // every where statement will begin with the alias and column name
    var columnSql = `${this.alias}.${this.quoteName(idColumn)}`
    // sql for where query
    var sql
    // if ids are array build in query
    if (Array.isArray(this.args.where.id)) {
        var i = 0
        // get placeholder for each in value
        var placeholders = _.map(this.args.where.id, id => {
            // get param name
            var paramName = `id${i}`
            // increment param counter
            i++
            // set value for param placeholder
            this.params[paramName] = id
            // create placeholder
            return this.unhexId(`:${paramName}`)
        })
        // return where sql
        sql = `WHERE ${columnSql} IN(${placeholders.join(', ')})`
    }
    // otherwise build equals query
    else {
        // set value for param placeholder
        this.params.id = this.args.where.id
        // get place holder
        var placeholder = this.unhexId(':id')
        // return where sql
        sql = `WHERE ${columnSql} = ${placeholder}`
    }
    // and deleted check if d column exists and set in args
    if (defined(this.model.columns.d) && typeof this.args.where.isDeleted === 'boolean') {
        sql += ` AND ${this.alias}.d = ${this.args.where.isDeleted ? 1 : 0}`
    }

    return sql
}
1022578
protected function getStaticValueIdsSql($id)
    {
        return (new Query())
            ->select('id')
            ->from(StaticValue::tableName())
            ->where(['property_id' => $id])
            ->createCommand()
            ->getRawSql();
    }
944239
def select(table, cols="*", where=(), group="", order=(), limit=(), **kwargs):
    """"""
    where = dict(where, **kwargs).items()
    sql, args = makeSQL("SELECT", table, cols, where, group, order, limit)
    return execute(sql, args)
930984
public function inWhere(){
       $this->find = true;
       if(2 == func_num_args()){
            $change = function ($str) {
               return sprintf("'%s'", $str);
            };
            $filed = func_get_arg(0);
            $getArgs = func_get_arg(1);
            if(is_array($getArgs)){
              $indata = implode(",",array_map($change, $getArgs));
              $sql = "`$filed` in ({$indata})";
            }else{
              $sql = "`$filed` in ({$getArgs})";
            }
            $this->arWhere .= $sql;
       }
       return $this;
    }
797896
public function select(array $where = [], array $nosql_options = [])
    {
        // Set statement
        $query = $this->getSelect($where);
        $statement = $this->getInstance()->prepare($query);

        // Bind where values
        foreach ($where as $key => $value) {
            $statement->bindValue(":where_$key", $value, $this->isPdoInt($value));
        }

        // Execute operation
        $statement->execute();

        // Return object
        return $statement->fetchAll(PDO::FETCH_OBJ);
    }
143452
function selectColumnSql (model, column, spec, alias, as) {
    // if alias is not registered then this should be a table name
    if (!this.aliases[alias]) {
        // create alias from table anme
        alias = this.getAlias(alias)
    }
    // base sql is alias.`column`
    var sql = alias+'.'+this.quoteName(column)
    // if column type is id then select HEX(alias.`column`) AS `column`
    if (spec.type === 'id' && model.binaryIds) {
        sql = 'LOWER(HEX('+sql+')) as '+this.quoteName(typeof as === 'string' ? as : column)
    }
    // if column type is data and compression then select
    // BASE_64(alias.`column`) AS `column`
    else if (spec.type === 'data' && model.compression) {
        sql = 'TO_BASE64('+sql+') as '+this.quoteName(typeof as === 'string' ? as : column)
    }
    // return column sql
    return sql
}
96718
function(req) {

    return req.options.id || ( req.options.where && req.options.where.id ) || req.allParams()['id'];
  }
884860
function getsql($ifreturn = true)
    {
        $this->sql = "select {$this->select} from {$this->table}";
        $this->sql .= implode(' ',
            array(
                $this->join,
                $this->use_index,
                $this->where,
                $this->union,
                $this->group,
                $this->having,
                $this->order,
                $this->limit,
                $this->for_update,
            ));

        if ($this->if_union)
        {
            $this->sql = str_replace('{#union_select#}', $this->union_select, $this->sql);
        }
        if ($ifreturn)
        {
            return $this->sql;
        }
    }
805899
function sql(str) {
    if (!(this instanceof sql))
      return applyNew(sql, arguments);

    this.str = str;
    this.vals = _.toArray(arguments).slice(1);

    // support passing a single array
    if (_.isArray(this.vals[0]))
      this.vals = this.vals[0];
  }
1006863
public function get_select_sql( $tables, $where = null, $fields = null, $limit = null, $offset = null, $order_by = null, $group_by = null, $for_update = false ) {
		$as = null;
		if ( is_array( $tables ) ) {
			if ( empty( $tables ) ) {
				return false;
			}
			$table = array_shift( $tables );
			$join  = $tables;
			if ( count( $table ) > 1 ) {
				$as = $table[1];
			}
			$table = $table[0];
		} else {
			$table = $tables;
			$join  = null;
		}
		if ( ! isset( $this->table_defines[ $table ] ) ) {
			return false;
		}

		$columns = $this->table_defines[ $table ]['columns'];

		! is_array( $where ) and $where = [];
		if ( $this->is_logical( $this->table_defines[ $table ] ) ) {
			$where['deleted_at'] = null;
		}

		list( $conditions, $values ) = $this->build_conditions( $where, $columns );
		$table  = $this->get_table( $table );
		$fields = $this->build_fields( $fields, $columns );
		$sql    = "SELECT {$fields} FROM $table";
		if ( isset( $as ) ) {
			$sql .= " AS $as";
		}
		$sql .= $this->build_join( $join );
		if ( ! empty( $conditions ) ) {
			$sql .= " WHERE $conditions";
		}
		$sql .= $this->build_group_by( $group_by, $columns );
		$sql .= $this->build_order_by( $order_by, $columns );
		$sql .= $this->build_limit( $limit, $offset );
		if ( $for_update ) {
			$sql .= ' FOR UPDATE';
		}

		return $this->prepare( $sql, $values );
	}
1298382
function get(tableName, fieldNames, where, orderBy) {
    if (orderBy && !checkOrderBy(orderBy)) {
      throw new Error('Invalid arg: orderBy');
    }
    if (!db) {
      throw new Error('Not connected');
    }
    let sql = `SELECT ${fieldNames.join(',')} FROM ${tableName}`;
    if (where) {
      sql += ` WHERE ${where}`;
    }
    if (orderBy) {
      sql += ` ORDER BY ${orderBy.join(',')}`;
    }
    return new Promise(((resolve, reject) => {
      db.get(sql, [], (error, row) => {
        if (error) {
          reject(error);
        } else {
          resolve(row);
        }
      });
    }));
  }
1370767
public function selectById($id)
	{
		$sql = "SELECT * FROM `$this->tableName` WHERE `$this->pkColName` = %d ";
		$stmt = $this->pdo->prepare(sprintf($sql, $id));
		$res = $stmt->execute();

		if ($res === false) {
			return null;
		}

		$rows = $stmt->fetchAll();

		if (count($rows) !== 1) {
			return null;
		}

		return $this->prepareEntity($rows[0]);
	}
224853
function where(column, operator, value) {

    // Support "where true || where false"
    if (column === false || column === true) {
      return this.where(1, '=', column ? 1 : 0);
    }

    // Check if the column is a function, in which case it's
    // a where statement wrapped in parens.
    if (typeof column === 'function') {
      return this.whereWrapped(column);
    }

    // Allow a raw statement to be passed along to the query.
    if (column instanceof Raw && arguments.length === 1) {
      return this.whereRaw(column);
    }

    // Allows `where({id: 2})` syntax.
    if (typeof column === 'object' && !(column instanceof Raw)) {
      return this._objectWhere(column);
    }

    // Enable the where('key', value) syntax, only when there
    // are explicitly two arguments passed, so it's not possible to
    // do where('key', '!=') and have that turn into where key != null
    if (arguments.length === 2) {
      value = operator;
      operator = '=';

      // If the value is null, and it's a two argument query,
      // we assume we're going for a `whereNull`.
      if (value === null) {
        return this.whereNull(column);
      }
    }

    // lower case the operator for comparison purposes
    var checkOperator = ('' + operator).toLowerCase().trim();

    // If there are 3 arguments, check whether 'in' is one of them.
    if (arguments.length === 3) {
      if (checkOperator === 'in' || checkOperator === 'not in') {
        return this._not(checkOperator === 'not in').whereIn(arguments[0], arguments[2]);
      }
      if (checkOperator === 'between' || checkOperator === 'not between') {
        return this._not(checkOperator === 'not between').whereBetween(arguments[0], arguments[2]);
      }
    }

    // If the value is still null, check whether they're meaning
    // where value is null
    if (value === null) {

      // Check for .where(key, 'is', null) or .where(key, 'is not', 'null');
      if (checkOperator === 'is' || checkOperator === 'is not') {
        return this._not(checkOperator === 'is not').whereNull(column);
      }
    }

    // Push onto the where statement stack.
    this._statements.push({
      grouping: 'where',
      type: 'whereBasic',
      column: column,
      operator: operator,
      value: value,
      not: this._not(),
      bool: this._bool()
    });
    return this;
  }
944109
@Override
  public String buildQuery() {
    validateQuery();

    StringBuilder stringBuilder = new StringBuilder();
    if (!Strings.isNullOrEmpty(select)) {
      stringBuilder = stringBuilder.append(SELECT).append(" ").append(select).append(" ");
    }
    if (!Strings.isNullOrEmpty(from)) {
      stringBuilder = stringBuilder.append(FROM).append(" ").append(from).append(" ");
    }
    if (!Strings.isNullOrEmpty(where)) {
      stringBuilder = stringBuilder.append(WHERE).append(" ").append(where).append(" ");
    }
    if (!Strings.isNullOrEmpty(orderBy)) {
      stringBuilder = stringBuilder.append(ORDER_BY).append(" ").append(orderBy).append(" ");
    }
    if (limit != null) {
      stringBuilder = stringBuilder.append(LIMIT).append(" ").append(limit).append(" ");
    }
    if (offset != null) {
      stringBuilder = stringBuilder.append(OFFSET).append(" ").append(offset).append(" ");
    }
    return stringBuilder.toString().trim();
  }
1207564
function buildWhereModel (name, value, alias) {
    // skip updefined values
    if (value === undefined) {
        return
    }
    // get id columns for model
    var idColumn = this.model.columnName('id')
    var originalIdColumn = this.model.columnName('originalId')
    // model column belongs to
    var model
    // column spec
    var spec
    // isDeleted where clause
    if (name === 'isDeleted') {
        // if value is null do nothing
        if (value === null) {
            return
        }
        // change column name to real column name (d)
        name = 'd'
    }
    // join column where clause
    if (name.match(/\./)) {
        var [prefix, column] = name.split('.')
        // prefix is for join
        if (this.joinRelations[prefix]) {
            // get join
            var join = this.joinRelations[prefix]
            // get relation
            var relation = this.model.relation(prefix)
            // set model for where clause
            model = relation.model
            // get column name from relation model
            name = model.columnName(column, true)
            // get spec
            spec = model.columns[name]
            // get alias
            alias = join.relationAlias
        }
        // error
        else {
            throw new Error('invalid column name in where '+name)
        }
    }
    // where clause for column on primary model table
    else {
        // model is base model
        model = this.model
        // validate column name - throw error
        name = this.model.columnName(name, true)
        // get column spec
        spec = this.model.columns[name]
        // if value is set for only the first column then need to add join to
        // select the record that matches the value
        if (spec.firstOnly) {
            // get new alias for primary table
            alias = this.newAlias(this.table)
            // add join
            this.join.push( this.joinSql(this.table, alias, originalIdColumn, this.alias, originalIdColumn) )
        }
    }
    // if optional alias is not set then get table alias for model name
    if (!alias) {
        alias = this.getAlias(model.name)
    }
    // flag set to true if this is negated statement
    var isNot = false
    // every where statement will begin with the alias and column name
    var whereSql = `${alias}.${this.quoteName(name)}`
    // if value is a string then do a simple column = :value
    if (typeof value === 'string' || typeof value === 'number') {
        // get param name for value placeholder
        var paramName = this.newParam(name)
        // set value for param placeholder
        this.params[paramName] = value
        // create sql
        whereSql += spec.type === 'id' && this.model.binaryIds
            ? ` = UNHEX(:${paramName})`
            : ` = :${paramName}`
    }
    // if value is boolean then do column = 1|0
    else if (spec.type === 'boolean' && typeof value === 'boolean') {
        // get param name for value placeholder
        var paramName = this.newParam(name)
        // create sql
        whereSql += ` = ${value ? 1 : 0}`
    }
    // if value is array then do IN () query
    else if (Array.isArray(value)) {
        var placeholders = _.map(value, v => {
            // get param name for each placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = v
            // create placeholder
            return spec.type === 'id' && this.model.binaryIds
                ? `UNHEX(:${paramName})`
                : `:${paramName}`
        })
        // create sql
        whereSql += ` IN(${placeholders.join(', ')})`
    }
    // if value is null then do IF NULL
    else if (value === null) {
        // create sql
        whereSql += ' IS NULL'
    }
    // if value is object then it should be a match type and value
    else if (typeof value === 'object') {
        // get keys of object
        var keys = _.keys(value)
        // there should be only one key
        assert.equal(keys.length, 1, 'statement must have one comparison operator in where '+name)
        // get operator
        var operator = keys[0]
        // get value
        var operatorValue = value[operator]
        var operatorValueType = typeof operatorValue
        // validate operator value
        if (operatorValueType === 'object' && operator !== 'in' && operator !== 'between' && operator !== 'not') {
            // if value is array change the type from object to array
            if (Array.isArray(operatorValue)) {
                operatorValueType = 'array'
            }
            // throw error
            throw new Error(`${model.name} query error: invalid value type '${operatorValueType}' for operator '${operator}'`)
        }
        // if operator is not then need to get next level deeper
        if (operator === 'not') {
            // if value is null than do IF NULL
            if (operatorValue === null) {
                // create sql
                whereSql += ' IS NOT NULL'
                // add sql to list of where clauses
                this.where.push(whereSql)
                // TODO: refactor this
                return
            }
            else {
                // get keys of not object
                keys = _.keys(operatorValue)
                // there should be only one key
                assert.equal(keys.length, 1, 'statement must have one comparison operator in where '+name)
                // get operator
                operator = keys[0]
                // get value
                operatorValue = operatorValue[operator]
                // set flag to negate statement
                isNot = true
            }
        }
        // LIKE :value
        if (operator === 'like') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` LIKE :${paramName}`
        }
        // > : value
        else if (operator === 'gt') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` > :${paramName}`
        }
        // >= : value
        else if (operator === 'gte') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` >= :${paramName}`
        }
        // < : value
        else if (operator === 'lt') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` < :${paramName}`
        }
        // <= : value
        else if (operator === 'lte') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += ` <= :${paramName}`
        }
        else if (operator === 'between') {
            assert.ok(Array.isArray(operatorValue), 'between value must be array in where '+name)
            assert.equal(operatorValue.length, 2, 'between array must have 2 elements in where '+name)
            // get param name for value placeholder
            var paramName1 = this.newParam(name)
            // set value for param placeholder
            this.params[paramName1] = operatorValue[0]
            // get param name for value placeholder
            var paramName2 = this.newParam(name)
            // set value for param placeholder
            this.params[paramName2] = operatorValue[1]
            // create sql
            whereSql += ` BETWEEN :${paramName1} AND :${paramName2}`
        }
        else if (operator === 'in') {
            assert.ok(Array.isArray(operatorValue), 'in value must be array in where '+name)
            // get placeholder for each in value
            var placeholders = _.map(operatorValue, v => {
                // get param name for each placeholder
                var paramName = this.newParam(name)
                // set value for param placeholder
                this.params[paramName] = v
                // create placeholder
                return spec.type === 'id' && this.model.binaryIds
                    ? `UNHEX(:${paramName})`
                    : `:${paramName}`
            })
            // create sql
            whereSql += ` IN(${placeholders.join(', ')})`
        }
        // = : value
        else if (operator === 'eq') {
            // get param name for value placeholder
            var paramName = this.newParam(name)
            // set value for param placeholder
            this.params[paramName] = operatorValue
            // create sql
            whereSql += spec.type === 'id' && this.model.binaryIds
                ? ` = UNHEX(:${paramName})`
                : ` = :${paramName}`
        }
        // operator type not supported
        else {
            throw new Error('invalid operator '+operator+' in where '+name)
        }
    }
    // query type not supported
    else {
        throw new Error('invalid value type '+typeof value+' in where '+name)
    }

    // if this is NOT statement then wrap in negation
    if (isNot) {
        whereSql = '!('+whereSql+')'
    }

    // add sql to list of where clauses
    this.where.push(whereSql)
}
225284
public function select($tableName, $where = null, $afterWhere = '')
    {
        return $this->pdo->select($tableName, $where, $afterWhere);
    }
1229439
public function checkExistsWithMultipleWhere($whereValue = '', $whereField = 'id', $select = '*')
    {
        if (is_array($whereValue) && count($whereValue) > 0) {
            foreach ($whereValue as $key => $value) {
                if (is_array($value['value'])) {
                    $this->db->where($value['field'], $value['value'], self::OPERATOR_IS_IN);
                } else {
                    $this->db->where($value['field'], $value['value'], $value['operator']);
                }
            }
        } else {
            $this->db->where($whereField, $whereValue, self::OPERATOR_EQUAL_TO);
        }
        $this->db->get($this->table, NULL, $select);

        return (int) $this->db->count;
    }