Replaces a string placeholder with the string held in the class variable

@param   string  $sql     The SQL statement to prepare
@param   string  $prefix  The common table prefix
@return  string
@since   2.0.0
514849
public function replacePrefix($sql, $prefix = '#__')
	{
		// As we replace strings of different lengths, subsequent prefix positions will become invalid.
		// Thus, we track that differential here to account for the shifting locations
		$differential = strlen($this->tablePrefix) - strlen($prefix);
		$count        = 0;

		foreach (Str::findLiteral($prefix, $sql) as $prefixPosition)
		{
			$sql = substr_replace($sql, $this->tablePrefix, $prefixPosition + ($differential*$count), strlen($prefix));
			$count++;
		}

		return $sql;
	}
9021
public function bindValues(
        /*# string */ $sql,
        array &$bindings,
        array $settings
    )/*# : string */ {
        // make sure escape function ok
        $this->setEscapeCallable($settings['escapeFunction']);

        // replace each placeholder with corresponding ?/:name/value
        return preg_replace_callback(
            '/\b__PHQUERY_[^_]++__\b/',
            function ($m) use (&$bindings, $settings) {
                return $this->replacePlaceholders($m[0], $bindings, $settings);
            },
            $sql
        );
    }
968002
public function prepare($sql)
    {
        if (! array_key_exists($sql, $this->statements)) {
            $this->statements[$sql] = $this->pdo->prepare($sql);

        }
        return $this->statements[$sql];
    }
805835
public function tablePrefix($action = null, $prefix = null) {
		$db = $this->_getConnection();
		$config = $db->config();
		$database = $config['database'];
		if (!empty($this->params['database'])) {
			$database = $this->params['database'];
		}

		while (!$action || !in_array($action, ['A', 'R'], true)) {
			$action = $this->in('Add or remove?', ['A', 'R']);
		}

		while (!$prefix) {
			$prefix = $this->in('Please select prefix:');
		}

		$space = "\n";
		if ($action === 'R') {
			$length = mb_strlen($prefix) + 1;
			$script = <<<SQL
SELECT  CONCAT('RENAME TABLE `$database`.`', table_name, '` TO `$database`.`', SUBSTR(table_name, $length), '`;$space') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		} else {
			$script = <<<SQL
SELECT  CONCAT('RENAME TABLE `$database`.`', table_name, '` TO `$database`.`$prefix', table_name, '`;$space') AS statement
FROM    information_schema.tables AS tb
WHERE   table_schema = '$database'
AND     table_name NOT LIKE '$prefix%'
AND     `TABLE_TYPE` = 'BASE TABLE';
SQL;
		}

		/** @var \Cake\Database\Statement\StatementDecorator $res */
		$res = $db->query($script);
		if (!$res->count()) {
			$this->abort('Nothing to do...');
		}

		$script = '';
		foreach ($res as $r) {
			$script .= $r['statement'];
			$this->out($r['statement'], 1, Shell::VERBOSE);
		}

		if (!$this->param('dry-run')) {
			$continue = $this->in($res->count() . ' tables will be altered.', ['Y', 'N'], 'N');
			if (strtoupper($continue) !== 'Y') {
				$this->abort('Aborted!');
			}
		}

		if (!$this->params['dry-run']) {
			$db->query($script);
		} else {
			$this->out($script);
		}
		$this->out('Done :)');
	}
362701
public function prepare($sql, $driverOptions = [])
    {
        $this->placeholders = $this->types = [];
        $sql = preg_replace_callback(static::PLACEHOLDER_REGEX, function ($matches) {
            $name = $matches[2];
            if (!isset($this->types[$name])) {
                $this->types[$name] = static::$typeMap[$matches[1]];
            }
            $this->placeholders[] = $name;

            return '?';
        }, $sql);

        return parent::prepare($sql, $driverOptions);
    }
505969
protected function add_no_lock_to_temp_tables($sql) {
        return preg_replace_callback('/(\{([a-z][a-z0-9_]*)\})(\s+(\w+))?/', function($matches) {
            $table = $matches[1]; // With the braces, so we can put it back in the query.
            $name = $matches[2]; // Without the braces, so we can check if it's a temptable.
            $tail = isset($matches[3]) ? $matches[3] : ''; // Catch the next word afterwards so that we can check if it's an alias.
            $replacement = $matches[0]; // The table and the word following it, so we can replace it back if no changes are needed.

            if ($this->temptables && $this->temptables->is_temptable($name)) {
                if (!empty($tail)) {
                    if (in_array(strtolower(trim($tail)), $this->reservewords)) {
                        // If the table is followed by a reserve word, it's not an alias so put the WITH (NOLOCK) in between.
                        return $table . ' WITH (NOLOCK)' . $tail;
                    }
                }
                // If the table is not followed by a reserve word, put the WITH (NOLOCK) after the whole match.
                return $replacement . ' WITH (NOLOCK)';
            } else {
                return $replacement;
            }
        }, $sql);
    }
765065
public function compileBindsQuestionMark(string $sql, $binds = null)
    {
        if (empty($binds) || strpos($sql, '?') === false) {
            return $sql;
        } elseif (! is_array($binds)) {
            $binds = [$binds];
            $bind_count = 1;
        } else {
            // Make sure we're using numeric keys
            $binds = array_values($binds);
            $bind_count = count($binds);
        }
        // Make sure not to replace a chunk inside a string that happens to match the bind marker
        if ($countMatches = preg_match_all("/'[^']*'/i", $sql, $matches)) {
            $countMatches = preg_match_all(
                '/\?/i', # regex
                str_replace(
                    $matches[0],
                    str_replace('?', str_repeat(' ', 1), $matches[0]),
                    $sql,
                    $countMatches
                ),
                $matches, # matches
                PREG_OFFSET_CAPTURE
            );
            // Bind values' count must match the count of markers in the query
            if ($bind_count !== $countMatches) {
                return false;
            }
        } elseif (($countMatches = preg_match_all('/\?/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count) {
            return $sql;
        }

        do {
            $countMatches--;
            $escapedValue = is_int($binds[$countMatches])
                ? $binds[$countMatches]
                : $this->quote($binds[$countMatches]);
            if (is_array($escapedValue)) {
                $escapedValue = '('.implode(',', $escapedValue).')';
            }
            $sql = substr_replace($sql, $escapedValue, $matches[0][$countMatches][1], 1);
        } while ($countMatches !== 0);

        return $sql;
    }
165063
public function engineCompat(string $sql): string
    {
        $sql = $this->c::mbTrim($sql);

        if (!preg_match('/^CREATE\s+TABLE\b/ui', $sql)) {
            return $sql; // Not applicable.
        }
        $sql = preg_replace('/\bENGINE\=[%a-z0-9_\-]*/ui', '', $sql);

        if (!preg_match('/\bFULLTEXT\s+KEY\b/ui', $sql) || version_compare($this->wp->db_version(), '5.6.4', '>=')) {
            // MySQL v5.6.4+ supports fulltext indexes w/ InnoDB. See: <http://bit.ly/ZVeF42>
            $sql = preg_replace('/;$/u', ' ENGINE=InnoDB;', $sql);
        } else {
            $sql = preg_replace('/;$/u', ' ENGINE=MyISAM;', $sql);
        }
        return $sql;
    }
10243
public function setPrefix($prefix = null)
    {
        $prefix = trim($prefix, '/');

        $this->prefix = ($prefix) ? trim($prefix, '/') . '/' : '';
    }
565270
public function insertQuery(string $prefix, string $table = null): InsertQuery
    {
        return new InsertQuery($this, $this->getCompiler($prefix), $table);
    }
678124
public function load($sql)
    {
        $query = '';
        $delimiter = ';';
        $delimiterLength = 1;

        $dollarsOpen = false;
        foreach ($sql as $sqlLine) {
            if (preg_match('/DELIMITER ([\;\$\|\\\\]+)/i', $sqlLine, $match)) {
                $delimiter = $match[1];
                $delimiterLength = strlen($delimiter);
                continue;
            }

            $parsed = trim($query) == '' && $this->sqlLine($sqlLine);
            if ($parsed) {
                continue;
            }

            // Ignore $$ inside SQL standard string syntax such as in INSERT statements.
            if (!preg_match('/\'.*\$\$.*\'/', $sqlLine)) {
                $pos = strpos($sqlLine, '$$');
                if (($pos !== false) && ($pos >= 0)) {
                    $dollarsOpen = !$dollarsOpen;
                }
            }

            if (preg_match('/SET search_path = .*/i', $sqlLine, $match)) {
                $this->searchPath = $match[0];
            }

            $query .= "\n" . rtrim($sqlLine);

            if (!$dollarsOpen && substr($query, -1 * $delimiterLength, $delimiterLength) == $delimiter) {
                $this->sqlQuery(substr($query, 0, -1 * $delimiterLength));
                $query = '';
            }
        }

        if ($query !== '') {
            $this->sqlQuery($query);
        }
    }
811619
public static function preparedQuery($sql) {
        self::init();
        if(!empty($exclusions = self::$_ops->getExclusions())) {
            $prepared = self::prepareStmt($sql);
            $inserts = [];
            $types = '';
            foreach($exclusions as $i => $substitute) {
                $types .= $substitute['type'];
                $inserts[] = $substitute['value'];
            }
            return self::executeStmt($prepared, $types, $inserts);
        } else {
            return self::query($sql);
        }
    }
1154565
protected function replace(array $data, $template, $prefix = null)
    {
        foreach ($data as $k => $d) {
            if (is_array($d)) {
                return $this->replace($d, $template, $k . '.');
            } else {
                $template = str_replace('{' . (!empty($prefix) ? $prefix . $k : $k) . '}', $d, $template);
            }
        }

        return $template;
    }
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;
	}
1042888
public function quote(string $sql): string
    {
        return preg_replace_callback('#".*\!' . $this->nameRegex . '.*"|\!(' . $this->nameRegex . ')#i', function ($matches) {
            return isset($matches[1]) ? static::quoteName($matches[1]) : $matches[0];
        }, $sql);
    }
831101
public function query($query)
    {
        // Replace prefix placeholder with prefix
        $query = str_replace("{prefix}", $this->prefix, $query);

        // Log last query and query count
        $this->lastQuery = $query;
        $this->queryCount++;

        // Query database
        return $this->connection->query($query);
    }
958073
protected function replaceTable($sql) {
		$table = $this->getTable();
		$i18nTable = $this->getTranslationTable();
		preg_match_all('/(?<![\.a-zA-Z0-9-_`\(\)])([a-z_][a-zA-Z0-9-_]*)(?![\.`\(\)])/', $sql, $matches);
		foreach($matches[0] as $property) {
			if($this->definition->hasProperty($property))
				$table = $this->definition->property($property)->get('i18n') ? $i18nTable:$table;
			$sql = preg_replace('/(?<![\.a-zA-Z0-9-_`\(\)])('.$property.')(?![\.a-zA-Z0-9-_`\(\)])/', $table.'.$1', $sql);
		}

		return $sql;
	}