construct SQL string from expression node
498228
def expr_to_str(n, l=None):
    
    op = n[0]
    if op.startswith('_') and op.endswith('_'):
        op = op.strip('_')
        if op == 'var':
            return n[1]
        elif op == 'literal':
            if isinstance(n[1], basestring):
                return "'%s'" % n[1]
            return str(n[1])
        elif op == 'cast':
            return "(%s)::%s" % (expr_to_str(n[1]), n[2])
    elif op in '+-*/':
        return "(%s) %s (%s)" % (expr_to_str(n[1]), op, expr_to_str(n[2]))
    elif op == "extract":
        return "extract( %s from %s )" % (n[1], expr_to_str(n[2]))
    else:
        arg = ','.join(map(expr_to_str, n[1:]))
        return "%s(%s)" % (op, arg)
1346285
private String buildConstraintExpr(String device_name, String attribute, String event_name, String[] filters) {
        String str =
                "$domain_name == \'" + device_name.toLowerCase() + "/" +
                        attribute.toLowerCase() + "\'" + " and $event_name == \'" +
                        event_name + "\'";
        if (filters != null && filters.length != 0) {
            str += " and ((";
            for (String filter : filters)
                str += filter;
            str += " ) and $forced_event > 0.5 )";
        }
        return str;
    }
491964
public String getString(Object node, String expression) {
		return (String) evalXPath(expression, node, XPathConstants.STRING);
	}
685264
private void parseSQLConfig(final Node node, final ConfigSettings config)
	{

		String name, value;
		Node nnode;
		NodeList list = node.getChildNodes();

		int length = list.getLength();
		for (int i = 0; i < length; i++) {
			nnode = list.item(i);

			name = nnode.getNodeName().toUpperCase();
			if (name.equals(KEY_HOST)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_HOST, value);

			}
			else if (name.equals(KEY_DATABASE)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_DATABASE, value);

			}
			else if (name.equals(KEY_USER)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_USERNAME, value);

			}
			else if (name.equals(KEY_PASSWORD)) {

				value = nnode.getChildNodes().item(0).getNodeValue();
				config.setConfigParameter(ConfigurationKeys.SQL_PASSWORD, value);
			}
		}
	}
1094228
private void get(final StringBuilder sql) {
        sql.append("SELECT * FROM ").append(getName()).append(" WHERE ").append(JdbcRepositories.getDefaultKeyName()).append(" = ?");
    }
1210644
def split_expression_by_path(
    where, schema, output=None, var_to_columns=None, lang=Language
):
    
    if var_to_columns is None:
        var_to_columns = {v.var: schema.leaves(v.var) for v in where.vars()}
        output = wrap({schema.query_path[0]: []})
        if not var_to_columns:
            output["\\."] += [where]  # LEGIT EXPRESSIONS OF ZERO VARIABLES
            return output

    where_vars = where.vars()
    all_paths = set(c.nested_path[0] for v in where_vars for c in var_to_columns[v.var])

    if len(all_paths) == 0:
        output["\\."] += [where]
    elif len(all_paths) == 1:
        output[literal_field(first(all_paths))] += [
            where.map(
                {
                    v.var: c.es_column
                    for v in where.vars()
                    for c in var_to_columns[v.var]
                }
            )
        ]
    elif is_op(where, AndOp_):
        for w in where.terms:
            split_expression_by_path(w, schema, output, var_to_columns, lang=lang)
    else:
        Log.error("Can not handle complex where clause")

    return output
1111393
public static StringExpression groupConcat(Expression<String> expr) {
        return Expressions.stringOperation(SQLOps.GROUP_CONCAT, expr);
    }
902678
@SuppressWarnings("unchecked")
    private void concatSqlText(Node node, SqlInfo sqlInfo) {
        // 获取所有子节点，并分别将其使用StringBuilder拼接起来
        List<Node> nodes = node.selectNodes(ZealotConst.ATTR_CHILD);
        for (Node n: nodes) {
            if (ZealotConst.NODETYPE_TEXT.equals(n.getNodeTypeName())) {
                // 如果子节点node 是文本节点，则直接获取其文本
                sqlInfo.getJoin().append(n.getText());
            } else {
                throw new ContainXmlTagException("<text></text>标签中不能包含其他xml标签，只能是文本元素！");
            }
        }
    }
266688
function toStatement(node, ignore) {
  if (t.isStatement(node)) {
    return node;
  }

  var mustHaveId = false;
  var newType;

  if (t.isClass(node)) {
    mustHaveId = true;
    newType = "ClassDeclaration";
  } else if (t.isFunction(node)) {
    mustHaveId = true;
    newType = "FunctionDeclaration";
  } else if (t.isAssignmentExpression(node)) {
    return t.expressionStatement(node);
  }

  if (mustHaveId && !node.id) {
    newType = false;
  }

  if (!newType) {
    if (ignore) {
      return false;
    } else {
      throw new Error("cannot turn " + node.type + " to a statement");
    }
  }

  node.type = newType;

  return node;
}
199339
def _query(_node_id, value=None, **kw):
    ""
    query_result = []
    try:
        query_result = db.execute(text(fetch_query_string('select_query_from_node.sql')), **kw).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s, %s", err, kw)
        return value
    #current_app.logger.debug("queries kw: %s", kw)
    #current_app.logger.debug("queries value: %s", value)
    current_app.logger.debug("queries: %s", query_result)
    if query_result:
        values = []
        for query_name in [x['name'] for x in query_result]:
            if query_name:
                result = []
                try:
                    current_app.logger.debug("query_name: %s", query_name)
                    #current_app.logger.debug("kw: %s", kw)
                    # Query string can be insert or select here
                    #statement = text(fetch_query_string(query_name))
                    #params = [x.key for x in statement.params().get_children()]
                    #skw = {key: kw[key] for key in params}
                    #result = db.execute(statement, **skw)
                    result = db.execute(text(fetch_query_string(query_name)), **kw)
                    current_app.logger.debug("result query: %s", result.keys())
                except (DatabaseError, StatementError) as err:
                    current_app.logger.error("DatabaseError (%s) %s: %s", query_name, kw, err)
                if result and result.returns_rows:
                    result = result.fetchall()
                    #values.append(([[dict(zip(result.keys(), x)) for x in result]], result.keys()))
                    #values.append((result.fetchall(), result.keys()))
                    #current_app.logger.debug("fetchall: %s", values)
                    if len(result) == 0:
                        values.append(([], []))
                    else:
                        current_app.logger.debug("result: %s", result)
                        # There may be more results, but only interested in the
                        # first one. Use the older rowify method for now.
                        # TODO: use case for rowify?
                        values.append(rowify(result, [(x, None) for x in result[0].keys()]))
                        #current_app.logger.debug("fetchone: %s", values)
        value = values
    #current_app.logger.debug("value: %s", value)
    return value
425892
@Override
    protected AstNode parseCreateViewStatement( DdlTokenStream tokens,
                                                AstNode parentNode ) throws ParsingException {
        assert tokens != null;
        assert parentNode != null;

        markStartOfStatement(tokens);
        // CREATE [OR REPLACE]
        // [[NO] FORCE] VIEW [schema.] view
        // [ ( { alias [ inline_constraint... ]
        // | out_of_line_constraint
        // }
        // [, { alias [ inline_constraint...]
        // | out_of_line_constraint
        // }
        // ]
        // )
        // | object_view_clause
        // | XMLType_view_clause
        // ]
        // AS subquery [ subquery_restriction_clause ] ;

        // NOTE: the query expression along with the CHECK OPTION clause require no SQL statement terminator.
        // So the CHECK OPTION clause will NOT

        String stmtType = "CREATE";
        tokens.consume("CREATE");
        if (tokens.canConsume("OR", "REPLACE")) {
            stmtType = stmtType + SPACE + "OR REPLACE";
        } else if (tokens.canConsume("NO", "FORCE")) {
            stmtType = stmtType + SPACE + "NO FORCE";
        } else if (tokens.canConsume("FORCE")) {
            stmtType = stmtType + SPACE + "FORCE";
        }

        tokens.consume("VIEW");
        stmtType = stmtType + SPACE + "VIEW";

        String name = parseName(tokens);

        AstNode createViewNode = nodeFactory().node(name, parentNode, TYPE_CREATE_VIEW_STATEMENT);

        // CONSUME COLUMNS
        parseColumnNameList(tokens, createViewNode, TYPE_COLUMN_REFERENCE);

        // (object_view_clause)
        //
        // OF [ schema. ] type_name
        // { WITH OBJECT IDENTIFIER
        // { DEFAULT | ( attribute [, attribute ]... ) }
        // | UNDER [ schema. ] superview
        // }
        // ( { out_of_line_constraint
        // | attribute { inline_constraint }...
        // } [, { out_of_line_constraint
        // | attribute { inline_constraint }...
        // }
        // ]...
        // )

        // (XMLType_view_clause)
        //
        // OF XMLTYPE [ XMLSchema_spec ]
        // WITH OBJECT IDENTIFIER
        // { DEFAULT | ( expr [, expr ]...) }

        // Basically, if next token matches "OF", then parse until token matches "AS"

        if (tokens.matches("OF")) {
            do {
                tokens.consume();
            } while (!tokens.matches("AS"));
        }

        tokens.consume("AS");

        String queryExpression = parseUntilTerminator(tokens);

        createViewNode.setProperty(CREATE_VIEW_QUERY_EXPRESSION, queryExpression);

        markEndOfStatement(tokens, createViewNode);

        return createViewNode;
    }
508146
private void selectExpressions(ParserString raw, Select select) throws SQLParserException {
	Expression exp = null;
	do {
	    raw.removeSpace();

	    exp = expression(raw);
	    if (exp == null) throw new SQLParserException("missing expression in select part of query");
	    raw.removeSpace();
	    if (raw.forwardIfCurrent("as ")) {
		String alias = identifier(raw, new RefBooleanImpl(false));
		if (alias == null) throw new SQLParserException("missing alias in select part");
		exp.setAlias(alias);
	    }
	    else {
		int start = raw.getPos();
		RefBoolean hb = new RefBooleanImpl(false);
		String alias = identifier(raw, hb);
		if (!hb.toBooleanValue() && "from".equalsIgnoreCase(alias)) raw.setPos(start);
		else if (alias != null) exp.setAlias(alias);
	    }
	    select.addSelectExpression(exp);
	    raw.removeSpace();
	}
	while (raw.forwardIfCurrent(','));

    }
590822
def _condition_as_sql(self, qn, connection):
        '''
        
        '''
        def escape(value):
            if isinstance(value, bool):
                value = str(int(value))
            if isinstance(value, six.string_types):
                # Escape params used with LIKE
                if '%' in value:
                    value = value.replace('%', '%%')
                # Escape single quotes
                if "'" in value:
                    value = value.replace("'", "''")
                # Add single quote to text values
                value = "'" + value + "'"
            return value

        sql, param = self.condition.query.where.as_sql(qn, connection)
        param = map(escape, param)

        return sql % tuple(param)
1186059
WrappedStatement compile(String sql) throws SQLException {
    WrappedStatement ws;
    if (! isEnabled(Option.REUSE_STATEMENTS)) {
      ws = new WrappedStatement(connection.prepareStatement(sql), false);
    }
    else {
      if (pool == null) {
        pool = new IdentityHashMap<>();
      }
      String sqlI = sql.intern();
      ws = pool.get(sqlI);
      if (ws == null) {
        ws =  new WrappedStatement(connection.prepareStatement(sql), true);
        pool.put(sqlI, ws);
      }
    }
    return ws;
  }
28006
public String createQueryStringFromNode(Node node, @Nullable Class<?> domainType) {
		return createQueryStringFromNode(node, 0, domainType);
	}
263773
public static <T> SQLQuery<T> select(Expression<T> expr) {
        return new SQLQuery<Void>().select(expr);
    }
957491
def from_db_value(self, value, expression, connection, context):
        
        if value is None:
            return value
        return json_decode(value)