sqlx icon indicating copy to clipboard operation
sqlx copied to clipboard

[MySql] String bind parameters encoded as UTF8 in non UTF8 columns

Open jairinhohw opened this issue 6 years ago • 3 comments

Example:

CREATE TABLE `conf` (
  `id` varchar(30) NOT NULL,
  `data` longtext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
let data = "açai";

sqlx::query("INSERT INTO conf values (?, ?)")
    .bind("test")
    .bind(data)
    .execute(&conn)
    .await
    .unwrap();

let (string, bin): (String, Vec<u8>) =
    sqlx::query_as("SELECT data, BINARY data as bin from conf where id = 'test'")
        .fetch_one(&conn)
        .await
        .unwrap();

assert_eq!(data.as_bytes(), &bin[..]);
assert_eq!(data, &string);

The first assertion works, but shouldn't, indicating that the string was written in the database with UTF8 encoding. The second panics with

 left: `"açai"`,
right: `"açai"`

jairinhohw avatar Jun 21 '20 00:06 jairinhohw

We don't really have a good way to address this as we'd have to query the charset of the column at bind time when the argument gets encoded, assuming we have any way to know what column a bind parameter corresponds to (which I don't think we do without analyzing the SQL ourselves).

As a workaround you can re-encode the string yourself and bind it as bytes.

abonander avatar Jun 21 '20 00:06 abonander

Hmm, if MySQL tells us the expected charset in the column definition packet for the parameter we can maybe re-encode the string corresponding to that parameter, but that would break with the workaround as we'd have to make an assumption as to the original encoding of the string.

abonander avatar Jun 21 '20 00:06 abonander

I had tested this with the current version in crates (0.3.5), but testing in the current master works as expected. Sorry for bothering.

jairinhohw avatar Jun 21 '20 09:06 jairinhohw