sfackler / rust-postgres

Native PostgreSQL driver for the Rust programming language
Apache License 2.0
3.49k stars 443 forks source link

Passing Enum with Postgres schema #954

Closed questin closed 1 year ago

questin commented 2 years ago

//// Postgres Setup CREATE SCHEMA cust;

CREATE TYPE cust."CustomerType" AS ENUM ('Test', 'Std');

CREATE TABLE IF NOT EXISTS cust.customer ( id integer NOT NULL DEFAULT nextval('cust.customer_id_seq'::regclass), name character varying(50) COLLATE pg_catalog."default" NOT NULL, created_at timestamp with time zone NOT NULL DEFAULT now(), is_active boolean NOT NULL, customer_type cust."CustomerType" NOT NULL, CONSTRAINT customer_pkey PRIMARY KEY (id) )

//// Rust Code - Example.rs

use postgres::{Client, NoTls}; use postgres_types::{ToSql, FromSql}; use log::{info, warn, error};

[derive(Debug, ToSql, FromSql)]

[postgres(name = "cust.CustomerType")]

pub enum CustomerType{ Test, Std, }

fn main() { info!("Connecting to SQL Server..."); let mut c = Client::connect(&String::from("postgresql://pluto:**@localhost/pluto"), NoTls).unwrap(); let name = String::from("ABC Corp."); let customer_type = CustomerType::Test; for row in &c.query( "INSERT INTO cust.customer (name, created_at, is_active, customer_type) VALUES ($1, now(), $2, $3) RETURNING id", &[&name, &true, &customer_type] ).unwrap() { info!("Created customer: {:?}", &name); } }

// Execution Result

DEBUG tokio_postgres::query > executing statement s0 with parameters: ["ABC Corp.", true, Test] thread 'main' panicked at 'called Result::unwrap() on an Err value: Error { kind: ToSql(2), cause: Some(WrongType { postgres: Other(Other { name: "CustomerType", oid: 16482, kind: Enum(["Test", "Std"]), schema: "cust" }), rust: "example::CustomerType" }) }', src/commandline/example.rs:20:7

questin commented 2 years ago

Not a priority as I can use this within the same schema for now.

sfackler commented 2 years ago

You don't need to include the schema in the type name. Just remove the #[postgres(name = "cust.CustomerType")] line.