src/bin/pgbench/pgbench.c:1916-1935
Replaces a variable placeholder in SQL text with its actual value, handling memory reallocation as needed.
static char *replaceVariable(char **sql, char *param, int len, char *value)This function performs in-place replacement of variable placeholders in SQL strings. It handles cases where the replacement value is larger than the original placeholder by reallocating the SQL string buffer. The function carefully manages memory by calculating offsets before reallocation to ensure pointers remain valid. When the replacement value differs in length from the placeholder, it uses memmove to shift the remaining text appropriately before copying the new value.
sql: Pointer to pointer to the SQL string buffer (may be reallocated)param: Pointer to the start of the variable placeholder within the SQL stringlen: Length of the variable placeholder to be replacedvalue: String value to substitute for the placeholder
- Functions called/Symbols referenced:
- strlen
- pg_realloc
- memmove
- memcpy
- Called from:
- assignVariables (src/bin/pgbench/pgbench.c:1965)
- parseQuery (src/bin/pgbench/pgbench.c:5490)
- Returns a pointer to the position immediately after the replaced text
- Handles memory reallocation when the replacement value is longer than the original placeholder
- Uses offset calculation to maintain pointer validity across reallocation
- Part of pgbench's variable substitution system for SQL script processing
- The sql parameter is passed by reference because the buffer may be reallocated
- Uses memmove for safe overlapping memory operations when adjusting text length
static char *
replaceVariable(char **sql, char *param, int len, char *value)
{
int valuelen = strlen(value);
// Reallocate buffer if replacement value is longer
if (valuelen > len)
{
size_t offset = param - *sql;
*sql = pg_realloc(*sql, strlen(*sql) - len + valuelen + 1);
param = *sql + offset; // Update pointer after reallocation
}
// Shift remaining text if lengths differ
if (valuelen != len)
memmove(param + valuelen, param + len, strlen(param + len) + 1);
// Copy new value into place
memcpy(param, value, valuelen);
return param + valuelen;
}