2

这是我使用postgrescrate 将数据插入 Postgres 数据库的代码(不幸的是,Rust Playground 上不存在):

使用以下 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使用format!宏将 UUID 转换为 a,因为 Postgres 应该隐式转换为 UUID,但它不起作用(相同的错误消息)。$1::uuid然后我在 Postgres 查询中添加了一个显式的,但问题仍然存在。

4

1 回答 1

2

板条箱页面指出:

可选功能

UUID 类型

该功能可选地提供 UUID 支持,该功能为's类型with-uuid添加ToSqlFromSql实现。需要版本 0.5。uuidUuiduuid

您尚未指定该功能,并且您使用的是不兼容的 uuid 版本。

货运.toml

[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);

代码

use postgres::{Connection, TlsMode};
use std::error::Error;
use uuid::Uuid;

fn main() -> Result<(), Box<Error>> {
    let conn = Connection::connect(
        "postgresql://shep@localhost:5432/stackoverflow",
        TlsMode::None,
    )
    .unwrap();

    let stuff_id = Uuid::default();

    conn.execute(
        "insert into public.junk (id) values ($1)",
        &[&stuff_id],
    )?;

    Ok(())
}

也可以看看:

于 2019-03-18T17:00:15.213 回答