目的
RustでPostgreSQLのエラーを扱いたい。特にsql_stateは自前のコードを定義して使うことが多いので、個人的に重要視しています。
プログラム
Cargo.toml
[package]
name = "pg"
version = "0.1.0"
edition = "2018"
[dependencies]
r2d2_postgres = "^0.14"
main.rs
fn main() {
let manager = r2d2_postgres::PostgresConnectionManager::new(
"postgres://user:pass@localhost:5432/test",
r2d2_postgres::TlsMode::None).unwrap();
let pool = r2d2_postgres::r2d2::Pool::new(manager).unwrap();
let conn = pool.get().unwrap();
let sql = r#"
SELECT * FROM dummies
"#;
let rows = conn.query(sql, &[]);
if let Err(err) = rows {
print_typename(&err);
println!("debug\n{:?}\n\nstring\n{}\n\ncode\n{}\n\nmessage\n{}\n\ndetail\n{}",
err,
err,
err.code().map(|sql_state| sql_state.code()).unwrap_or(""),
err.as_db().map(|db_error| &db_error.message).unwrap_or(&"".to_string()),
err.as_db().and_then(|db_error| db_error.detail.as_ref()).unwrap_or(&"detail not found".to_string()),
);
}
}
fn print_typename<T>(_: &T) {
println!("type\n{}\n", std::any::type_name::<T>());
}
type
postgres_shared::error::Error
debug
Error(Db(DbError { severity: "ERROR", parsed_severity: Some(Error), code: SqlState("42P01"), message: "relation \"dummies\" does not exist", detail: None, hint: None, position: Some(Normal(24)), where_: None, schema: None, table: None, column: None, datatype: None, constraint: None, file: Some("parse_relation.c"), line: Some(1194), routine: Some("parserOpenTable") }))
string
database error: ERROR: relation "dummies" does not exist
code
42P01
message
relation "dummies" does not exist
detail
detail not found