Skip to content

Commit 2dc80be

Browse files
committed
Documentation
1 parent ba1d9d1 commit 2dc80be

File tree

11 files changed

+146
-26
lines changed

11 files changed

+146
-26
lines changed

postgres-shared/src/lib.rs

+9
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,15 @@ pub mod error;
1515
pub mod params;
1616
pub mod types;
1717

18+
/// Contains information necessary to cancel queries for a session.
19+
#[derive(Copy, Clone, Debug)]
20+
pub struct CancelData {
21+
/// The process ID of the session.
22+
pub process_id: i32,
23+
/// The secret key for the session.
24+
pub secret_key: i32,
25+
}
26+
1827
pub struct RowData {
1928
buf: Vec<u8>,
2029
indices: Vec<Option<Range<usize>>>,

postgres-tokio/src/error.rs

+8
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Error types.
2+
13
use std::error;
24
use std::io;
35
use std::fmt;
@@ -7,10 +9,16 @@ use Connection;
79
#[doc(inline)]
810
pub use postgres_shared::error::*;
911

12+
/// A runtime error.
1013
#[derive(Debug)]
1114
pub enum Error<C = Connection> {
15+
/// An error communicating with the database.
16+
///
17+
/// IO errors are fatal - the connection is not returned.
1218
Io(io::Error),
19+
/// An error reported by the database.
1320
Db(Box<DbError>, C),
21+
/// An error converting between Rust and Postgres types.
1422
Conversion(Box<error::Error + Sync + Send>, C),
1523
}
1624

postgres-tokio/src/lib.rs

+76-17
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
//! An asynchronous Postgres driver.
2+
#![warn(missing_docs)]
3+
14
extern crate fallible_iterator;
25
extern crate futures;
36
extern crate futures_state_stream;
@@ -28,11 +31,11 @@ use std::sync::mpsc::{self, Sender, Receiver};
2831
use tokio_core::reactor::Handle;
2932

3033
#[doc(inline)]
31-
pub use postgres_shared::{params, Column, RowIndex};
34+
pub use postgres_shared::{params, CancelData};
3235

3336
use error::{ConnectError, Error, DbError, SqlState};
3437
use params::{ConnectParams, IntoConnectParams};
35-
use stmt::Statement;
38+
use stmt::{Statement, Column};
3639
use stream::PostgresStream;
3740
use tls::Handshake;
3841
use transaction::Transaction;
@@ -55,18 +58,27 @@ const TYPEINFO_QUERY: &'static str = "__typeinfo";
5558
const TYPEINFO_ENUM_QUERY: &'static str = "__typeinfo_enum";
5659
const TYPEINFO_COMPOSITE_QUERY: &'static str = "__typeinfo_composite";
5760

61+
/// Specifies the TLS support required for a new connection.
5862
pub enum TlsMode {
63+
/// The connection must use TLS.
5964
Require(Box<Handshake>),
65+
/// The connection will use TLS if available.
6066
Prefer(Box<Handshake>),
67+
/// The connection will not use TLS.
6168
None,
6269
}
6370

64-
#[derive(Debug, Copy, Clone)]
65-
pub struct CancelData {
66-
pub process_id: i32,
67-
pub secret_key: i32,
68-
}
69-
71+
/// Attempts to cancel an in-progress query.
72+
///
73+
/// The backend provides no information about whether a cancellation attempt
74+
/// was successful or not. An error will only be returned if the driver was
75+
/// unable to connect to the database.
76+
///
77+
/// A `CancelData` object can be created via `Connection::cancel_data`. The
78+
/// object can cancel any query made on that connection.
79+
///
80+
/// Only the host and port of the connection info are used. See
81+
/// `Connection::connect` for details of the `params` argument.
7082
pub fn cancel_query<T>(params: T,
7183
tls_mode: TlsMode,
7284
cancel_data: CancelData,
@@ -161,6 +173,7 @@ impl Sink for InnerConnection {
161173
}
162174
}
163175

176+
/// A connection to a Postgres database.
164177
pub struct Connection(InnerConnection);
165178

166179
// FIXME fill out
@@ -172,6 +185,24 @@ impl fmt::Debug for Connection {
172185
}
173186

174187
impl Connection {
188+
/// Creates a new connection to a Postgres database.
189+
///
190+
/// Most applications can use a URL string in the normal format:
191+
///
192+
/// ```notrust
193+
/// postgresql://user[:password]@host[:port][/database][?param1=val1[[&param2=val2]...]]
194+
/// ```
195+
///
196+
/// The password may be omitted if not required. The default Postgres port
197+
/// (5432) is used if none is specified. The database name defaults to the
198+
/// username if not specified.
199+
///
200+
/// To connect to the server via Unix sockets, `host` should be set to the
201+
/// absolute path of the directory containing the socket file. Since `/` is
202+
/// a reserved character in URLs, the path should be URL encoded. If the
203+
/// path contains non-UTF 8 characters, a `ConnectParams` struct should be
204+
/// created manually and passed in. Note that Postgres does not support TLS
205+
/// over Unix sockets.
175206
pub fn connect<T>(params: T,
176207
tls_mode: TlsMode,
177208
handle: &Handle)
@@ -421,6 +452,19 @@ impl Connection {
421452
.boxed()
422453
}
423454

455+
/// Execute a sequence of SQL statements.
456+
///
457+
/// Statements should be separated by `;` characters. If an error occurs,
458+
/// execution of the sequence will stop at that point. This is intended for
459+
/// execution of batches of non-dynamic statements - for example, creation
460+
/// of a schema for a fresh database.
461+
///
462+
/// # Warning
463+
///
464+
/// Prepared statements should be used for any SQL statement which contains
465+
/// user-specified data, as it provides functionality to safely embed that
466+
/// data in the statement. Do not form statements via string concatenation
467+
/// and feed them into this method.
424468
pub fn batch_execute(self, query: &str) -> BoxFuture<Connection, Error> {
425469
self.simple_query(query)
426470
.map(|r| r.1)
@@ -873,6 +917,7 @@ impl Connection {
873917
.boxed()
874918
}
875919

920+
/// Creates a new prepared statement.
876921
pub fn prepare(mut self, query: &str) -> BoxFuture<(Statement, Connection), Error> {
877922
let id = self.0.next_stmt_id;
878923
self.0.next_stmt_id += 1;
@@ -888,12 +933,24 @@ impl Connection {
888933
.boxed()
889934
}
890935

936+
/// Executes a statement, returning the number of rows modified.
937+
///
938+
/// # Panics
939+
///
940+
/// Panics if the number of parameters provided does not match the number
941+
/// expected.
891942
pub fn execute(self, statement: &Statement, params: &[&ToSql]) -> BoxFuture<(u64, Connection), Error> {
892943
self.raw_execute(statement.name(), "", statement.parameters(), params)
893944
.and_then(|conn| conn.finish_execute())
894945
.boxed()
895946
}
896947

948+
/// Executes a statement, returning a stream over the resulting rows.
949+
///
950+
/// # Panics
951+
///
952+
/// Panics if the number of parameters provided does not match the number
953+
/// expected.
897954
pub fn query(self,
898955
statement: &Statement,
899956
params: &[&ToSql])
@@ -905,24 +962,26 @@ impl Connection {
905962
.boxed()
906963
}
907964

965+
/// Starts a new transaction.
908966
pub fn transaction(self) -> BoxFuture<Transaction, Error> {
909967
self.simple_query("BEGIN")
910968
.map(|(_, c)| Transaction::new(c))
911969
.boxed()
912970
}
913971

914-
pub fn close(self) -> BoxFuture<(), Error> {
915-
let mut terminate = vec![];
916-
frontend::terminate(&mut terminate);
917-
self.0.send(terminate)
918-
.map(|_| ())
919-
.map_err(Error::Io)
920-
.boxed()
921-
}
922-
972+
/// Returns information used to cancel pending queries.
973+
///
974+
/// Used with the `cancel_query` function. The object returned can be used
975+
/// to cancel any query executed by the connection it was created from.
923976
pub fn cancel_data(&self) -> CancelData {
924977
self.0.cancel_data
925978
}
979+
980+
/// Returns the value of the specified Postgres backend parameter, such as
981+
/// `timezone` or `server_version`.
982+
pub fn parameter(&self, param: &str) -> Option<&str> {
983+
self.0.parameters.get(param).map(|s| &**s)
984+
}
926985
}
927986

928987
fn connect_err(fields: &mut ErrorFields) -> ConnectError {

postgres-tokio/src/rows.rs

+22
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Postgres rows.
2+
13
use postgres_shared::{RowData, Column};
24
use std::collections::HashMap;
35
use std::error::Error;
@@ -10,6 +12,7 @@ pub use postgres_shared::RowIndex;
1012
use RowNew;
1113
use types::{WrongType, FromSql, SessionInfo};
1214

15+
/// A row from Postgres.
1316
pub struct Row {
1417
columns: Arc<Vec<Column>>,
1518
data: RowData,
@@ -25,14 +28,25 @@ impl RowNew for Row {
2528
}
2629

2730
impl Row {
31+
/// Returns information about the columns in the row.
2832
pub fn columns(&self) -> &[Column] {
2933
&self.columns
3034
}
3135

36+
/// Returns the number of values in the row
3237
pub fn len(&self) -> usize {
3338
self.columns.len()
3439
}
3540

41+
/// Retrieves the contents of a field of the row.
42+
///
43+
/// A field can be accessed by the name or index of its column, though
44+
/// access by index is more efficient. Rows are 0-indexed.
45+
///
46+
/// # Panics
47+
///
48+
/// Panics if the index does not reference a column or the return type is
49+
/// not compatible with the Postgres type.
3650
pub fn get<T, I>(&self, idx: I) -> T
3751
where T: FromSql,
3852
I: RowIndex + fmt::Debug
@@ -44,6 +58,14 @@ impl Row {
4458
}
4559
}
4660

61+
/// Retrieves the contents of a field of the row.
62+
///
63+
/// A field can be accessed by the name or index of its column, though
64+
/// access by index is more efficient. Rows are 0-indexed.
65+
///
66+
/// Returns `None` if the index does not reference a column, `Some(Err(..))`
67+
/// if there was an error converting the result value, and `Some(Ok(..))`
68+
/// on success.
4769
pub fn try_get<T, I>(&self, idx: I) -> Result<Option<T>, Box<Error + Sync + Send>>
4870
where T: FromSql,
4971
I: RowIndex

postgres-tokio/src/stmt.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! Prepared statements.
2+
13
use std::mem;
24
use std::sync::Arc;
35
use std::sync::mpsc::Sender;
@@ -8,6 +10,7 @@ pub use postgres_shared::Column;
810
use StatementNew;
911
use types::Type;
1012

13+
/// A prepared statement.
1114
pub struct Statement {
1215
close_sender: Sender<(u8, String)>,
1316
name: String,
@@ -46,10 +49,12 @@ impl Drop for Statement {
4649
}
4750

4851
impl Statement {
52+
/// Returns the types of query parameters for this statement.
4953
pub fn parameters(&self) -> &[Type] {
5054
&self.params
5155
}
5256

57+
/// Returns information about the resulting columns for this statement.
5358
pub fn columns(&self) -> &[Column] {
5459
&self.columns
5560
}

postgres-tokio/src/stream.rs

+1
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ pub fn connect(host: ConnectTarget,
7979
.boxed()
8080
}
8181

82+
/// A raw connection to the database.
8283
pub struct Stream(InnerStream);
8384

8485
enum InnerStream {

postgres-tokio/src/tls/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! TLS support.
2+
13
use futures::BoxFuture;
24
use std::error::Error;
35
use tokio_core::io::Io;
@@ -7,9 +9,12 @@ pub use stream::Stream;
79
#[cfg(feature = "with-openssl")]
810
pub mod openssl;
911

12+
/// A trait implemented by streams returned from `Handshake` implementations.
1013
pub trait TlsStream: Io + Send {
14+
/// Returns a shared reference to the inner stream.
1115
fn get_ref(&self) -> &Stream;
1216

17+
/// Returns a mutable reference to the inner stream.
1318
fn get_mut(&mut self) -> &mut Stream;
1419
}
1520

@@ -25,7 +30,9 @@ impl TlsStream for Stream {
2530
}
2631
}
2732

33+
/// A trait implemented by types that can manage TLS encryption for a stream.
2834
pub trait Handshake: 'static + Sync + Send {
35+
/// Performs a TLS handshake, returning a wrapped stream.
2936
fn handshake(self: Box<Self>,
3037
host: &str,
3138
stream: Stream)

postgres-tokio/src/tls/openssl.rs

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
//! OpenSSL support.
2+
13
use futures::{Future, BoxFuture};
24
use openssl::ssl::{SslMethod, SslConnector, SslConnectorBuilder};
35
use openssl::error::ErrorStack;
@@ -16,9 +18,11 @@ impl TlsStream for SslStream<Stream> {
1618
}
1719
}
1820

21+
/// A `Handshake` implementation using OpenSSL.
1922
pub struct OpenSsl(SslConnector);
2023

2124
impl OpenSsl {
25+
/// Creates a new `OpenSsl` with default settings.
2226
pub fn new() -> Result<OpenSsl, ErrorStack> {
2327
let connector = try!(SslConnectorBuilder::new(SslMethod::tls())).build();
2428
Ok(OpenSsl(connector))

0 commit comments

Comments
 (0)