$ cargo new psql
crateはpostgresを使用する
https://docs.rs/postgres/latest/postgres/#example
[dependencies] postgres = "0.19.9"
use postgres::{Client, NoTls};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut client = Client::connect("host=localhost user=postgres password=password", NoTls)?;
client.batch_execute("
CREATE TABLE person (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
data BYTEA
)
")?;
let name = "Ferris";
let data = None::<&[u8]>;
client.execute(
"INSERT INTO person (name, data) VALUES ($1, $2)",
&[&name, &data],
)?;
for row in client.query("SELECT id, name, data From person", &[])? {
let id: i32 = row.get(0);
let name: &str = row.get(1);
let data: Option<&[u8]> = row.get(2);
println!("found person: {} {} {:?}", id, name, data);
}
Ok(())
}
$ cargo run
Compiling psql v0.1.0 (/home/vagrant/dev/rust/psql)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 2.54s
Running `target/debug/psql`
found person: 1 Ferris None
おおおおおおおおおお
create tableはrustではなく、setup.shでpythonで実行して、rustではinsertとselectのみを実行するようにしたいですね。
setup.sh
pip install psycopg2-binary yes | sudo apt install libpq-dev pip install psycopg2 python3 init.py
init.py
import psycopg2
connection = psycopg2.connect(
host='localhost',
user='postgres',
password='password'
)
cur = connection.cursor()
cur.execute('CREATE TABLE person ( \
id SERIAL PRIMARY KEY, \
name TEXT NOT NULL, \
data BYTEA \
);')
connection.commit()
cur.close()
connection.close()
$ cargo run
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.17s
Running `target/debug/psql`
found person: 1 Ferris None
転送元ノードのIPを取得してDBに入れようと思ったけど、ちょっと難しいな…