Skip to content

Commit 37954d1

Browse files
committed
Update documentation to focus on direct execution and querying
It's the common case, so make things look simpler to a newcomer.
1 parent 685557a commit 37954d1

2 files changed

Lines changed: 70 additions & 40 deletions

File tree

README.md

Lines changed: 27 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ fn main() {
6868
Connect to a Postgres server using the standard URI format:
6969
```rust
7070
let conn = try!(Connection::connect("postgres://user:pass@host:port/database?arg1=val1&arg2=val2",
71-
&SslMode::None));
71+
SslMode::None));
7272
```
7373
`pass` may be omitted if not needed. `port` defaults to `5432` and `database`
7474
defaults to the value of `user` if not specified. The driver supports `trust`,
@@ -77,48 +77,49 @@ defaults to the value of `user` if not specified. The driver supports `trust`,
7777
Unix domain sockets can be used as well by activating the `unix_socket` feature.
7878
The `host` portion of the URI should be set to the absolute path to the
7979
directory containing the socket file. Since `/` is a reserved character in
80-
URLs, the path should be URL encoded.
80+
URLs, the path should be URL encoded. If Postgres stored its socket files in
81+
`/run/postgres`, the connection would then look like:
8182
```rust
82-
let conn = try!(Connection::connect("postgres://postgres@%2Frun%2Fpostgres", &SslMode::None));
83+
let conn = try!(Connection::connect("postgres://postgres@%2Frun%2Fpostgres", SslMode::None));
8384
```
8485
Paths which contain non-UTF8 characters can be handled in a different manner;
8586
see the documentation for details.
8687

87-
### Statement Preparation
88-
Prepared statements can have parameters, represented as `$n` where `n` is an
89-
index into the parameter array starting from 1:
90-
```rust
91-
let stmt = try!(conn.prepare("SELECT * FROM foo WHERE bar = $1 AND baz = $2"));
92-
```
93-
9488
### Querying
95-
A prepared statement can be executed with the `query` and `execute` methods.
96-
Both methods take an array of parameters to bind to the query represented as
97-
`&ToSql` trait objects. `execute` returns the number of rows affected by the
98-
query (or 0 if not applicable):
89+
SQL statements can be executed with the `query` and `execute` methods. Both
90+
methods take a query string as well as a slice of parameters to bind to the
91+
query. The `i`th query parameter is specified in the query string by `$i`. Note
92+
that query parameters are 1-indexed rather than the more common 0-indexing.
93+
94+
`execute` returns the number of rows affected by the query (or 0 if not
95+
applicable):
9996
```rust
100-
let stmt = try!(conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2"));
101-
let updates = try!(stmt.execute(&[&1i32, &"biz"]));
97+
let updates = try!(conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2", &[&1i32, &"biz"]));
10298
println!("{} rows were updated", updates);
10399
```
104-
`query` returns an iterator over the rows returned from the database. The
105-
fields in a row can be accessed either by their indices or their column names,
106-
though access by index is more efficient. Unlike statement parameters, result
107-
columns are zero-indexed.
100+
101+
`query` returns an iterable object holding the rows returned from the database.
102+
The fields in a row can be accessed either by their indices or their column
103+
names, though access by index is more efficient. Unlike statement parameters,
104+
result columns are zero-indexed.
108105
```rust
109106
let stmt = try!(conn.prepare("SELECT bar, baz FROM foo"));
110-
for row in try!(stmt.query(&[])) {
107+
for row in &try!(conn.query("SELECT bar, baz FROM foo WHERE buz = $1", &[&1i32])) {
111108
let bar: i32 = row.get(0);
112109
let baz: String = row.get("baz");
113110
println!("bar: {}, baz: {}", bar, baz);
114111
}
115112
```
116-
In addition, `Connection` has utility `execute` and `query` methods which are
117-
useful if a statement is only going to be executed once:
113+
114+
### Statement Preparation
115+
If the same statement will be executed repeatedly (possibly with different
116+
parameters), explicitly preparing it can improve performance:
117+
118118
```rust
119-
let updates = try!(conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2",
120-
&[&1i32, &"biz"]));
121-
println!("{} rows were updated", updates);
119+
let stmt = try!(conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2"));
120+
for (bar, baz) in updates {
121+
try!(stmt.update(&[bar, baz]));
122+
}
122123
```
123124

124125
### Transactions

src/lib.rs

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -908,17 +908,33 @@ impl Connection {
908908
InnerConnection::connect(params, ssl).map(|conn| Connection { conn: RefCell::new(conn) })
909909
}
910910

911-
/// A convenience function for queries that are only run once.
911+
/// Executes a statement, returning the number of rows modified.
912912
///
913-
/// If an error is returned, it could have come from either the preparation
914-
/// or execution of the statement.
913+
/// A statement may contain parameters, specified by `$n` where `n` is the
914+
/// index of the parameter in the list provided, 1-indexed.
915+
///
916+
/// If the statement does not modify any rows (e.g. SELECT), 0 is returned.
915917
///
916-
/// On success, returns the number of rows modified or 0 if not applicable.
918+
/// If the same statement will be repeatedly executed (perhaps with
919+
/// different query parameters), consider using the `prepare` and
920+
/// `prepare_cached` methods.
917921
///
918922
/// # Panics
919923
///
920924
/// Panics if the number of parameters provided does not match the number
921925
/// expected.
926+
///
927+
/// # Example
928+
///
929+
/// ```rust,no_run
930+
/// # use postgres::{Connection, SslMode};
931+
/// # let conn = Connection::connect("", SslMode::None).unwrap();
932+
/// # let bar = 1i32;
933+
/// # let baz = true;
934+
/// let rows_updated = conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2", &[&bar, &baz])
935+
/// .unwrap();
936+
/// println!("{} rows updated", rows_updated);
937+
/// ```
922938
pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
923939
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
924940
let stmt = Statement::new(self,
@@ -930,17 +946,31 @@ impl Connection {
930946
stmt.execute(params)
931947
}
932948

933-
/// A convenience function for queries that are only run once.
949+
/// Executes a statement, returning the resulting rows.
934950
///
935-
/// If an error is returned, it could have come from either the preparation
936-
/// or execution of the statement.
951+
/// A statement may contain parameters, specified by `$n` where `n` is the
952+
/// index of the parameter in the list provided, 1-indexed.
937953
///
938-
/// On success, returns the resulting rows.
954+
/// If the same statement will be repeatedly executed (perhaps with
955+
/// different query parameters), consider using the `prepare` and
956+
/// `prepare_cached` methods.
939957
///
940-
/// ## Panics
958+
/// # Panics
941959
///
942960
/// Panics if the number of parameters provided does not match the number
943961
/// expected.
962+
///
963+
/// # Example
964+
///
965+
/// ```rust,no_run
966+
/// # use postgres::{Connection, SslMode};
967+
/// # let conn = Connection::connect("", SslMode::None).unwrap();
968+
/// # let baz = true;
969+
/// for row in &conn.query("SELECT foo FROM bar WHERE baz = $1", &[&baz]).unwrap() {
970+
/// let foo: i32 = row.get("foo");
971+
/// println!("foo: {}", foo);
972+
/// }
973+
/// ```
944974
pub fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>> {
945975
let (param_types, columns) = try!(self.conn.borrow_mut().raw_prepare("", query));
946976
let stmt = Statement::new(self, "".to_owned(), param_types, columns, Cell::new(0), true);
@@ -989,9 +1019,8 @@ impl Connection {
9891019

9901020
/// Creates a new prepared statement.
9911021
///
992-
/// A statement may contain parameters, specified by `$n` where `n` is the
993-
/// index of the parameter in the list provided at execution time,
994-
/// 1-indexed.
1022+
/// If the same statement will be executed repeatedly, explicitly preparing
1023+
/// it can improve performance.
9951024
///
9961025
/// The statement is associated with the connection that created it and may
9971026
/// not outlive that connection.
@@ -1016,8 +1045,8 @@ impl Connection {
10161045
///
10171046
/// Like `prepare`, except that the statement is only prepared once over
10181047
/// the lifetime of the connection and then cached. If the same statement
1019-
/// is going to be used frequently, caching it can improve performance by
1020-
/// reducing the number of round trips to the Postgres backend.
1048+
/// is going to be prepared frequently, caching it can improve performance
1049+
/// by reducing the number of round trips to the Postgres backend.
10211050
///
10221051
/// # Example
10231052
///

0 commit comments

Comments
 (0)