Rewrite the named statement and parameters to positional.

Example:
- before:
- statement: SELECT * FROM foo WHERE bar = :bar
- parameters: array()
- after:
- statement: SELECT * FROM foo WHERE bar = ?
- parameters: array(':bar' => array(1))
439557
private function rewrite()
    {
        // Current positional parameter.
        $positionalParameter = 1;

        // TRUE if we are in a literal section else FALSE.
        $literal = false;

        // The statement length.
        $statementLength = strlen($this->statement);

        // Iterate each statement char.
        for ($placeholderPos = 0; $placeholderPos < $statementLength; $placeholderPos++) {

            // Switch the literal flag if the current statement char is a literal delimiter.
            if (in_array($this->statement[$placeholderPos], array('\'', '"'))) {
                $literal = !$literal;
            }

            // Check if we are not in a literal section and the current statement char is a double colon.
            if (!$literal && $this->statement[$placeholderPos] === ':') {

                // Determine placeholder length.
                $placeholderLength = 1;
                while (isset($this->statement[$placeholderPos + $placeholderLength])
                    && $this->isValidPlaceholderCharacter($this->statement[$placeholderPos + $placeholderLength])) {
                    $placeholderLength++;
                }

                // Extract placeholder from the statement.
                $placeholder = substr($this->statement, $placeholderPos, $placeholderLength);

                // Initialize rewrites parameters.
                if (!isset($this->parameters[$placeholder])) {
                    $this->parameters[$placeholder] = array();
                }

                // Rewrites parameter.
                $this->parameters[$placeholder][] = $positionalParameter;

                // Rewrite statement.
                $this->statement = substr($this->statement, 0, $placeholderPos).
                    '?'.
                    substr($this->statement, $placeholderPos + $placeholderLength);

                // Decrement statement length.
                $statementLength = $statementLength - $placeholderLength + 1;

                // Increment position parameter.
                $positionalParameter++;
            }
        }
    }
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;
	}
258753
def p_statement_call(p):
    
    if len(p) > 2 and p[2] is None:
        p[0] = None
    elif len(p) == 2:
        entry = SYMBOL_TABLE.get_entry(p[1])
        if not entry or entry.class_ in (CLASS.label, CLASS.unknown):
            p[0] = make_label(p[1], p.lineno(1))
        else:
            p[0] = make_sub_call(p[1], p.lineno(1), make_arg_list(None))
    else:
        p[0] = make_sub_call(p[1], p.lineno(1), p[2])
99403
static Object[] paramsForStatement(AdHocPlannedStatement statement, Object[] userparams) {
        // When there are no user-provided parameters, statements may have parameterized constants.
        if (userparams.length > 0) {
            return userparams;
        } else {
            return statement.extractedParamArray();
        }
    }
356071
function prepare($statement = null, array $placeholders = null) {
		$this->dbh !== null or $this->setup();

		if ($placeholders !== null) {
			$consts = [];
			foreach ($placeholders as $key => $val) {
				$consts["[$key]"] = $val;
			}

			return \fenrir\MysqlStatement::instance($this->dbh, strtr($statement, $consts));
		}
		else { // placeholders === null
			return \fenrir\MysqlStatement::instance($this->dbh, $statement);
		}
	}
715666
private static function getPositionalPlaceholderPositions(string $statement) : array
    {
        return self::collectPlaceholders(
            $statement,
            '?',
            self::POSITIONAL_TOKEN,
            static function (string $_, int $placeholderPosition, int $fragmentPosition, array &$carry) : void {
                $carry[] = $placeholderPosition + $fragmentPosition;
            }
        );
    }
1294634
def p_statement_foreach(p):
    ''
    if p[6] is None:
        p[0] = ast.Foreach(p[3], None, p[5], p[8], lineno=p.lineno(1))
    else:
        p[0] = ast.Foreach(p[3], p[5], p[6], p[8], lineno=p.lineno(1))
616554
function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
    {
        $operatorValue = str_replace( "\n",
                                      "<br />",
                                      $operatorValue );
    }
1076229
def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil)
      exec_query(sql, name, binds)
    end
340501
function sqlParams(sql, params)
{
  var args = [];

  var keys = sql.match(/@\w+/g);
  var aKeys = sql.match(/\$\d+/g);

  if (keys && aKeys)
    throw new Error(
      'Cannot use both array-style and object-style parametric values');

  // Array-style (native)
  if (aKeys) {
    return { text: sql, values: params };
  }

  // No params
  if (!keys) {
    return { text: sql, values: [] };
  }

  var n = 1;
  keys.forEach(function(key) {
    key = key.substr(1);
    var val = params[key];
    if (val === undefined)
      throw new Error('No value for @' + key + ' provided');
    args.push(val);
    sql = sql.replace('@' + key, '$' + n++);
  });

  return { text: sql, values: args };
}
759298
public function query($query_with_placeholders, $named_parameters = []) {
            Event::dispatch(EventData::forBefore(Event::BEFORE_QUERY, '', $named_parameters, $query_with_placeholders), $named_parameters);
            try {
                $stmt = $this->prepareStatement($query_with_placeholders, $named_parameters);
                $stmt->execute();
            } catch (Exception $ex) {
                Event::dispatch(EventData::forException($ex, $query_with_placeholders, $named_parameters));
                throw new QueryException($ex->getMessage(), $ex->getCode(), $ex);
            }

            Event::dispatch(EventData::forAfter(Event::AFTER_QUERY, null, $named_parameters, $query_with_placeholders, $stmt->rowCount()));

            return $this->fetch($stmt);
        }
333229
private Statement handleTranslationWithPlaceholders(
      MsgNode msg,
      ImmutableList<SoyPrintDirective> escapingDirectives,
      Expression soyMsgParts,
      Expression locale,
      MsgPartsAndIds partsAndId) {
    // We need to render placeholders into a buffer and then pack them into a map to pass to
    // Runtime.renderSoyMsgWithPlaceholders.

    Map<String, Function<Expression, Statement>> placeholderNameToPutStatement =
        new LinkedHashMap<>();
    putPlaceholdersIntoMap(msg, partsAndId.parts, placeholderNameToPutStatement);
    // sanity check
    checkState(!placeholderNameToPutStatement.isEmpty());
    ConstructorRef cstruct =
        msg.isPlrselMsg() ? ConstructorRef.PLRSEL_MSG_RENDERER : ConstructorRef.MSG_RENDERER;
    Statement initRendererStatement =
        variables
            .getCurrentRenderee()
            .putInstanceField(
                thisVar,
                cstruct.construct(
                    constant(partsAndId.id),
                    soyMsgParts,
                    locale,
                    constant(placeholderNameToPutStatement.size())));
    List<Statement> initializationStatements = new ArrayList<>();
    initializationStatements.add(initRendererStatement);
    for (Function<Expression, Statement> fn : placeholderNameToPutStatement.values()) {
      initializationStatements.add(fn.apply(variables.getCurrentRenderee().accessor(thisVar)));
    }

    Statement initMsgRenderer = Statement.concat(initializationStatements);
    Statement render;
    if (areAllPrintDirectivesStreamable(escapingDirectives)) {
      AppendableAndOptions wrappedAppendable =
          applyStreamingEscapingDirectives(
              escapingDirectives,
              appendableExpression,
              parameterLookup.getPluginContext(),
              variables);
      FieldRef currentAppendableField = variables.getCurrentAppendable();
      Statement initAppendable =
          currentAppendableField.putInstanceField(thisVar, wrappedAppendable.appendable());
      Expression appendableExpression = currentAppendableField.accessor(thisVar);
      Statement clearAppendable =
          currentAppendableField.putInstanceField(
              thisVar, constantNull(LOGGING_ADVISING_APPENDABLE_TYPE));
      if (wrappedAppendable.closeable()) {
        clearAppendable =
            Statement.concat(
                appendableExpression
                    .checkedCast(BytecodeUtils.CLOSEABLE_TYPE)
                    .invokeVoid(MethodRef.CLOSEABLE_CLOSE),
                clearAppendable);
      }
      render =
          Statement.concat(
              initAppendable,
              detachState.detachForRender(
                  variables
                      .getCurrentRenderee()
                      .accessor(thisVar)
                      .invoke(
                          MethodRef.SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE,
                          appendableExpression,
                          // set the isLast field to true since we know this will only be rendered
                          // once.
                          /* isLast=*/ constant(true))),
              clearAppendable);
    } else {
      Label start = new Label();
      SoyExpression value =
          SoyExpression.forSoyValue(
              StringType.getInstance(),
              detachState
                  .createExpressionDetacher(start)
                  .resolveSoyValueProvider(variables.getCurrentRenderee().accessor(thisVar))
                  .checkedCast(SOY_STRING_TYPE));
      for (SoyPrintDirective directive : escapingDirectives) {
        value = parameterLookup.getRenderContext().applyPrintDirective(directive, value);
      }
      render =
          appendableExpression.appendString(value.unboxAsString()).toStatement().labelStart(start);
    }
    return Statement.concat(
        initMsgRenderer,
        render,
        // clear the field
        variables
            .getCurrentRenderee()
            .putInstanceField(
                thisVar,
                BytecodeUtils.constantNull(ConstructorRef.MSG_RENDERER.instanceClass().type())));
  }
447699
def __build_query(self, routine, parameters):
        """"""

        parameter_names = []
        replacements = {}
        for i, value in enumerate(parameters):
            name = 'arg' + str(i)

            parameter_names.append(name)
            replacements[name] = value

        parameter_pieces = []
        for i, name in enumerate(parameter_names):
            if i > 0:
                parameter_pieces.append(', ')

            # Embed encoded blobs directly.
            if issubclass(replacements[name].__class__, _BlobArgumentWrapper) is True:
                parameter_pieces.append(replacements[name].encoded)
                del replacements[name]
            else:
                parameter_pieces.append(':' + name)

        query = "CALL " + routine + "(" + ''.join(parameter_pieces) + ")"

        return (query, replacements)
1080279
private static ArrayList<NamedList<Object>> rewriteToArray(
      NamedList<Object> nnl) {
    ArrayList<NamedList<Object>> al = new ArrayList<>();
    String key;
    Iterator<Entry<String, Object>> it = nnl.iterator();
    while (it.hasNext()) {
      Entry<String, Object> entry = it.next();
      NamedList<Object> item = (NamedList<Object>) entry.getValue();
      key = entry.getKey();
      if (key.startsWith(GroupHit.KEY_START)) {
        StringBuilder newKey = new StringBuilder("");
        item.add("group", GroupHit.keyToObject(key, newKey));
        item.add("key", newKey.toString().trim());
      } else {
        item.add("key", key);
      }
      al.add(item);
    }
    return al;
  }
17094
def get_params(self, *args, **kwargs):
        '''
        
        '''
        kwargs.update(self._data)
        if args and kwargs:
            raise ValueError('Cannot mix positional and named parameters')
        if args:
            return list(args)
        else:
            return kwargs
597618
def p_statement_declare(p):
    ''
    p[0] = ast.Declare(p[3], p[5], lineno=p.lineno(1))
369164
def where(cls, where_clause="", start_position="", max_results="", qb=None):
        
        if where_clause:
            where_clause = "WHERE " + where_clause

        if start_position:
            start_position = " STARTPOSITION " + str(start_position)

        if max_results:
            max_results = " MAXRESULTS " + str(max_results)

        select = "SELECT * FROM {0} {1}{2}{3}".format(
            cls.qbo_object_name, where_clause, start_position, max_results)

        return cls.query(select, qb=qb)