Parse a Vector value for SQL-IN
548582
private AbstractExpression parseVectorExpression(VoltXMLElement exprNode) {
        ArrayList<AbstractExpression> args = new ArrayList<>();
        for (VoltXMLElement argNode : exprNode.children) {
            assert(argNode != null);
            // recursively parse each argument subtree (could be any kind of expression).
            AbstractExpression argExpr = parseExpressionNode(argNode);
            assert(argExpr != null);
            args.add(argExpr);
        }

        VectorValueExpression vve = new VectorValueExpression();
        vve.setValueType(VoltType.VOLTTABLE);
        vve.setArgs(args);
        return vve;
    }
261558
@Override
    public String readValue(String column, int line) throws TechnicalException {
        logger.debug("readValue: column:[{}] and line:[{}] ", column, line);
        String sqlRequest;
        try {
            final Path file = Paths.get(dataInPath + scenarioName + ".sql");
            sqlRequest = new String(Files.readAllBytes(file), Charset.forName(Constants.DEFAULT_ENDODING));
            sqlSanitized4readOnly(sqlRequest);
        } catch (final IOException e) {
            throw new TechnicalException(Messages.getMessage(TechnicalException.TECHNICAL_ERROR_MESSAGE) + e.getMessage(), e);
        }
        try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(sqlRequest); ResultSet rs = statement.executeQuery();) {
            if (line < 1) {
                return column;
            }
            while (rs.next() && rs.getRow() < line) {
            }
            logger.info("column: {}", column);
            return rs.getString(column);
        } catch (final SQLException e) {
            logger.error("error DBDataProvider.readValue({}, {})", column, line, e);
            return "";
        }
    }
262177
def match(value, query):
    
    if type(query) in [str, int, float, type(None)]:
        return value == query
    elif type(query) == dict and len(query.keys()) == 1:
        for op in query:
            if op == "$eq": return value == query[op]
            elif op == "$lt": return value < query[op]
            elif op == "$lte": return value <= query[op]
            elif op == "$gt": return value > query[op]
            elif op == "$gte": return value >= query[op]
            elif op == "$ne": return value != query[op]
            elif op == "$in": return value in query[op]
            elif op == "$nin": return value not in query[op]
            else: GeoQLError("Not a valid query operator: " + op)
    else:
        raise GeoQLError("Not a valid query: " + str(query))
395022
public long getInternalLong(ColumnInformation columnInfo) throws SQLException {
    if (lastValueWasNull()) {
      return 0;
    }
    try {
      switch (columnInfo.getColumnType()) {
        case FLOAT:
          Float floatValue = Float.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8));
          if (floatValue.compareTo((float) Long.MAX_VALUE) >= 1) {
            throw new SQLException(
                "Out of range value for column '" + columnInfo.getName() + "' : value "
                    + new String(buf, pos, length, StandardCharsets.UTF_8)
                    + " is not in Long range", "22003", 1264);
          }
          return floatValue.longValue();
        case DOUBLE:
          Double doubleValue = Double.valueOf(new String(buf, pos, length, StandardCharsets.UTF_8));
          if (doubleValue.compareTo((double) Long.MAX_VALUE) >= 1) {
            throw new SQLException(
                "Out of range value for column '" + columnInfo.getName() + "' : value "
                    + new String(buf, pos, length, StandardCharsets.UTF_8)
                    + " is not in Long range", "22003", 1264);
          }
          return doubleValue.longValue();
        case BIT:
          return parseBit();
        case TINYINT:
        case SMALLINT:
        case YEAR:
        case INTEGER:
        case MEDIUMINT:
        case BIGINT:
          long result = 0;
          boolean negate = false;
          int begin = pos;
          if (length > 0 && buf[begin] == 45) { //minus sign
            negate = true;
            begin++;
          }
          for (; begin < pos + length; begin++) {
            result = result * 10 + buf[begin] - 48;
          }
          //specific for BIGINT : if value > Long.MAX_VALUE , will become negative until -1
          if (result < 0) {
            //CONJ-399 : handle specifically Long.MIN_VALUE that has absolute value +1 compare to LONG.MAX_VALUE
            if (result == Long.MIN_VALUE && negate) {
              return Long.MIN_VALUE;
            }
            throw new SQLException(
                "Out of range value for column '" + columnInfo.getName() + "' for value "
                    + new String(buf, pos, length, StandardCharsets.UTF_8), "22003", 1264);
          }
          return (negate ? -1 * result : result);
        default:
          return Long.parseLong(new String(buf, pos, length, StandardCharsets.UTF_8));
      }

    } catch (NumberFormatException nfe) {
      //parse error.
      //if its a decimal retry without the decimal part.
      String value = new String(buf, pos, length, StandardCharsets.UTF_8);
      if (isIntegerRegex.matcher(value).find()) {
        try {
          return Long.parseLong(value.substring(0, value.indexOf(".")));
        } catch (NumberFormatException nfee) {
          //eat exception
        }
      }
      throw new SQLException(
          "Out of range value for column '" + columnInfo.getName() + "' : value " + value, "22003",
          1264);
    }
  }
885648
function parseVarInt(cursor) {
    var result = 0, byte;

    do {
        byte = cursor.readUInt8();

        result <<= 7;
        result |= byte & 0x7F;
    } while (byte & 0x80);

    return result;
}
385378
public void parse(final SelectStatement selectStatement) {
        if (!lexerEngine.skipIfEqual(SQLServerKeyword.OFFSET)) {
            return;
        }
        int offsetValue = -1;
        int offsetIndex = -1;
        if (lexerEngine.equalAny(Literals.INT)) {
            offsetValue = Integer.parseInt(lexerEngine.getCurrentToken().getLiterals());
        } else if (lexerEngine.equalAny(Symbol.QUESTION)) {
            offsetIndex = selectStatement.getParametersIndex();
            selectStatement.setParametersIndex(selectStatement.getParametersIndex() + 1);
        } else {
            throw new SQLParsingException(lexerEngine);
        }
        lexerEngine.nextToken();
        Limit limit = new Limit();
        if (lexerEngine.skipIfEqual(DefaultKeyword.FETCH)) {
            lexerEngine.nextToken();
            int rowCountValue = -1;
            int rowCountIndex = -1;
            lexerEngine.nextToken();
            if (lexerEngine.equalAny(Literals.INT)) {
                rowCountValue = Integer.parseInt(lexerEngine.getCurrentToken().getLiterals());
            } else if (lexerEngine.equalAny(Symbol.QUESTION)) {
                rowCountIndex = selectStatement.getParametersIndex();
                selectStatement.setParametersIndex(selectStatement.getParametersIndex() + 1);
            } else {
                throw new SQLParsingException(lexerEngine);
            }
            lexerEngine.nextToken();
            lexerEngine.nextToken();
            limit.setRowCount(new LimitValue(rowCountValue, rowCountIndex, false));
            limit.setOffset(new LimitValue(offsetValue, offsetIndex, true));
        } else {
            limit.setOffset(new LimitValue(offsetValue, offsetIndex, true));
        }
        selectStatement.setLimit(limit);
    }
1148423
public void parse(final InsertStatement insertStatement) {
        if (!lexerEngine.skipIfEqual(getCustomizedInsertKeywords())) {
            return;
        }
        lexerEngine.accept(DefaultKeyword.DUPLICATE);
        lexerEngine.accept(DefaultKeyword.KEY);
        lexerEngine.accept(DefaultKeyword.UPDATE);
        do {
            Column column = new Column(SQLUtil.getExactlyValue(lexerEngine.getCurrentToken().getLiterals()), insertStatement.getTables().getSingleTableName());
            if (shardingRule.isShardingColumn(column.getName(), column.getTableName())) {
                throw new SQLParsingException("INSERT INTO .... ON DUPLICATE KEY UPDATE can not support on sharding column, token is '%s', literals is '%s'.",
                        lexerEngine.getCurrentToken().getType(), lexerEngine.getCurrentToken().getLiterals());
            }
            basicExpressionParser.parse(insertStatement);
            lexerEngine.accept(Symbol.EQ);
            if (lexerEngine.skipIfEqual(DefaultKeyword.VALUES)) {
                lexerEngine.accept(Symbol.LEFT_PAREN);
                basicExpressionParser.parse(insertStatement);
                lexerEngine.accept(Symbol.RIGHT_PAREN);
            } else {
                lexerEngine.nextToken();
            }
        } while (lexerEngine.skipIfEqual(Symbol.COMMA));
    }
959998
private SQLExpression parseExpression(final SQLStatement sqlStatement) {
        String literals = lexerEngine.getCurrentToken().getLiterals();
        final int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - literals.length();
        final SQLExpression expression = getExpression(literals, sqlStatement);
        lexerEngine.nextToken();
        if (lexerEngine.skipIfEqual(Symbol.DOT)) {
            String property = lexerEngine.getCurrentToken().getLiterals();
            lexerEngine.nextToken();
            return skipIfCompositeExpression(sqlStatement)
                    ? new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition, lexerEngine.getCurrentToken().getEndPosition()))
                    : new SQLPropertyExpression(new SQLIdentifierExpression(literals), property);
        }
        if (lexerEngine.equalAny(Symbol.LEFT_PAREN)) {
            lexerEngine.skipParentheses(sqlStatement);
            skipRestCompositeExpression(sqlStatement);
            return new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition,
                    lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length()).trim());
        }
        return skipIfCompositeExpression(sqlStatement)
                ? new SQLIgnoreExpression(lexerEngine.getInput().substring(beginPosition, lexerEngine.getCurrentToken().getEndPosition())) : expression;
    }
942067
def _parse_row(self, i):
        
        row = self.data[i]
        for j in range(len(row)):
            self.data[i][j] = self._parse_value(self.data[i][j])
766943
def from_value(self, value):
        
        if value is None:
            sql_type = NVarCharType(size=1)
        else:
            sql_type = self._from_class_value(value, type(value))
        return sql_type
838890
public static String sqlValueToString(ResultSet rs, int index, int sqlType) throws SQLException {
        Class<?> requiredType = sqlTypeToJavaTypeMap.get(sqlType);
        if (requiredType == null) {
            throw new IllegalArgumentException("unknow java.sql.Types - " + sqlType);
        }

        return getResultSetValue(rs, index, requiredType);
    }
1100848
public static SqlParamsPairs handleIn(String sql, Object[] params){
		
		//split with question mark placeholder
		String[] sqlPieces = sql.split("\\?");
		
		//question mark placeholder list
		String[] questionPlaceholders;
		if(sql.endsWith("?")){
			questionPlaceholders = new String[sqlPieces.length];
		}else{
			questionPlaceholders = new String[sqlPieces.length-1];
		}
		for(int i=0;i<questionPlaceholders.length;i++){
			questionPlaceholders[i]="?";
		}
		
		List<Object> plist = new ArrayList<Object>();
		for(int i=0; i<params.length; i++){
			Object p = params[i];
			if(p.getClass().equals(ArrayList.class)){
				
				//change ? => (?,?,?...)
				//change list to objects
				StringBuilder sb = new StringBuilder();
				sb.append("(");
				ArrayList inParams = (ArrayList)p;
				for(int j=0;j<inParams.size();j++){
					if(j!=0){
						sb.append(",");
					}
					sb.append("?");
					//split list to objects
					plist.add(inParams.get(j));
				}
				sb.append(")");
				questionPlaceholders[i] = sb.toString();
				
			}else{
				plist.add(p);
			}
		}
		
		//join sql
		StringBuilder sqlsb = new StringBuilder();
		for(int i=0;i<sqlPieces.length;i++){
			
			sqlsb.append(sqlPieces[i]);
			if(i<questionPlaceholders.length){
				sqlsb.append(questionPlaceholders[i]);
			}
		}
		
		
		SqlParamsPairs spPairs = new SqlParamsPairs(sqlsb.toString(),plist.toArray());
		
		return spPairs;
	}
313236
function _query($sql,$inputarr=false)
	{
		if (is_array($inputarr)) {
			$i = 0;
			if (is_array($sql)) {
				foreach($inputarr as $v) {
					$arr['bind'.$i++] = $v;
				}
			} else {
				// Need to identify if the ? is inside a quoted string, and if
				// so not use it as a bind variable
				preg_match_all('/".*\??"|\'.*\?.*?\'/', $sql, $matches);
				foreach($matches[0] as $qmMatch){
					$qmReplace = str_replace('?', '-QUESTIONMARK-', $qmMatch);
					$sql = str_replace($qmMatch, $qmReplace, $sql);
				}

				// Replace parameters if any were found
				$sqlarr = explode('?',$sql);
				if(count($sqlarr) > 1) {
					$sql = $sqlarr[0];

					foreach ($inputarr as $k => $v) {
						$sql .= ":$k" . $sqlarr[++$i];
					}
				}

				$sql = str_replace('-QUESTIONMARK-', '?', $sql);
			}
		}
		return ADODB_oci8::_query($sql,$inputarr);
	}
983344
@ScalarFunction(value = "like", hidden = true)
    @LiteralParameters("x")
    @SqlType(StandardTypes.BOOLEAN)
    public static boolean likeVarchar(@SqlType("varchar(x)") Slice value, @SqlType(LikePatternType.NAME) Regex pattern)
    {
        // Joni can infinite loop with UTF8Encoding when invalid UTF-8 is encountered.
        // NonStrictUTF8Encoding must be used to avoid this issue.
        byte[] bytes = value.getBytes();
        return regexMatches(pattern, bytes);
    }
4916
function convertRawVariant(rawColumnValue, column, context)
{
  var ret;

  // if the input is a non-empty string, convert it to a json object
  if (Util.string.isNotNullOrEmpty(rawColumnValue))
  {
    try
    {
      ret = eval("(" + rawColumnValue + ")");
    }
    catch (parseError)
    {
      // TODO: log the error

      // throw the error
      throw parseError;
    }
  }

  return ret;
}
1253580
def fetchvalue(self, sql: str, *args) -> Optional[Any]:
        """"""
        row = self.fetchone(sql, *args)
        if row is None:
            return None
        return row[0]
805142
def parse_query_value(combined_value):
    """"""
    split = len(combined_value) - len(combined_value.lstrip('<>='))
    operator = combined_value[:split]
    if operator == '':
        operator = '='
    try:
        operator_func = search_operators[operator]
    except KeyError:
        raise ValueError(
            'Numeric query should start with operator, choose from %s' %
            ', '.join(search_operators.keys()))
    value = combined_value[split:].strip()
    return operator_func, value