这是我使用postgres
板条箱(很不幸地不在Rust Playground上)在Postgres数据库中插入数据的代码:
使用以下Cargo.toml:
[package]
name = "suff-import"
version = "0.1.0"
authors = ["greg"]
[dependencies]
csv = "1"
postgres = "0.15"
uuid = "0.7"
文件main.rs
:
extern crate csv;
extern crate postgres;
extern crate uuid;
use uuid::Uuid;
use postgres::{Connection, TlsMode};
use std::error::Error;
use std::io;
use csv::StringRecord;
struct Stuff {
stuff_id: Uuid,
created_at: String,
description: String,
is_something: bool,
}
impl Stuff {
fn from_string_record(record: StringRecord) -> Stuff {
Stuff {
stuff_id: Uuid::parse_str(record.get(0).unwrap()).unwrap(),
created_at: record.get(1).unwrap().to_string(),
description: record.get(2).unwrap().to_string(),
is_something: record.get(3).unwrap().to_string().parse::<i32>().unwrap() == 2,
}
}
}
fn save_row(dbcon: &Connection, stuff: Stuff) -> Result<(), Box<Error>> {
dbcon.execute(
"insert into public.stuff (stuff_id, created_at, description, is_something) values ($1::uuid, $2, $3, $4)",
&[&format!("{}", &stuff.stuff_id).as_str(), &stuff.created_at, &stuff.description, &stuff.is_something]
)?;
Ok(())
}
fn import() -> Result<(), Box<Error>> {
let mut reader = csv::Reader::from_reader(io::stdin());
let dbcon = Connection::connect("postgres://gregoire@10.129.198.251/gregoire", TlsMode::None).unwrap();
for result in reader.records() {
let record = result?;
println!(".");
save_row(&dbcon, Stuff::from_string_record(record))?;
}
Ok(())
}
fn main() {
if let Err(error) = import() {
println!("There were some errors: {}", error);
std::process::exit(1);
}
}
程序已编译,但是在运行时出现错误消息时退出:
./target/debug/suff-import <<EOF
stuff_id,created_at,description,is_something
5252fff5-d04f-4e0f-8d3e-27da489cf40c,"2019-03-15 16:39:32","This is a description",1
EOF
.
There were some errors: type conversion error: cannot convert to or from a Postgres value of type `uuid`
我测试了使用&str
宏将UUID转换为format!
的原因,因为Postgres应该隐式地转换为UUID,但是没有用(相同的错误消息)。然后,我在Postgres查询中添加了一个明确的$1::uuid
,但问题仍然存在。
答案 0 :(得分:1)
crate page指出:
可选功能
UUID类型
UUID支持由
with-uuid
功能提供,该功能为ToSql
的{{1}}类型添加了FromSql
和uuid
实现。需要Uuid
版本0.5。
您尚未指定功能,并且使用的是不兼容的uuid版本。
Cargo.toml
uuid
数据库设置
[package]
name = "repro"
version = "0.1.0"
edition = "2018"
[dependencies]
postgres = { version = "0.15.2", features = ["with-uuid"] }
uuid = "0.5"
代码
CREATE TABLE junk (id uuid);
另请参阅: