Skip to content

Commit e372cdc

Browse files
committed
Docs
1 parent 1f6d9dd commit e372cdc

File tree

3 files changed

+203
-33
lines changed

3 files changed

+203
-33
lines changed

tokio-postgres/src/config.rs

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,13 @@ use crate::proto::HandshakeFuture;
2222
use crate::{Connect, MakeTlsMode, Socket};
2323
use crate::{Error, Handshake, TlsMode};
2424

25+
/// Properties required of a database.
2526
#[cfg(feature = "runtime")]
2627
#[derive(Debug, Copy, Clone, PartialEq)]
2728
pub enum TargetSessionAttrs {
29+
/// No special permissions are required.
2830
Any,
31+
/// The database must be writable.
2932
ReadWrite,
3033
#[doc(hidden)]
3134
__NonExhaustive,
@@ -60,6 +63,77 @@ pub(crate) struct Inner {
6063
pub(crate) target_session_attrs: TargetSessionAttrs,
6164
}
6265

66+
/// Connection configuration.
67+
///
68+
/// Configuration can be parsed from libpq-style connection strings. These strings come in two formats:
69+
///
70+
/// # Key-Value
71+
///
72+
/// This format consists of space-separated key-value pairs. Values which are either the empty string or contain
73+
/// whitespace should be wrapped in `'`. `'` and `\` characters should be backslash-escaped.
74+
///
75+
/// ## Keys
76+
///
77+
/// * `user` - The username to authenticate with. Required.
78+
/// * `password` - The password to authenticate with.
79+
/// * `dbname` - The name of the database to connect to. Defaults to the username.
80+
/// * `options` - Command line options used to configure the server.
81+
/// * `application_name` - Sets the `application_name` parameter on the server.
82+
/// * `host` - The host to connect to. On Unix platforms, if the host starts with a `/` character it is treated as the
83+
/// path to the directory containing Unix domain sockets. Otherwise, it is treated as a hostname. Multiple hosts
84+
/// can be specified, separated by commas. Each host will be tried in turn when connecting. Required if connecting
85+
/// with the `connect` method.
86+
/// * `port` - The port to connect to. Multiple ports can be specified, separated by commas. The number of ports must be
87+
/// either 1, in which case it will be used for all hosts, or the same as the number of hosts. Defaults to 5432 if
88+
/// omitted or the empty string.
89+
/// * `connect_timeout` - The time limit in seconds applied to each socket-level connection attempt. Note that hostnames
90+
/// can resolve to multiple IP addresses, and this limit is applied to each address. Defaults to no timeout.
91+
/// * `keepalives` - Controls the use of TCP keepalive. A value of 0 disables keepalive and nonzero integers enable it.
92+
/// This option is ignored when connecting with Unix sockets. Defaults to on.
93+
/// * `keepalives_idle` - The number of seconds of inactivity after which a keepalive message is sent to the server.
94+
/// This option is ignored when connecting with Unix sockets. Defaults to 2 hours.
95+
/// * `target_session_attrs` - Specifies requirements of the session. If set to `read-write`, the client will check that
96+
/// the `transaction_read_write` session parameter is set to `on`. This can be used to connect to the primary server
97+
/// in a database cluster as opposed to the secondary read-only mirrors. Defaults to `all`.
98+
///
99+
/// ## Examples
100+
///
101+
/// ```not_rust
102+
/// host=localhost user=postgres connect_timeout=10 keepalives=0
103+
/// ```
104+
///
105+
/// ```not_rust
106+
/// host=/var/lib/postgresql,localhost port=1234 user=postgres password='password with spaces'
107+
/// ```
108+
///
109+
/// ```not_rust
110+
/// host=host1,host2,host3 port=1234,,5678 user=postgres target_session_attrs=read-write
111+
/// ```
112+
///
113+
/// # Url
114+
///
115+
/// This format resembles a URL with a scheme of either `postgres://` or `postgresql://`. All components are optional,
116+
/// and the format accept query parameters for all of the key-value pairs described in the section above. Multiple
117+
/// host/port pairs can be comma-separated. Unix socket paths in the host section of the URL should be percent-encoded,
118+
/// as the path component of the URL specifies the database name.
119+
///
120+
/// ## Examples
121+
///
122+
/// ```not_rust
123+
/// postgresql://user@localhost
124+
/// ```
125+
///
126+
/// ```not_rust
127+
/// postgresql://user:password@%2Fvar%2Flib%2Fpostgresql/mydb?connect_timeout=10
128+
/// ```
129+
///
130+
/// ```not_rust
131+
/// postgresql://user@host1:1234,host2host3:5678?target_session_attrs=read-write
132+
/// ```
133+
///
134+
/// ```not_rust
135+
/// postgresql:///mydb?user=user&host=/var/lib/postgresql
136+
/// ```
63137
#[derive(Debug, Clone, PartialEq)]
64138
pub struct Config(pub(crate) Arc<Inner>);
65139

tokio-postgres/src/lib.rs

Lines changed: 127 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@
5454
//! The client supports *pipelined* requests. Pipelining can improve performance in use cases in which multiple,
5555
//! independent queries need to be executed. In a traditional workflow, each query is sent to the server after the
5656
//! previous query completes. In contrast, pipelining allows the client to send all of the queries to the server up
57-
//! front, eliminating time spent on both sides waiting for the other to finish sending data:
57+
//! front, minimizing time spent by one side waiting for the other to finish sending data:
5858
//!
5959
//! ```not_rust
6060
//! Sequential Pipelined
@@ -75,31 +75,7 @@
7575
//! the connection to work concurrently when possible.
7676
//!
7777
//! Pipelining happens automatically when futures are polled concurrently (for example, by using the futures `join`
78-
//! combinator). Say we want to prepare 2 statements:
79-
//!
80-
//! ```no_run
81-
//! use futures::Future;
82-
//! use tokio_postgres::{Client, Error, Statement};
83-
//!
84-
//! fn prepare_sequential(
85-
//! client: &mut Client,
86-
//! ) -> impl Future<Item = (Statement, Statement), Error = Error>
87-
//! {
88-
//! client.prepare("SELECT * FROM foo")
89-
//! .and_then({
90-
//! let f = client.prepare("INSERT INTO bar (id, name) VALUES ($1, $2)");
91-
//! |s1| f.map(|s2| (s1, s2))
92-
//! })
93-
//! }
94-
//!
95-
//! fn prepare_pipelined(
96-
//! client: &mut Client,
97-
//! ) -> impl Future<Item = (Statement, Statement), Error = Error>
98-
//! {
99-
//! client.prepare("SELECT * FROM foo")
100-
//! .join(client.prepare("INSERT INTO bar (id, name) VALUES ($1, $2)"))
101-
//! }
102-
//! ```
78+
//! combinator). Say we want to prepare 2 statements.
10379
//!
10480
//! # Runtime
10581
//!
@@ -143,6 +119,13 @@ fn next_portal() -> String {
143119
format!("p{}", ID.fetch_add(1, Ordering::SeqCst))
144120
}
145121

122+
/// A convenience function which parses a connection string and connects to the database.
123+
///
124+
/// See the documentation for [`Config`] for details on the connection string format.
125+
///
126+
/// Requires the `runtime` Cargo feature (enabled by default).
127+
///
128+
/// [`Config`]: ./Config.t.html
146129
#[cfg(feature = "runtime")]
147130
pub fn connect<T>(config: &str, tls_mode: T) -> Connect<T>
148131
where
@@ -151,33 +134,73 @@ where
151134
Connect(proto::ConnectFuture::new(tls_mode, config.parse()))
152135
}
153136

137+
/// An asynchronous PostgreSQL client.
138+
///
139+
/// The client is one half of what is returned when a connection is established. Users interact with the database
140+
/// through this client object.
154141
pub struct Client(proto::Client);
155142

156143
impl Client {
144+
/// Creates a new prepared statement.
145+
///
146+
/// Prepared statements can be executed repeatedly, and may contain query parameters (indicated by `$1`, `$2`, etc),
147+
/// which are set when executed. Prepared statements can only be used with the connection that created them.
157148
pub fn prepare(&mut self, query: &str) -> Prepare {
158149
self.prepare_typed(query, &[])
159150
}
160151

152+
/// Like `prepare`, but allows the types of query parameters to be explicitly specified.
153+
///
154+
/// The list of types may be smaller than the number of parameters - the types of the remaining parameters will be
155+
/// inferred. For example, `client.prepare_typed(query, &[])` is equivalent to `client.prepare(query)`.
161156
pub fn prepare_typed(&mut self, query: &str, param_types: &[Type]) -> Prepare {
162157
Prepare(self.0.prepare(next_statement(), query, param_types))
163158
}
164159

160+
/// Executes a statement, returning the number of rows modified.
161+
///
162+
/// If the statement does not modify any rows (e.g. `SELECT`), 0 is returned.
163+
///
164+
/// # Panics
165+
///
166+
/// Panics if the number of parameters provided does not match the number expected.
165167
pub fn execute(&mut self, statement: &Statement, params: &[&dyn ToSql]) -> Execute {
166168
Execute(self.0.execute(&statement.0, params))
167169
}
168170

171+
/// Executes a statement, returning a stream of the resulting rows.
172+
///
173+
/// # Panics
174+
///
175+
/// Panics if the number of parameters provided does not match the number expected.
169176
pub fn query(&mut self, statement: &Statement, params: &[&dyn ToSql]) -> Query {
170177
Query(self.0.query(&statement.0, params))
171178
}
172179

180+
/// Binds a statement to a set of parameters, creating a `Portal` which can be incrementally queried.
181+
///
182+
/// Portals only last for the duration of the transaction in which they are created - in particular, a portal
183+
/// created outside of a transaction is immediately destroyed. Portals can only be used on the connection that
184+
/// created them.
185+
/// # Panics
186+
///
187+
/// Panics if the number of parameters provided does not match the number expected.
173188
pub fn bind(&mut self, statement: &Statement, params: &[&dyn ToSql]) -> Bind {
174189
Bind(self.0.bind(&statement.0, next_portal(), params))
175190
}
176191

192+
/// Continues execution of a portal, returning a stream of the resulting rows.
193+
///
194+
/// Unlike `query`, portals can be incrementally evaluated by limiting the number of rows returned in each call to
195+
/// query_portal. If the requested number is negative or 0, all rows will be returned.
177196
pub fn query_portal(&mut self, portal: &Portal, max_rows: i32) -> QueryPortal {
178197
QueryPortal(self.0.query_portal(&portal.0, max_rows))
179198
}
180199

200+
/// Executes a `COPY FROM STDIN` statement, returning the number of rows created.
201+
///
202+
/// The data in the provided stream is passed along to the server verbatim; it is the caller's responsibility to
203+
/// ensure it uses the proper format.
181204
pub fn copy_in<S>(
182205
&mut self,
183206
statement: &Statement,
@@ -194,18 +217,36 @@ impl Client {
194217
CopyIn(self.0.copy_in(&statement.0, params, stream))
195218
}
196219

220+
/// Executes a `COPY TO STDOUT` statement, returning a stream of the resulting data.
197221
pub fn copy_out(&mut self, statement: &Statement, params: &[&dyn ToSql]) -> CopyOut {
198222
CopyOut(self.0.copy_out(&statement.0, params))
199223
}
200224

201-
pub fn transaction(&mut self) -> TransactionBuilder {
202-
TransactionBuilder(self.0.clone())
203-
}
204-
225+
/// Executes a sequence of SQL statements.
226+
///
227+
/// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
228+
/// point. This is intended for the execution of batches of non-dynamic statements, for example, the creation of
229+
/// a schema for a fresh database.
230+
///
231+
/// # Warning
232+
///
233+
/// Prepared statements should be use for any query which contains user-specified data, as they provided the
234+
/// functionality to safely imbed that data in the request. Do not form statements via string concatenation and pass
235+
/// them to this method!
205236
pub fn batch_execute(&mut self, query: &str) -> BatchExecute {
206237
BatchExecute(self.0.batch_execute(query))
207238
}
208239

240+
pub fn transaction(&mut self) -> TransactionBuilder {
241+
TransactionBuilder(self.0.clone())
242+
}
243+
244+
/// Attempts to cancel an in-progress query.
245+
///
246+
/// The server provides no information about whether a cancellation attempt was successful or not. An error will
247+
/// only be returned if the client was unable to connect to the database.
248+
///
249+
/// Requires the `runtime` Cargo feature (enabled by default).
209250
#[cfg(feature = "runtime")]
210251
pub fn cancel_query<T>(&mut self, make_tls_mode: T) -> CancelQuery<T>
211252
where
@@ -214,6 +255,8 @@ impl Client {
214255
CancelQuery(self.0.cancel_query(make_tls_mode))
215256
}
216257

258+
/// Like `cancel_query`, but uses a stream which is already connected to the server rather than opening a new
259+
/// connection itself.
217260
pub fn cancel_query_raw<S, T>(&mut self, stream: S, tls_mode: T) -> CancelQueryRaw<S, T>
218261
where
219262
S: AsyncRead + AsyncWrite,
@@ -222,26 +265,47 @@ impl Client {
222265
CancelQueryRaw(self.0.cancel_query_raw(stream, tls_mode))
223266
}
224267

268+
/// Determines if the connection to the server has already closed.
269+
///
270+
/// In that case, all future queries will fail.
225271
pub fn is_closed(&self) -> bool {
226272
self.0.is_closed()
227273
}
228274

275+
/// Polls the client to check if it is idle.
276+
///
277+
/// A connection is idle if there are no outstanding requests, whether they have begun being polled or not. For
278+
/// example, this can be used by a connection pool to ensure that all work done by one checkout is done before
279+
/// making the client available for a new request. Otherwise, any non-completed work from the first request could
280+
/// interleave with the second.
229281
pub fn poll_idle(&mut self) -> Poll<(), Error> {
230282
self.0.poll_idle()
231283
}
232284
}
233285

286+
/// A connection to a PostgreSQL database.
287+
///
288+
/// This is one half of what is returned when a new connection is established. It performs the actual IO with the
289+
/// server, and should generally be spawned off onto an executor to run in the background.
290+
///
291+
/// `Connection` implements `Future`, and only resolves when the connection is closed, either because a fatal error has
292+
/// occurred, or because its associated `Client` has dropped and all outstanding work has completed.
234293
#[must_use = "futures do nothing unless polled"]
235294
pub struct Connection<S>(proto::Connection<S>);
236295

237296
impl<S> Connection<S>
238297
where
239298
S: AsyncRead + AsyncWrite,
240299
{
300+
/// Returns the value of a runtime parameter for this connection.
241301
pub fn parameter(&self, name: &str) -> Option<&str> {
242302
self.0.parameter(name)
243303
}
244304

305+
/// Polls for asynchronous messages from the server.
306+
///
307+
/// The server can send notices as well as notifications asynchronously to the client. Applications which wish to
308+
/// examine those messages should use this method to drive the connection rather than its `Future` implementation.
245309
pub fn poll_message(&mut self) -> Poll<Option<AsyncMessage>, Error> {
246310
self.0.poll_message()
247311
}
@@ -259,9 +323,16 @@ where
259323
}
260324
}
261325

326+
/// An asynchronous message from the server.
262327
#[allow(clippy::large_enum_variant)]
263328
pub enum AsyncMessage {
329+
/// A notice.
330+
///
331+
/// Notices use the same format as errors, but aren't "errors" per-se.
264332
Notice(DbError),
333+
/// A notification.
334+
///
335+
/// Connections can subscribe to notifications with the `LISTEN` command.
265336
Notification(Notification),
266337
#[doc(hidden)]
267338
__NonExhaustive,
@@ -361,14 +432,19 @@ impl Future for Prepare {
361432
}
362433
}
363434

435+
/// A prepared statement.
436+
///
437+
/// Prepared statements can only be used with the connection that created them.
364438
#[derive(Clone)]
365439
pub struct Statement(proto::Statement);
366440

367441
impl Statement {
442+
/// Returns the expected types of the statement's parameters.
368443
pub fn params(&self) -> &[Type] {
369444
self.0.params()
370445
}
371446

447+
/// Returns information about the columns returned when the statement is queried.
372448
pub fn columns(&self) -> &[Column] {
373449
self.0.columns()
374450
}
@@ -426,6 +502,10 @@ impl Stream for QueryPortal {
426502
}
427503
}
428504

505+
/// A portal.
506+
///
507+
/// Portals can only be used with the connection that created them, and only exist for the duration of the transaction
508+
/// in which they were created.
429509
pub struct Portal(proto::Portal);
430510

431511
#[must_use = "futures do nothing unless polled"]
@@ -512,10 +592,24 @@ impl Future for BatchExecute {
512592
/// An asynchronous notification.
513593
#[derive(Clone, Debug)]
514594
pub struct Notification {
595+
process_id: i32,
596+
channel: String,
597+
payload: String,
598+
}
599+
600+
impl Notification {
515601
/// The process ID of the notifying backend process.
516-
pub process_id: i32,
602+
pub fn process_id(&self) -> i32 {
603+
self.process_id
604+
}
605+
517606
/// The name of the channel that the notify has been raised on.
518-
pub channel: String,
607+
pub fn channel(&self) -> &str {
608+
&self.channel
609+
}
610+
519611
/// The "payload" string passed from the notifying process.
520-
pub payload: String,
612+
pub fn payload(&self) -> &str {
613+
&self.payload
614+
}
521615
}

0 commit comments

Comments
 (0)