collect all extrassions of a set of expression types appearing anywhere
in a select statement and its subselects, etc.
967818
static void collectAllExpressions(HsqlList set, Expression e,
                                      OrderedIntHashSet typeSet,
                                      OrderedIntHashSet stopAtTypeSet) {

        if (e == null) {
            return;
        }

        if (stopAtTypeSet.contains(e.opType)) {
            return;
        }

        for (int i = 0; i < e.nodes.length; i++) {
            collectAllExpressions(set, e.nodes[i], typeSet, stopAtTypeSet);
        }

        if (typeSet.contains(e.opType)) {
            set.add(e);
        }

        if (e.subQuery != null && e.subQuery.queryExpression != null) {
            e.subQuery.queryExpression.collectAllExpressions(set, typeSet,
                    stopAtTypeSet);
        }
    }
157645
def select_values(statement, build_arg = nil)
    select(statement, build_arg).collect { |row| row.values }
  end
663240
def root_expressions

      roots = @expressions.select { |e| e.h.parent_id == nil }

      roots = roots.each_with_object({}) { |e, h|
        h["#{e.h.fei['expid']}__#{e.h.fei['subid']}"] = e
      }

      roots.keys.sort.collect { |k| roots[k] }
    end
980569
public static SQLQuery<Tuple> selectDistinct(Expression<?>... exprs) {
        return new SQLQuery<Void>().select(exprs).distinct();
    }
142191
private AbstractExpression optimizeInExpressions(AbstractExpression expr) {
        ExpressionType exprType = expr.getExpressionType();
        if (ExpressionType.CONJUNCTION_AND == exprType || ExpressionType.CONJUNCTION_OR == exprType) {
            AbstractExpression optimizedLeft = optimizeInExpressions(expr.getLeft());
            expr.setLeft(optimizedLeft);
            AbstractExpression optimizedRight = optimizeInExpressions(expr.getRight());
            expr.setRight(optimizedRight);
            return expr;
        }

        if (ExpressionType.COMPARE_EQUAL != exprType) {
            return expr;
        }

        assert(expr instanceof ComparisonExpression);
        if (((ComparisonExpression)expr).getQuantifier() != QuantifierType.ANY) {
            return expr;
        }

        /*
         * Verify that an IN expression can be safely converted to an EXISTS one
         * IN (SELECT" forms e.g. "(A, B) IN (SELECT X, Y, FROM ...) =>
         * EXISTS (SELECT 42 FROM ... AND|WHERE|HAVING A=X AND|WHERE|HAVING B=Y)
         */
        AbstractExpression inColumns = expr.getLeft();
        if (inColumns instanceof SelectSubqueryExpression) {
            // If the left child is a (SELECT ...) expression itself we can't convert it
            // to the EXISTS expression because the mandatory run time scalar check -
            // (expression must return a single row at most)
            return expr;
        }

        // The right hand operand of the equality operation must be a SELECT statement
        AbstractExpression rightExpr = expr.getRight();
        if (!(rightExpr instanceof SelectSubqueryExpression)) {
            return expr;
        }

        SelectSubqueryExpression subqueryExpr = (SelectSubqueryExpression) rightExpr;
        AbstractParsedStmt subquery = subqueryExpr.getSubqueryStmt();
        if (!(subquery instanceof ParsedSelectStmt)) {
            return expr;
        }

        ParsedSelectStmt selectStmt = (ParsedSelectStmt) subquery;

        // Must not have OFFSET or LIMIT set
        // EXISTS (select * from T where T.X = parent.X order by T.Y offset 10 limit 5)
        //      seems to require 11 matches
        // parent.X IN (select T.X from T order by T.Y offset 10 limit 5)
        //      seems to require 1 match that has exactly 10-14 rows (matching or not) with lesser or equal values of Y.
        if (selectStmt.hasLimitOrOffset()) {
            return expr;
        }

        ParsedSelectStmt.rewriteInSubqueryAsExists(selectStmt, inColumns);
        subqueryExpr.resolveCorrelations();
        AbstractExpression existsExpr = new OperatorExpression();
        existsExpr.setExpressionType(ExpressionType.OPERATOR_EXISTS);
        existsExpr.setLeft(subqueryExpr);
        return optimizeExistsExpression(existsExpr);
    }
1302267
private static List<FieldItem> collectSelectQueryFields(MySqlSelectQueryBlock sqlSelectQueryBlock) {
        return sqlSelectQueryBlock.getSelectList().stream().map(selectItem -> {
            FieldItem fieldItem = new FieldItem();
            fieldItem.setFieldName(selectItem.getAlias());
            fieldItem.setExpr(selectItem.toString());
            visitColumn(selectItem.getExpr(), fieldItem);
            return fieldItem;
        }).collect(Collectors.toList());
    }
1296717
private void gatherProperties(List<VariableElement> fields, Element element) {

    TypeElement typeElement = (TypeElement) element;
    TypeMirror superclass = typeElement.getSuperclass();
    Element mappedSuper = typeUtils.asElement(superclass);
    if (isMappedSuperOrInheritance(mappedSuper)) {
      gatherProperties(fields, mappedSuper);
    }

    List<VariableElement> allFields = ElementFilter.fieldsIn(element.getEnclosedElements());
    for (VariableElement field : allFields) {
      if (!ignoreField(field)) {
        fields.add(field);
      }
    }
  }
246313
def getAllIDs(cls, where=None, orderBy=None):
        
        (sql, fields) = cls._prepareSQL("SELECTALL", where,
                                        cls._sqlPrimary, orderBy=orderBy)
        curs = cls.cursor()
        curs.execute(sql)
        # We might start eating memory at this point
        rows = curs.fetchall()
        curs.close()
        result = []
        idPositions = [fields.index(key) for key in cls._sqlPrimary]
        for row in rows:
            ids = [row[pos] for pos in idPositions]
            if len(idPositions) > 1:
                ids = tuple(ids)
            else:
                ids = ids[0]
            result.append((ids))
        return result
39113
def _validate_select_where(self):
        
        # check that there's either a =, a IN or a CONTAINS (collection)
        # relationship with a primary key or indexed field. We also allow
        # custom indexes to be queried with any operator (a difference
        # between a secondary index)
        equal_ops = [self.model._get_column_by_db_name(w.field) \
                     for w in self._where if not isinstance(w.value, Token)
                     and (isinstance(w.operator, EqualsOperator)
                          or self.model._get_column_by_db_name(w.field).custom_index)]
        token_comparison = any([w for w in self._where if isinstance(w.value, Token)])
        if not any(w.primary_key or w.has_index for w in equal_ops) and not token_comparison and not self._allow_filtering:
            raise QueryException(
                ('Where clauses require either  =, a IN or a CONTAINS '
                 '(collection) comparison with either a primary key or '
                 'indexed field. You might want to consider setting '
                 'custom_index on fields that you manage index outside '
                 'cqlengine.'))

        if not self._allow_filtering:
            # if the query is not on an indexed field
            if not any(w.has_index for w in equal_ops):
                if not any([w.partition_key for w in equal_ops]) and not token_comparison:
                    raise QueryException(
                        ('Filtering on a clustering key without a partition '
                         'key is not allowed unless allow_filtering() is '
                         'called on the queryset. You might want to consider '
                         'setting custom_index on fields that you manage '
                         'index outside cqlengine.'))
959064
def select(self):
        """"""
        # Try to match the asterisk, any or list of vars.
        if self.tokens.accept(grammar.select_any):
            return self.select_any()

        if self.tokens.accept(grammar.select_all):
            # The FROM after SELECT * is required.
            self.tokens.expect(grammar.select_from)
            return self.select_from()

        return self.select_what()
755788
function (sql) {
            var values = this.__opts.values;
            if (isArray(values) && !values.length) {
                return " ()";
            } else {
                return this._super(arguments);
            }
        }
218127
private Expression extractSideEffects(Expression expr) {
    if (expr.getConstantValue() instanceof Boolean) {
      return null;
    }
    switch (expr.getKind()) {
      case INFIX_EXPRESSION:
        {
          List<Expression> operands = ((InfixExpression) expr).getOperands();
          Expression lastOperand = operands.remove(operands.size() - 1);
          lastOperand = extractSideEffects(lastOperand);
          if (lastOperand != null) {
            operands.add(lastOperand);
          }
          if (operands.size() == 1) {
            return operands.remove(0);
          }
          return TreeUtil.remove(expr);
        }
      case PARENTHESIZED_EXPRESSION:
        {
          Expression sideEffects = extractSideEffects(
              ((ParenthesizedExpression) expr).getExpression());
          if (sideEffects != null) {
            return ParenthesizedExpression.parenthesize(sideEffects);
          }
          return null;
        }
      default:
        return null;
    }
  }
543847
private AggregationBuilder buildSelectAggregations(AggregationBuilder aggregationBuilder,
            SelectStatement selectStatement, EntityMetadata entityMetadata)
    {
        Expression expression = ((SelectClause) selectStatement.getSelectClause()).getSelectExpression();

        if (expression instanceof CollectionExpression)
        {
            aggregationBuilder = appendAggregation((CollectionExpression) expression, entityMetadata,
                    aggregationBuilder);
        }
        else
        {
            if (isAggregationExpression(expression) && checkIfKeyExists(expression.toParsedText()))
                aggregationBuilder.subAggregation(getMetricsAggregation(expression, entityMetadata));
        }
        return aggregationBuilder;
    }
411337
def select(table, index_track, field_name, op, value, includeMissing):
    '''
    '''
    result = []
    result_index = []
    counter = 0
    for row in table:
        if detect_fields(field_name, convert_to_dict(row)):
            final_value = get_value(row, field_name)
            if do_op(final_value, op, value):
                result.append(row)
                result_index.append(index_track[counter])
        else:
            if includeMissing:
                result.append(row)
                result_index.append(index_track[counter])
        counter += 1
    #table = result
    #index_track = result_index
    return (result, result_index)
263773
public static <T> SQLQuery<T> select(Expression<T> expr) {
        return new SQLQuery<Void>().select(expr);
    }
86050
def collect_and_execute_subfields(
        self,
        return_type: GraphQLObjectType,
        field_nodes: List[FieldNode],
        path: ResponsePath,
        result: Any,
    ) -> AwaitableOrValue[Dict[str, Any]]:
        """"""
        sub_field_nodes = self.collect_subfields(return_type, field_nodes)
        return self.execute_fields(return_type, result, path, sub_field_nodes)
840127
def selectcontains(table, field, value, complement=False):
    """"""

    return selectop(table, field, value, operator.contains,
                    complement=complement)