:param where: EXPRESSION TO INSPECT
    :param schema: THE SCHEMA
    :param output:
    :param var_to_depth: MAP FROM EACH VARIABLE NAME TO THE DEPTH
    :return:
165438
def split_expression_by_depth(where, schema, output=None, var_to_depth=None):
    
    """
    It is unfortunate that ES can not handle expressions that
    span nested indexes.  This will split your where clause
    returning {"and": [filter_depth0, filter_depth1, ...]}
    """
    vars_ = where.vars()

    if var_to_depth is None:
        if not vars_:
            return Null
        # MAP VARIABLE NAMES TO HOW DEEP THEY ARE
        var_to_depth = {
            v.var: max(len(c.nested_path) - 1, 0) for v in vars_ for c in schema[v.var]
        }
        all_depths = set(var_to_depth.values())
        if len(all_depths) == 0:
            all_depths = {0}
        output = wrap([[] for _ in range(MAX(all_depths) + 1)])
    else:
        all_depths = set(var_to_depth[v.var] for v in vars_)

    if len(all_depths) == 1:
        output[first(all_depths)] += [where]
    elif is_op(where, AndOp_):
        for a in where.terms:
            split_expression_by_depth(a, schema, output, var_to_depth)
    else:
        Log.error("Can not handle complex where clause")

    return output
974628
def _where_terms(master, where, schema):
    
    if is_data(where):
        if where.term:
            # MAP TERM
            try:
                output = _map_term_using_schema(master, [], where.term, schema.edges)
                return output
            except Exception as e:
                Log.error("programmer problem?", e)
        elif where.terms:
            # MAP TERM
            output = FlatList()
            for k, v in where.terms.items():
                if not is_container(v):
                    Log.error("terms filter expects list of values")
                edge = schema.edges[k]
                if not edge:
                    output.append({"terms": {k: v}})
                else:
                    if is_text(edge):
                        # DIRECT FIELD REFERENCE
                        return {"terms": {edge: v}}
                    try:
                        domain = edge.getDomain()
                    except Exception as e:
                        Log.error("programmer error", e)
                    fields = domain.dimension.fields
                    if is_data(fields):
                        or_agg = []
                        for vv in v:
                            and_agg = []
                            for local_field, es_field in fields.items():
                                vvv = vv[local_field]
                                if vvv != None:
                                    and_agg.append({"term": {es_field: vvv}})
                            or_agg.append({"and": and_agg})
                        output.append({"or": or_agg})
                    elif is_list(fields) and len(fields) == 1 and is_variable_name(fields[0]):
                        output.append({"terms": {fields[0]: v}})
                    elif domain.partitions:
                        output.append({"or": [domain.getPartByKey(vv).esfilter for vv in v]})
            return {"and": output}
        elif where["or"]:
            return {"or": [unwrap(_where_terms(master, vv, schema)) for vv in where["or"]]}
        elif where["and"]:
            return {"and": [unwrap(_where_terms(master, vv, schema)) for vv in where["and"]]}
        elif where["not"]:
            return {"not": unwrap(_where_terms(master, where["not"], schema))}
    return where
959872
def extract_fields(cls, schema):
        
        # -- BASED-ON: parse.Parser._generate_expression()
        for part in parse.PARSE_RE.split(schema):
            if not part or part == '{{' or part == '}}':
                continue
            elif part[0] == '{':
                # this will be a braces-delimited field to handle
                yield cls.parse(part)
272902
def dump(schema):
    
    result = {}

    for name, _ in iteritems(schema.getschemas()):

        if hasattr(schema, name):
            val = getattr(schema, name)

            if isinstance(val, DynamicValue):
                val = val()

            if isinstance(val, Schema):
                val = dump(val)

            result[name] = val

    return result
208237
def CaptureVariable(self, value, depth, limits, can_enqueue=True):
    """"""
    try:
      return self.CaptureVariableInternal(value, depth, limits, can_enqueue)
    except BaseException as e:  # pylint: disable=broad-except
      return {
          'status': {
              'isError': True,
              'refersTo': 'VARIABLE_VALUE',
              'description': {
                  'format': ('Failed to capture variable: $0'),
                  'parameters': [str(e)]
              }
          }
      }
669285
def solve_var(expr, vars):
    """"""
    try:
        return Result(structured.resolve(vars, expr.value), ())
    except (KeyError, AttributeError) as e:
        # Raise a better exception for accessing a non-existent member.
        raise errors.EfilterKeyError(root=expr, key=expr.value, message=e,
                                     query=expr.source)
    except (TypeError, ValueError) as e:
        # Raise a better exception for what is probably a null pointer error.
        if vars.locals is None:
            raise errors.EfilterNoneError(
                root=expr, query=expr.source,
                message="Trying to access member %r of a null." % expr.value)
        else:
            raise errors.EfilterTypeError(
                root=expr, query=expr.source,
                message="%r (vars: %r)" % (e, vars))
    except NotImplementedError as e:
        raise errors.EfilterError(
            root=expr, query=expr.source,
            message="Trying to access member %r of an instance of %r." %
            (expr.value, type(vars)))
1292601
def build_where_clause(mappings, operator='AND'):
        
        where_clause_mappings = {}
        where_clause_mappings.update(mappings)

        where_clause = 'WHERE ' + ' {} '.format(operator).join(
            '{k} = {v}'.format(k=k, v='"{}"'.format(v) if isinstance(v, basestring) else v)
            for k, v in where_clause_mappings.iteritems()
        )
        return where_clause
691631
def lookup(parser, var, context, resolve=True, apply_filters=True):
    
    if resolve:
        try:
            return Variable(var).resolve(context)
        except VariableDoesNotExist:
            if apply_filters and var.find('|') > -1:
                return parser.compile_filter(var).resolve(context)
            return Constant(var)
        except TypeError:
            # already resolved
            return var
    return var
725223
def get_expr(self, ctx):
        
        varname = ctx.lookup_variable(self.varname)
        if varname is None:
            val = ctx.lookup_constant(self.varname)
            if val:
                try:
                    return val.generate_code(ctx)
                except AttributeError:
                    return val
            raise MuvError(
                "Undeclared identifier '%s'." % self.varname,
                position=self.position
            )
        if len(self.indexing) == 0:
            return "{var} @".format(
                var=varname,
            )
        if len(self.indexing) == 1:
            return "{var} @ {idx} []".format(
                var=varname,
                idx=self.indexing[0],
            )
        return (
            "{var} @ {{ {idx} }}list array_nested_get".format(
                var=varname,
                idx=" ".join(str(x) for x in self.indexing),
            )
        )
1041201
def _process_schema(self, schema_dict, validators):
        
        schema_flat = util.flatten(schema_dict)

        for key, expression in schema_flat.items():
            try:
                schema_flat[key] = syntax.parse(expression, validators)
            except SyntaxError as e:
                # Tack on some more context and rethrow.
                error = str(e) + ' at node \'%s\'' % key
                raise SyntaxError(error)
        return schema_flat
484540
def sparql_query(self, query, flush=None, limit=None):
        
        return self.find_statements(query, language='sparql', type='tuples',
            flush=flush, limit=limit)
512692
def generate_schema_mapping(resolver, schema_uri, depth=1):
    
    visitor = SchemaVisitor({'$ref': schema_uri}, resolver)
    return _generate_schema_mapping(visitor, set(), depth)
215636
def _nest_wheres_for_scope(self, query, where_counts):
        
        # Here, we totally remove all of the where clauses since we are going to
        # rebuild them as nested queries by slicing the groups of wheres into
        # their own sections. This is to prevent any confusing logic order.
        wheres = query.wheres

        query.wheres = []

        # We will take the first offset (typically 0) of where clauses and start
        # slicing out every scope's where clauses into their own nested where
        # groups for improved isolation of every scope's added constraints.
        previous_count = where_counts.pop(0)

        for where_count in where_counts:
            query.wheres.append(
                self._slice_where_conditions(
                    wheres, previous_count, where_count - previous_count
                )
            )

            previous_count = where_count
164310
function getSchema(connection) {
  return runQuery(SCHEMA_SQL_V1, connection)
    .then(queryResult => formatSchemaQueryResults(queryResult))
    .catch(() =>
      runQuery(SCHEMA_SQL_V0, connection).then(queryResult =>
        formatSchemaQueryResults(queryResult)
      )
    );
}
818809
def _nest_variable(v, check_records=False):
    
    if (check_records and is_cwl_record(v) and len(v["id"].split("/")) > 1 and
         v.get("type", {}).get("type") == "array"):
        return v
    else:
        v = copy.deepcopy(v)
        v["type"] = {"type": "array", "items": v["type"]}
        return v
252022
def get_vars_in_expression(source):
    ''''''

    import compiler
    from compiler.ast import Node

    ##
    # @brief Internal recursive function.
    # @param node An AST parse Node.
    # @param var_list Input list of variables.
    # @return An updated list of variables.
    def get_vars_body(node, var_list=[]):
        if isinstance(node, Node):
            if node.__class__.__name__ == 'Name':
                for child in node.getChildren():
                    if child not in var_list:
                        var_list.append(child)
            for child in node.getChildren():
                if isinstance(child, Node):
                    for child in node.getChildren():
                        var_list = get_vars_body(child, var_list)
                    break

        return var_list

    return get_vars_body(compiler.parse(source))
941443
def parse_condition(self, schema, name, v):
        

        S = schema
        col = S.get_column(name)
        condition = None

        if col is not None:  # can create condition
            if isinstance(v, (str, unicode)):
                if v.startswith('>='):
                    condition = (col >= eval(v[2:].strip()))
                elif v.startswith('>'):
                    condition = (col > eval(v[1:].strip()))
                elif v.startswith('<='):
                    condition = (col <= eval(v[2:].strip()))
                elif v.startswith('<'):
                    condition = (col < eval(v[1:].strip()))
                elif v.startswith('='):
                    condition = (col == eval(v[1:].strip()))
                elif v.startswith('!='):
                    condition = (col != eval(v[2:].strip()))
                elif v.startswith('like'):
                    condition = col.like(v[4:].strip())
                elif v.startswith('between'):
                    _v = eval(v[7:].strip())
                    if not isinstance(_v, (tuple, list)):
                        raise ValueError("Between operation should be a list, but {!r} found".format(v))
                    condition = (col.between(*_v))
                elif v.startswith('in'):
                    condition = (col.in_(eval(v[2:].strip())))
                else:
                    if '%' in v:  # like
                        condition = col.like(v)
                    else:
                        condition = (col == v)
            elif isinstance(v, (tuple, list)):
                condition = (col.in_(v))
            else:
                condition = (col == v)
        return condition