From 2dc80bec2e356fb7fac02946530d20a00e05f9ab Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Mon, 26 Dec 2016 16:21:20 -0500 Subject: [PATCH] Documentation --- postgres-shared/src/lib.rs | 9 +++ postgres-tokio/src/error.rs | 8 +++ postgres-tokio/src/lib.rs | 93 +++++++++++++++++++++++++------ postgres-tokio/src/rows.rs | 22 ++++++++ postgres-tokio/src/stmt.rs | 5 ++ postgres-tokio/src/stream.rs | 1 + postgres-tokio/src/tls/mod.rs | 7 +++ postgres-tokio/src/tls/openssl.rs | 4 ++ postgres-tokio/src/transaction.rs | 9 +++ postgres-tokio/src/types.rs | 2 + postgres/src/lib.rs | 12 +--- 11 files changed, 146 insertions(+), 26 deletions(-) diff --git a/postgres-shared/src/lib.rs b/postgres-shared/src/lib.rs index 15d3d4e4..bc5b290f 100644 --- a/postgres-shared/src/lib.rs +++ b/postgres-shared/src/lib.rs @@ -15,6 +15,15 @@ pub mod error; pub mod params; pub mod types; +/// Contains information necessary to cancel queries for a session. +#[derive(Copy, Clone, Debug)] +pub struct CancelData { + /// The process ID of the session. + pub process_id: i32, + /// The secret key for the session. + pub secret_key: i32, +} + pub struct RowData { buf: Vec, indices: Vec>>, diff --git a/postgres-tokio/src/error.rs b/postgres-tokio/src/error.rs index b6219879..1d25cd0f 100644 --- a/postgres-tokio/src/error.rs +++ b/postgres-tokio/src/error.rs @@ -1,3 +1,5 @@ +//! Error types. + use std::error; use std::io; use std::fmt; @@ -7,10 +9,16 @@ use Connection; #[doc(inline)] pub use postgres_shared::error::*; +/// A runtime error. #[derive(Debug)] pub enum Error { + /// An error communicating with the database. + /// + /// IO errors are fatal - the connection is not returned. Io(io::Error), + /// An error reported by the database. Db(Box, C), + /// An error converting between Rust and Postgres types. Conversion(Box, C), } diff --git a/postgres-tokio/src/lib.rs b/postgres-tokio/src/lib.rs index 279818f5..6294cf2d 100644 --- a/postgres-tokio/src/lib.rs +++ b/postgres-tokio/src/lib.rs @@ -1,3 +1,6 @@ +//! An asynchronous Postgres driver. +#![warn(missing_docs)] + extern crate fallible_iterator; extern crate futures; extern crate futures_state_stream; @@ -28,11 +31,11 @@ use std::sync::mpsc::{self, Sender, Receiver}; use tokio_core::reactor::Handle; #[doc(inline)] -pub use postgres_shared::{params, Column, RowIndex}; +pub use postgres_shared::{params, CancelData}; use error::{ConnectError, Error, DbError, SqlState}; use params::{ConnectParams, IntoConnectParams}; -use stmt::Statement; +use stmt::{Statement, Column}; use stream::PostgresStream; use tls::Handshake; use transaction::Transaction; @@ -55,18 +58,27 @@ const TYPEINFO_QUERY: &'static str = "__typeinfo"; const TYPEINFO_ENUM_QUERY: &'static str = "__typeinfo_enum"; const TYPEINFO_COMPOSITE_QUERY: &'static str = "__typeinfo_composite"; +/// Specifies the TLS support required for a new connection. pub enum TlsMode { + /// The connection must use TLS. Require(Box), + /// The connection will use TLS if available. Prefer(Box), + /// The connection will not use TLS. None, } -#[derive(Debug, Copy, Clone)] -pub struct CancelData { - pub process_id: i32, - pub secret_key: i32, -} - +/// Attempts to cancel an in-progress query. +/// +/// The backend provides no information about whether a cancellation attempt +/// was successful or not. An error will only be returned if the driver was +/// unable to connect to the database. +/// +/// A `CancelData` object can be created via `Connection::cancel_data`. The +/// object can cancel any query made on that connection. +/// +/// Only the host and port of the connection info are used. See +/// `Connection::connect` for details of the `params` argument. pub fn cancel_query(params: T, tls_mode: TlsMode, cancel_data: CancelData, @@ -161,6 +173,7 @@ impl Sink for InnerConnection { } } +/// A connection to a Postgres database. pub struct Connection(InnerConnection); // FIXME fill out @@ -172,6 +185,24 @@ impl fmt::Debug for Connection { } impl Connection { + /// Creates a new connection to a Postgres database. + /// + /// Most applications can use a URL string in the normal format: + /// + /// ```notrust + /// postgresql://user[:password]@host[:port][/database][?param1=val1[[¶m2=val2]...]] + /// ``` + /// + /// 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. + /// + /// To connect to the server via Unix sockets, `host` should be set to the + /// absolute path of the directory containing the socket file. Since `/` is + /// a reserved character in URLs, the path should be URL encoded. If the + /// path contains non-UTF 8 characters, a `ConnectParams` struct should be + /// created manually and passed in. Note that Postgres does not support TLS + /// over Unix sockets. pub fn connect(params: T, tls_mode: TlsMode, handle: &Handle) @@ -421,6 +452,19 @@ impl Connection { .boxed() } + /// Execute a sequence of SQL statements. + /// + /// Statements should be separated by `;` characters. If an error occurs, + /// execution of the sequence will stop at that point. This is intended for + /// execution of batches of non-dynamic statements - for example, creation + /// of a schema for a fresh database. + /// + /// # Warning + /// + /// Prepared statements should be used for any SQL statement which contains + /// user-specified data, as it provides functionality to safely embed that + /// data in the statement. Do not form statements via string concatenation + /// and feed them into this method. pub fn batch_execute(self, query: &str) -> BoxFuture { self.simple_query(query) .map(|r| r.1) @@ -873,6 +917,7 @@ impl Connection { .boxed() } + /// Creates a new prepared statement. pub fn prepare(mut self, query: &str) -> BoxFuture<(Statement, Connection), Error> { let id = self.0.next_stmt_id; self.0.next_stmt_id += 1; @@ -888,12 +933,24 @@ impl Connection { .boxed() } + /// Executes a statement, returning the number of rows modified. + /// + /// # Panics + /// + /// Panics if the number of parameters provided does not match the number + /// expected. pub fn execute(self, statement: &Statement, params: &[&ToSql]) -> BoxFuture<(u64, Connection), Error> { self.raw_execute(statement.name(), "", statement.parameters(), params) .and_then(|conn| conn.finish_execute()) .boxed() } + /// Executes a statement, returning a stream over the resulting rows. + /// + /// # Panics + /// + /// Panics if the number of parameters provided does not match the number + /// expected. pub fn query(self, statement: &Statement, params: &[&ToSql]) @@ -905,24 +962,26 @@ impl Connection { .boxed() } + /// Starts a new transaction. pub fn transaction(self) -> BoxFuture { self.simple_query("BEGIN") .map(|(_, c)| Transaction::new(c)) .boxed() } - pub fn close(self) -> BoxFuture<(), Error> { - let mut terminate = vec![]; - frontend::terminate(&mut terminate); - self.0.send(terminate) - .map(|_| ()) - .map_err(Error::Io) - .boxed() - } - + /// Returns information used to cancel pending queries. + /// + /// Used with the `cancel_query` function. The object returned can be used + /// to cancel any query executed by the connection it was created from. pub fn cancel_data(&self) -> CancelData { self.0.cancel_data } + + /// Returns the value of the specified Postgres backend parameter, such as + /// `timezone` or `server_version`. + pub fn parameter(&self, param: &str) -> Option<&str> { + self.0.parameters.get(param).map(|s| &**s) + } } fn connect_err(fields: &mut ErrorFields) -> ConnectError { diff --git a/postgres-tokio/src/rows.rs b/postgres-tokio/src/rows.rs index 238d6882..8705fb9c 100644 --- a/postgres-tokio/src/rows.rs +++ b/postgres-tokio/src/rows.rs @@ -1,3 +1,5 @@ +//! Postgres rows. + use postgres_shared::{RowData, Column}; use std::collections::HashMap; use std::error::Error; @@ -10,6 +12,7 @@ pub use postgres_shared::RowIndex; use RowNew; use types::{WrongType, FromSql, SessionInfo}; +/// A row from Postgres. pub struct Row { columns: Arc>, data: RowData, @@ -25,14 +28,25 @@ impl RowNew for Row { } impl Row { + /// Returns information about the columns in the row. pub fn columns(&self) -> &[Column] { &self.columns } + /// Returns the number of values in the row pub fn len(&self) -> usize { self.columns.len() } + /// Retrieves the contents of a field of the row. + /// + /// A field can be accessed by the name or index of its column, though + /// access by index is more efficient. Rows are 0-indexed. + /// + /// # Panics + /// + /// Panics if the index does not reference a column or the return type is + /// not compatible with the Postgres type. pub fn get(&self, idx: I) -> T where T: FromSql, I: RowIndex + fmt::Debug @@ -44,6 +58,14 @@ impl Row { } } + /// Retrieves the contents of a field of the row. + /// + /// A field can be accessed by the name or index of its column, though + /// access by index is more efficient. Rows are 0-indexed. + /// + /// Returns `None` if the index does not reference a column, `Some(Err(..))` + /// if there was an error converting the result value, and `Some(Ok(..))` + /// on success. pub fn try_get(&self, idx: I) -> Result, Box> where T: FromSql, I: RowIndex diff --git a/postgres-tokio/src/stmt.rs b/postgres-tokio/src/stmt.rs index 70dc5728..0bf17275 100644 --- a/postgres-tokio/src/stmt.rs +++ b/postgres-tokio/src/stmt.rs @@ -1,3 +1,5 @@ +//! Prepared statements. + use std::mem; use std::sync::Arc; use std::sync::mpsc::Sender; @@ -8,6 +10,7 @@ pub use postgres_shared::Column; use StatementNew; use types::Type; +/// A prepared statement. pub struct Statement { close_sender: Sender<(u8, String)>, name: String, @@ -46,10 +49,12 @@ impl Drop for Statement { } impl Statement { + /// Returns the types of query parameters for this statement. pub fn parameters(&self) -> &[Type] { &self.params } + /// Returns information about the resulting columns for this statement. pub fn columns(&self) -> &[Column] { &self.columns } diff --git a/postgres-tokio/src/stream.rs b/postgres-tokio/src/stream.rs index 73753fb9..bfcbfaf9 100644 --- a/postgres-tokio/src/stream.rs +++ b/postgres-tokio/src/stream.rs @@ -79,6 +79,7 @@ pub fn connect(host: ConnectTarget, .boxed() } +/// A raw connection to the database. pub struct Stream(InnerStream); enum InnerStream { diff --git a/postgres-tokio/src/tls/mod.rs b/postgres-tokio/src/tls/mod.rs index 6701b5ce..32053ab7 100644 --- a/postgres-tokio/src/tls/mod.rs +++ b/postgres-tokio/src/tls/mod.rs @@ -1,3 +1,5 @@ +//! TLS support. + use futures::BoxFuture; use std::error::Error; use tokio_core::io::Io; @@ -7,9 +9,12 @@ pub use stream::Stream; #[cfg(feature = "with-openssl")] pub mod openssl; +/// A trait implemented by streams returned from `Handshake` implementations. pub trait TlsStream: Io + Send { + /// Returns a shared reference to the inner stream. fn get_ref(&self) -> &Stream; + /// Returns a mutable reference to the inner stream. fn get_mut(&mut self) -> &mut Stream; } @@ -25,7 +30,9 @@ impl TlsStream for Stream { } } +/// A trait implemented by types that can manage TLS encryption for a stream. pub trait Handshake: 'static + Sync + Send { + /// Performs a TLS handshake, returning a wrapped stream. fn handshake(self: Box, host: &str, stream: Stream) diff --git a/postgres-tokio/src/tls/openssl.rs b/postgres-tokio/src/tls/openssl.rs index d9a78508..986f4339 100644 --- a/postgres-tokio/src/tls/openssl.rs +++ b/postgres-tokio/src/tls/openssl.rs @@ -1,3 +1,5 @@ +//! OpenSSL support. + use futures::{Future, BoxFuture}; use openssl::ssl::{SslMethod, SslConnector, SslConnectorBuilder}; use openssl::error::ErrorStack; @@ -16,9 +18,11 @@ impl TlsStream for SslStream { } } +/// A `Handshake` implementation using OpenSSL. pub struct OpenSsl(SslConnector); impl OpenSsl { + /// Creates a new `OpenSsl` with default settings. pub fn new() -> Result { let connector = try!(SslConnectorBuilder::new(SslMethod::tls())).build(); Ok(OpenSsl(connector)) diff --git a/postgres-tokio/src/transaction.rs b/postgres-tokio/src/transaction.rs index 19ddf50f..31957481 100644 --- a/postgres-tokio/src/transaction.rs +++ b/postgres-tokio/src/transaction.rs @@ -1,3 +1,5 @@ +//! Transactions. + use futures::{Future, BoxFuture}; use futures_state_stream::{StateStream, BoxStateStream}; @@ -7,6 +9,7 @@ use stmt::Statement; use types::ToSql; use rows::Row; +/// An in progress Postgres transaction. #[derive(Debug)] pub struct Transaction(Connection); @@ -17,6 +20,7 @@ impl TransactionNew for Transaction { } impl Transaction { + /// Like `Connection::batch_execute`. pub fn batch_execute(self, query: &str) -> BoxFuture> { self.0.batch_execute(query) .map(Transaction) @@ -24,6 +28,7 @@ impl Transaction { .boxed() } + /// Like `Connection::prepare`. pub fn prepare(self, query: &str) -> BoxFuture<(Statement, Transaction), Error> { self.0.prepare(query) .map(|(s, c)| (s, Transaction(c))) @@ -31,6 +36,7 @@ impl Transaction { .boxed() } + /// Like `Connection::execute`. pub fn execute(self, statement: &Statement, params: &[&ToSql]) @@ -41,6 +47,7 @@ impl Transaction { .boxed() } + /// Like `Connection::query`. pub fn query(self, statement: &Statement, params: &[&ToSql]) @@ -51,10 +58,12 @@ impl Transaction { .boxed() } + /// Commits the transaction. pub fn commit(self) -> BoxFuture { self.finish("COMMIT") } + /// Rolls back the transaction. pub fn rollback(self) -> BoxFuture { self.finish("ROLLBACK") } diff --git a/postgres-tokio/src/types.rs b/postgres-tokio/src/types.rs index aa172ad9..4f6b6582 100644 --- a/postgres-tokio/src/types.rs +++ b/postgres-tokio/src/types.rs @@ -1,3 +1,5 @@ +//! Postgres types + pub use postgres_shared::types::*; /// Generates a simple implementation of `ToSql::accepts` which accepts the diff --git a/postgres/src/lib.rs b/postgres/src/lib.rs index b4e4a96c..987f93c9 100644 --- a/postgres/src/lib.rs +++ b/postgres/src/lib.rs @@ -103,6 +103,9 @@ use stmt::{Statement, Column}; use transaction::{Transaction, IsolationLevel}; use types::{IsNull, Kind, Type, SessionInfo, Oid, Other, ToSql, FromSql, Field}; +#[doc(inline)] +pub use postgres_shared::CancelData; + #[macro_use] mod macros; @@ -151,15 +154,6 @@ impl HandleNotice for LoggingNoticeHandler { } } -/// Contains information necessary to cancel queries for a session. -#[derive(Copy, Clone, Debug)] -pub struct CancelData { - /// The process ID of the session. - pub process_id: i32, - /// The secret key for the session. - pub secret_key: i32, -} - /// Attempts to cancel an in-progress query. /// /// The backend provides no information about whether a cancellation attempt