Add examples!

This commit is contained in:
Steven Fackler 2014-03-09 15:22:20 -07:00
parent 999804a840
commit 58571cab26
3 changed files with 128 additions and 4 deletions

View File

@ -267,6 +267,24 @@ pub struct PostgresCancelData {
/// A `PostgresCancelData` object can be created via
/// `PostgresConnection::cancel_data`. The object can cancel any query made on
/// that connection.
///
/// # Example
///
/// ```rust
/// # extern crate postgres;
/// # fn main() {}
/// # fn foo() {
/// # use postgres::{PostgresConnection, NoSsl};
/// # let url = "";
/// let conn = PostgresConnection::connect(url, &NoSsl);
/// let cancel_data = conn.cancel_data();
/// spawn(proc() {
/// conn.execute("SOME EXPENSIVE QUERY", []);
/// });
/// # let _ =
/// postgres::cancel_query(url, &NoSsl, cancel_data);
/// # }
/// ```
pub fn cancel_query(url: &str, ssl: &SslMode, data: PostgresCancelData)
-> Result<(), PostgresConnectError> {
let Url { host, port, .. }: Url = match FromStr::from_str(url) {
@ -691,6 +709,21 @@ impl PostgresConnection {
/// The password may be omitted if not required. The default Postgres port
/// (5432) is used if none is specified. The database name defaults to the
/// username if not specified.
///
/// # Example
///
/// ```rust
/// # fn main() {}
/// # fn foo() {
/// # use postgres::{PostgresConnection, NoSsl};
/// let url = "postgres://postgres:hunter2@localhost:2994/foodb";
/// let maybe_conn = PostgresConnection::try_connect(url, &NoSsl);
/// let conn = match maybe_conn {
/// Ok(conn) => conn,
/// Err(err) => fail!("Error connecting: {}", err)
/// };
/// # }
/// ```
pub fn try_connect(url: &str, ssl: &SslMode)
-> Result<PostgresConnection, PostgresConnectError> {
InnerPostgresConnection::try_connect(url, ssl).map(|conn| {
@ -736,6 +769,20 @@ impl PostgresConnection {
///
/// The statement is associated with the connection that created it and may
/// not outlive that connection.
///
/// # Example
///
/// ```rust
/// # use postgres::{PostgresConnection, NoSsl};
/// # fn main() {}
/// # fn foo() {
/// # let conn = PostgresConnection::connect("", &NoSsl);
/// let maybe_stmt = conn.try_prepare("SELECT foo FROM bar WHERE baz = $1");
/// let stmt = match maybe_stmt {
/// Ok(stmt) => stmt,
/// Err(err) => fail!("Error preparing statement: {}", err)
/// };
/// # }
pub fn try_prepare<'a>(&'a self, query: &str)
-> Result<NormalPostgresStatement<'a>, PostgresError> {
self.conn.with_mut(|conn| conn.try_prepare(query, self))
@ -761,6 +808,26 @@ impl PostgresConnection {
/// is active until the `PostgresTransaction` object falls out of scope.
/// A transaction will commit by default unless the task fails or the
/// transaction is set to roll back.
///
/// # Example
///
/// ```rust
/// # use postgres::{PostgresConnection, NoSsl};
/// # fn main() {}
/// # fn foo() -> Result<(), postgres::error::PostgresError> {
/// # let conn = PostgresConnection::connect("", &NoSsl);
/// let trans = try!(conn.try_transaction());
/// trans.execute("UPDATE foo SET bar = 10", []);
///
/// # let something_bad_happened = true;
/// if something_bad_happened {
/// trans.set_rollback();
/// }
///
/// drop(trans);
/// # Ok(())
/// # }
/// ```
pub fn try_transaction<'a>(&'a self)
-> Result<PostgresTransaction<'a>, PostgresError> {
check_desync!(self);

View File

@ -33,6 +33,25 @@ impl InnerConnectionPool {
/// A simple fixed-size Postgres connection pool.
///
/// It can be shared across tasks.
///
/// # Example
///
/// ```rust
/// # use postgres::NoSsl;
/// # use postgres::pool::PostgresConnectionPool;
/// # fn main() {}
/// # fn foo() {
/// let pool = PostgresConnectionPool::new("postgres://postgres@localhost",
/// NoSsl, 5);
/// for _ in range(0, 10) {
/// let pool = pool.clone();
/// spawn(proc() {
/// let conn = pool.get_connection();
/// conn.execute("UPDATE foo SET bar = 1", []);
/// });
/// }
/// # }
/// ```
#[deriving(Clone)]
pub struct PostgresConnectionPool {
priv pool: MutexArc<InnerConnectionPool>

View File

@ -37,6 +37,23 @@ pub trait PostgresStatement {
///
/// Fails if the number or types of the provided parameters do not match
/// the parameters of the statement.
///
/// # Example
///
/// ```rust
/// # use postgres::{PostgresConnection, NoSsl, PostgresStatement};
/// # use postgres::types::ToSql;
/// # fn main() {}
/// # fn foo() {
/// # let conn = PostgresConnection::connect("", &NoSsl);
/// # let bar = 1i32;
/// # let baz = true;
/// let stmt = conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2");
/// match stmt.try_execute([&bar as &ToSql, &baz as &ToSql]) {
/// Ok(count) => println!("{} row(s) updated", count),
/// Err(err) => println!("Error executing query: {}", err)
/// }
/// # }
fn try_execute(&self, params: &[&ToSql]) -> Result<uint, PostgresError>;
/// A convenience function wrapping `try_execute`.
@ -47,7 +64,7 @@ pub trait PostgresStatement {
fn execute(&self, params: &[&ToSql]) -> uint {
match self.try_execute(params) {
Ok(count) => count,
Err(err) => fail!("Error running query\n{}", err.to_str())
Err(err) => fail!("Error running query\n{}", err)
}
}
@ -58,6 +75,27 @@ pub trait PostgresStatement {
///
/// Fails if the number or types of the provided parameters do not match
/// the parameters of the statement.
///
/// # Example
///
/// ```rust
/// # use postgres::{PostgresConnection, NoSsl, PostgresStatement};
/// # use postgres::types::ToSql;
/// # fn main() {}
/// # fn foo() {
/// # let conn = PostgresConnection::connect("", &NoSsl);
/// let stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1");
/// # let baz = true;
/// let mut rows = match stmt.try_query([&baz as &ToSql]) {
/// Ok(rows) => rows,
/// Err(err) => fail!("Error running query: {}", err)
/// };
/// for row in rows {
/// let foo: i32 = row["foo"];
/// println!("foo: {}", foo);
/// }
/// # }
/// ```
fn try_query<'a>(&'a self, params: &[&ToSql])
-> Result<PostgresResult<'a>, PostgresError>;
@ -69,7 +107,7 @@ pub trait PostgresStatement {
fn query<'a>(&'a self, params: &[&ToSql]) -> PostgresResult<'a> {
match self.try_query(params) {
Ok(result) => result,
Err(err) => fail!("Error executing query:\n{}", err.to_str())
Err(err) => fail!("Error executing query:\n{}", err)
}
}
@ -431,8 +469,8 @@ impl<'stmt> PostgresResult<'stmt> {
/// Like `PostgresResult::next` except that it returns any errors to the
/// caller instead of failing.
pub fn try_next(&mut self)
-> Result<Option<PostgresRow<'stmt>>, PostgresError> {
pub fn try_next(&mut self) -> Result<Option<PostgresRow<'stmt>>,
PostgresError> {
if self.data.is_empty() && self.more_rows {
try!(self.execute());
}