gpt4 book ai didi

mysql - 如何将使用 Node Buffers 创建的 MySQL BINARY 列转换为 Rust 中的字符串?

转载 作者:行者123 更新时间:2023-12-03 11:26:29 26 4
gpt4 key购买 nike

我做了什么

  • 将 UUID 存储为 BINARY(16)在 NodeJS 中使用
const uuid = Buffer.from('myEditedUuid');

(How do I fetch binary columns from MySQL in Rust? 的跟进)

我想做什么

我想使用 Rust 获取所述 UUID https://docs.rs/mysql/20.0.0/mysql/ .我目前正在使用 Vec<u8>获得所述 UUID:

#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct Policy {
sub: String,
contents: Option<String>,
}

#[derive(Debug, PartialEq, Eq, Serialize)]
pub struct RawPolicy {
sub: Option<Vec<u8>>,
contents: Option<String>,
}

// fetch policies themselves
let policies: Vec<RawPolicy> = connection.query_map("SELECT sub, contents FROM policy", |(sub, contents)| {
RawPolicy { sub, contents }
},)?;

// convert uuid to string
let processed = policies.into_iter().map(|policy| {
let sub = policy.sub.unwrap();
let sub_string = String::from_utf8(sub).unwrap().to_string();
Policy {
sub: sub_string,
contents: policy.contents,
}
}).collect();

我的问题是什么

在 Node 中,我将从所述数据库接收一个缓冲区并使用类似 uuidBUffer.toString('utf8'); 的东西所以在 Rust 中,我尝试使用 String::from_utf8() ,但说 Vec 似乎不是有效的 utf8-vec:

panicked at 'called `Result::unwrap()` on an `Err` value: FromUtf8Error { bytes: [17, 234, 79, 61, 99, 181, 10, 240, 164, 224, 103, 175, 134, 6, 72, 71], error: Utf8Error { valid_up_to: 1, error_len: Some(1) } }'

我的问题是

正在使用 Vec 获取的正确方法 BINARY - 列,如果是,我如何将它们转换回字符串?

编辑1:

Node 似乎使用 Base 16 将字符串转换为缓冲区 (Buffer.from('abcd') => <Buffer 61 62 63 64>)。

在使用 Buffer.from() 制作的 Rust 中获取我解析的 UUID 给我 Vec<u8> [17, 234, 79, 61, 99, 181, 10, 240, 164, 224, 103, 175, 134, 6, 72, 71]这表示 utf8-Error。MySQL 在 Rust 中似乎不允许使用 Vec。

最佳答案

解决方法很简单:您需要在数据库查询或代码中将 BINARY 转换为十六进制。所以要么尝试使用 HEX-Crate https://docs.rs/hex/0.4.2/hex/或重写您的查询:

重写查询

let policies: Vec<RawPolicy> = connection.query_map("SELECT hex(sub), contents FROM policy", |(sub, contents)| {
RawPolicy { sub, contents }
},)?;

将 sub 转换为十六进制数。现在可以使用

转换生成的 Vec
let sub = policy.sub.unwrap();
let sub_string = String::from_utf8(sub).unwrap();

关于mysql - 如何将使用 Node Buffers 创建的 MySQL BINARY 列转换为 Rust 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com