sfackler / rust-postgres

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

Examples. #674

Open hbowden opened 4 years ago

hbowden commented 4 years ago

Are there any more examples? The only example I can find for the most recent version is here: https://docs.rs/tokio-postgres/0.6.0/tokio_postgres/ . Are there any examples of doing a SELECT statement with more than one row/value? Connection pooling? Prepared statements, etc?

sfackler commented 4 years ago

Are there any examples of doing a SELECT statement with more than one row/value?

In the example you linked, client.query() returns a Vec of rows. If there is more than one row, there will be more than one value in the vector.

Connection pooling?

Connection pooling would be handled by a separate library.

Prepared statements, etc?

You use the client.prepare method to make a prepared statement: https://github.com/sfackler/rust-postgres/blob/master/tokio-postgres/tests/test/main.rs#L342-L343

hbowden commented 4 years ago

More examples of getting the actual value would be really helpful, for example why is this okay...

let id: &str = rows[0].get(0).unwrap();

But this is not...

let id: String = rows[0].get(0).unwrap();

and how come try_get works for String but get does not?


 let id: String = rows[0].try_get(0).unwrap();

And how would I get a non string/text value?

sfackler commented 4 years ago

Both of those first two examples should not have the .unwrap(). Returning a String works just fine with .get.

You get a non string/text value by calling .get or .try_get with the appropriate Rust type for your Postgres type. For example, if column 0 is a Postgres BIGINT you'd do let id: i64 = rows[0].get(0);

andreespirela commented 4 years ago

@sfackler How would you do if you don't know the type you're getting back? Dynamic parameter & dynamic values.

sfackler commented 4 years ago

You can look at the information in the row to see what Postgres type it is and pick the appropriate Rust type from that.

andreespirela commented 4 years ago

@sfackler sounds like a lot to do a match/if/switch for every type possible

sfackler commented 4 years ago

What other option is there? Postgres sends a blob of bytes, and you need to understand how to interpret that blob if you want to do anything with it.