Skip to main content

convert_mysql_placeholders_to_postgresql

Function convert_mysql_placeholders_to_postgresql 

Source
pub fn convert_mysql_placeholders_to_postgresql(sql: &str) -> String
Expand description

Convert MySQL placeholder (?) to PostgreSQL placeholders ($1, $2, $3, …)

This function efficiently converts MySQL-style question mark placeholders to PostgreSQL-style numbered placeholders while respecting SQL string literals and comments.

§Escape Sequences

  • \? is converted to ? (not a placeholder)
  • ?? is converted to ? (not a placeholder)
  • Single ? is converted to $1, $2, etc.

§Examples

use senax_pgsql_parser::convert_mysql_placeholders_to_postgresql;

// Basic placeholder conversion
let mysql_sql = "SELECT * FROM users WHERE id = ? AND name = ?";
let postgresql_sql = convert_mysql_placeholders_to_postgresql(mysql_sql);
assert_eq!(postgresql_sql, "SELECT * FROM users WHERE id = $1 AND name = $2");

// String literals are preserved
let mysql_sql = "SELECT * FROM users WHERE name = 'user?' AND id = ?";
let postgresql_sql = convert_mysql_placeholders_to_postgresql(mysql_sql);
assert_eq!(postgresql_sql, "SELECT * FROM users WHERE name = 'user?' AND id = $1");

// Escaped \? is converted to ? (useful for PostgreSQL JSON operators)
let mysql_sql = r"SELECT * FROM users WHERE json_data \? 'key' AND id = ?";
let postgresql_sql = convert_mysql_placeholders_to_postgresql(mysql_sql);
assert_eq!(postgresql_sql, "SELECT * FROM users WHERE json_data ? 'key' AND id = $1");

// Double ?? is converted to ? (useful for PostgreSQL JSON operators)
let mysql_sql = "SELECT * FROM users WHERE json_data ?? 'key' AND id = ?";
let postgresql_sql = convert_mysql_placeholders_to_postgresql(mysql_sql);
assert_eq!(postgresql_sql, "SELECT * FROM users WHERE json_data ? 'key' AND id = $1");

// Combined usage
let mysql_sql = r"SELECT \? as escaped, ?? as double, ? as param";
let postgresql_sql = convert_mysql_placeholders_to_postgresql(mysql_sql);
assert_eq!(postgresql_sql, "SELECT ? as escaped, ? as double, $1 as param");