Skip to content

Commit 0916a53

Browse files
committed
Make lazy_query result return a Result
1 parent 78c96f2 commit 0916a53

3 files changed

Lines changed: 29 additions & 54 deletions

File tree

README.md

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,8 @@ Connecting
8080
----------
8181
Connect to a Postgres server using the standard URI format:
8282
```rust
83-
let conn = PostgresConnection::connect("postgres://user:pass@host:port/database?arg1=val1&arg2=val2",
84-
&NoSsl);
83+
let conn = try!(PostgresConnection::connect("postgres://user:pass@host:port/database?arg1=val1&arg2=val2",
84+
&NoSsl));
8585
```
8686
`pass` may be omitted if not needed. `port` defaults to `5432` and `database`
8787
defaults to the value of `user` if not specified. The driver supports `trust`,
@@ -92,7 +92,7 @@ Statement Preparation
9292
Prepared statements can have parameters, represented as `$n` where `n` is an
9393
index into the parameter array starting from 1:
9494
```rust
95-
let stmt = conn.prepare("SELECT * FROM foo WHERE bar = $1 AND baz = $2");
95+
let stmt = try!(conn.prepare("SELECT * FROM foo WHERE bar = $1 AND baz = $2"));
9696
```
9797

9898
Querying
@@ -111,8 +111,8 @@ fields in a row can be accessed either by their indices or their column names,
111111
though access by index is more efficient. Like statement parameters, result
112112
columns are one-indexed.
113113
```rust
114-
let stmt = conn.prepare("SELECT bar, baz FROM foo");
115-
for row in stmt.query([]) {
114+
let stmt = try!(conn.prepare("SELECT bar, baz FROM foo"));
115+
for row in try!(stmt.query([])) {
116116
let bar: i32 = row[1];
117117
let baz: ~str = row["baz"];
118118
println!("bar: {}, baz: {}", bar, baz);
@@ -121,8 +121,8 @@ for row in stmt.query([]) {
121121
In addition, `PostgresConnection` has a utility `execute` method which is useful
122122
if a statement is only going to be executed once:
123123
```rust
124-
let updates = conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2",
125-
[&1i32 as &ToSql, & &"biz" as &ToSql]);
124+
let updates = try!(conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2",
125+
[&1i32 as &ToSql, & &"biz" as &ToSql]));
126126
println!("{} rows were updated", updates);
127127
```
128128

@@ -133,9 +133,9 @@ The `transaction` method will start a new transaction. It returns a
133133
`PostgresConnection` as well as methods to control the result of the
134134
transaction:
135135
```rust
136-
let trans = conn.transaction();
137-
trans.execute(...);
138-
let stmt = trans.prepare(...);
136+
let trans = try!(conn.transaction());
137+
try!(trans.execute(...));
138+
let stmt = try!(trans.prepare(...));
139139

140140
if a_bad_thing_happened {
141141
trans.set_rollback();
@@ -151,37 +151,20 @@ The transaction will be active until the `PostgresTransaction` object falls out
151151
of scope. A transaction will commit by default. Nested transactions are
152152
supported via savepoints.
153153

154-
Error Handling
155-
--------------
156-
The methods described above will fail if there is an error. For each of these
157-
methods, there is a second variant prefixed with `try_` which returns a
158-
`Result`:
159-
```rust
160-
match conn.try_execute(query, params) {
161-
Ok(updates) => println!("{} rows were updated", updates),
162-
Err(PgDbError(PostgresDbError { code: NotNullViolation, .. })) =>
163-
println!("Something was NULL that shouldn't be"),
164-
Err(PgDbError(PostgresDbError { code: SyntaxError, .. })) =>
165-
println!("Invalid query syntax"),
166-
_ => println!("A bad thing happened: {}", err),
167-
}
168-
}
169-
```
170-
171154
Connection Pooling
172155
------------------
173156
A very basic fixed-size connection pool is provided in the `pool` module. A
174157
single pool can be shared across tasks and `get_connection` will block until a
175158
connection is available.
176159
```rust
177-
let pool = PostgresConnectionPool::new("postgres://postgres@localhost",
178-
NoSsl, 5);
160+
let pool = try!(PostgresConnectionPool::new("postgres://postgres@localhost",
161+
NoSsl, 5));
179162

180163
for _ in range(0, 10) {
181164
let pool = pool.clone();
182165
spawn(proc() {
183166
let conn = pool.get_connection();
184-
conn.query(...);
167+
conn.query(...).unwrap();
185168
})
186169
}
187170
```

src/lib.rs

Lines changed: 15 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1307,30 +1307,28 @@ impl<'stmt> PostgresResult<'stmt> {
13071307
self.finish_inner()
13081308
}
13091309

1310-
/// Like `PostgresResult::next` except that it returns any errors to the
1311-
/// caller instead of failing.
1312-
pub fn try_next(&mut self) -> Result<Option<PostgresRow<'stmt>>,
1313-
PostgresError> {
1310+
fn try_next(&mut self) -> Option<Result<PostgresRow<'stmt>,
1311+
PostgresError>> {
13141312
if self.data.is_empty() && self.more_rows {
1315-
try!(self.execute());
1313+
match self.execute() {
1314+
Ok(()) => {}
1315+
Err(err) => return Some(Err(err))
1316+
}
13161317
}
13171318

1318-
let row = self.data.pop_front().map(|row| {
1319-
PostgresRow {
1319+
self.data.pop_front().map(|row| {
1320+
Ok(PostgresRow {
13201321
stmt: self.stmt,
13211322
data: row
1322-
}
1323-
});
1324-
Ok(row)
1323+
})
1324+
})
13251325
}
13261326
}
13271327

13281328
impl<'stmt> Iterator<PostgresRow<'stmt>> for PostgresResult<'stmt> {
13291329
fn next(&mut self) -> Option<PostgresRow<'stmt>> {
1330-
match self.try_next() {
1331-
Ok(ok) => ok,
1332-
Err(err) => fail!("Error fetching rows: {}", err)
1333-
}
1330+
// we'll never hit the network on a non-lazy result
1331+
self.try_next().map(|r| r.unwrap())
13341332
}
13351333

13361334
fn size_hint(&self) -> (uint, Option<uint>) {
@@ -1426,18 +1424,12 @@ impl<'trans, 'stmt> PostgresLazyResult<'trans, 'stmt> {
14261424
pub fn finish(self) -> Result<(), PostgresError> {
14271425
self.result.finish()
14281426
}
1429-
1430-
/// Like `PostgresResult::try_next`.
1431-
pub fn try_next(&mut self) -> Result<Option<PostgresRow<'stmt>>,
1432-
PostgresError> {
1433-
self.result.try_next()
1434-
}
14351427
}
14361428

1437-
impl<'trans, 'stmt> Iterator<PostgresRow<'stmt>>
1429+
impl<'trans, 'stmt> Iterator<Result<PostgresRow<'stmt>, PostgresError>>
14381430
for PostgresLazyResult<'trans, 'stmt> {
1439-
fn next(&mut self) -> Option<PostgresRow<'stmt>> {
1440-
self.result.next()
1431+
fn next(&mut self) -> Option<Result<PostgresRow<'stmt>, PostgresError>> {
1432+
self.result.try_next()
14411433
}
14421434

14431435
fn size_hint(&self) -> (uint, Option<uint>) {

src/test.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ fn test_lazy_query() {
302302
}
303303
let stmt = or_fail!(conn.prepare("SELECT id FROM foo ORDER BY id"));
304304
let result = or_fail!(trans.lazy_query(&stmt, [], 2));
305-
assert_eq!(values, result.map(|row| row[1]).collect());
305+
assert_eq!(values, result.map(|row| row.unwrap()[1]).collect());
306306

307307
trans.set_rollback();
308308
}

0 commit comments

Comments
 (0)