插入Postgres时,无法转换为类型为“uuid”的Postgres值

问题描述 投票:-1回答:1

下面是我用来在Postgres数据库中使用postgres crate插入数据的代码(不幸的是不存在于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://[email protected]/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,但问题仍然存在。

postgresql rust
1个回答
1
投票

crate page说:

可选功能

UUID type

Qazxswpoi功能可选择提供UUID支持,为with-uuidToSql类型添加FromSqluuid实现。需要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);

也可以看看:

  • 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(()) }
© www.soinside.com 2019 - 2024. All rights reserved.