まず動作したコード
extern crate postgres; use postgres::{Connection, SslMode}; struct Counter { id: i32, counter: i16 } fn main() { let dsn = "postgres://postgres@localhost"; let conn = match Connection::connect(dsn, SslMode::None) { Ok(conn) => conn, Err(e) => { println!("Connection error: {}", e); return; } }; // Create Table conn.execute("CREATE TABLE counter ( id SERIAL, counter SMALLINT NOT NULL DEFAULT 0 )", &[]).unwrap(); // Counter type let me = Counter { id: 0, counter: 1 }; // Interting let stmt = match conn.prepare("INSERT INTO counter (counter) VALUES ($1)") { Ok(stmt) => stmt, Err(e) => { println!("Preparing query failed: {}", e); return; } }; // Run stmt.execute(&[&me.counter]).ok().expect("Inserting counter failed"); for row in &conn.query("SELECT id, counter FROM counter", &[]).unwrap() { let counter = Counter { id: row.get(0), counter: row.get(1) }; println!("Found counter {}", counter.counter); } }
ダメだった時
Process didn't exit successfully: `target/debug/nickel-helloworld` (exit code: 101)
のエラーが出てた。
原因
struct Counter { id: i32, counter: i32 }
counterカラムがSMALLINT
なのにi32
にしていた。
i16
じゃないとダメ
テーブル名とカラム名が同じだからとか、1つの数字には入れたらいけないとかと勘違いしていた。
thread '<main>' panicked at 'error retrieving column 1: Conversion(WrongType(Int2))', /Users/shinriyo/.multirust/toolchains/stable/cargo/registry/src/github.com-88ac128001ac3a9a/postgres-0.11.0/src/rows.rs:194
Int2
ってなんだよーって。
Postgres の Int2 ってのがSMALLINTのときはRustでいうi16だと思う。