Docs.rs
  • tokio-postgres-0.7.13
    • tokio-postgres 0.7.13
    • Docs.rs crate page
    • MIT OR Apache-2.0
    • Links
    • Repository
    • crates.io
    • Source
    • Owners
    • sfackler
    • Dependencies
      • async-trait ^0.1 normal
      • byteorder ^1.0 normal
      • bytes ^1.0 normal
      • fallible-iterator ^0.2 normal
      • futures-channel ^0.3 normal
      • futures-util ^0.3 normal
      • log ^0.4 normal
      • parking_lot ^0.12 normal
      • percent-encoding ^2.0 normal
      • phf ^0.11 normal
      • pin-project-lite ^0.2 normal
      • postgres-protocol ^0.6.8 normal
      • postgres-types ^0.2.9 normal
      • rand ^0.9.0 normal
      • tokio ^1.27 normal
      • tokio-util ^0.7 normal
      • whoami ^1.4.1 normal
      • bit-vec ^0.6 dev
      • chrono ^0.4 dev
      • criterion ^0.5 dev
      • env_logger ^0.11 dev
      • eui48 ^1.0 dev
      • futures-executor ^0.3 dev
      • geo-types ^0.6 dev
      • geo-types ^0.7 dev
      • jiff ^0.1 dev
      • serde ^1.0 dev
      • serde_json ^1.0 dev
      • smol_str ^0.1 dev
      • time ^0.2 dev
      • time ^0.3 dev
      • tokio ^1.0 dev
      • uuid ^0.8 dev
      • uuid ^1.0 dev
      • socket2 ^0.5 normal
    • Versions
    • 100% of the crate is documented
  • Platform
    • i686-pc-windows-msvc
    • i686-unknown-linux-gnu
    • x86_64-apple-darwin
    • x86_64-pc-windows-msvc
    • x86_64-unknown-linux-gnu
  • Feature flags
  • docs.rs
    • About docs.rs
    • Privacy policy
  • Rust
    • Rust website
    • The Book
    • Standard Library API Reference
    • Rust by Example
    • The Cargo Guide
    • Clippy Documentation

Crate tokio_postgres

tokio_postgres0.7.13

  • All Items

Sections

  • Example
  • Behavior
  • Pipelining
  • Runtime
  • SSL/TLS support
  • Features

Crate Items

  • Re-exports
  • Modules
  • Structs
  • Enums
  • Traits
  • Functions

Crates

  • tokio_postgres

Crate tokio_postgres

Source
Expand description

An asynchronous, pipelined, PostgreSQL client.

§Example

use tokio_postgres::{NoTls, Error};

#[tokio::main] // By default, tokio_postgres uses the tokio crate as its runtime.
async fn main() -> Result<(), Error> {
    // Connect to the database.
    let (client, connection) =
        tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;

    // The connection object performs the actual communication with the database,
    // so spawn it off to run on its own.
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });

    // Now we can execute a simple statement that just returns its parameter.
    let rows = client
        .query("SELECT $1::TEXT", &[&"hello world"])
        .await?;

    // And then check that we got back the same string we sent over.
    let value: &str = rows[0].get(0);
    assert_eq!(value, "hello world");

    Ok(())
}

§Behavior

Calling a method like Client::query on its own does nothing. The associated request is not sent to the database until the future returned by the method is first polled. Requests are executed in the order that they are first polled, not in the order that their futures are created.

§Pipelining

The client supports pipelined requests. Pipelining can improve performance in use cases in which multiple, independent queries need to be executed. In a traditional workflow, each query is sent to the server after the previous query completes. In contrast, pipelining allows the client to send all of the queries to the server up front, minimizing time spent by one side waiting for the other to finish sending data:

            Sequential                              Pipelined
| Client         | Server          |    | Client         | Server          |
|----------------|-----------------|    |----------------|-----------------|
| send query 1   |                 |    | send query 1   |                 |
|                | process query 1 |    | send query 2   | process query 1 |
| receive rows 1 |                 |    | send query 3   | process query 2 |
| send query 2   |                 |    | receive rows 1 | process query 3 |
|                | process query 2 |    | receive rows 2 |                 |
| receive rows 2 |                 |    | receive rows 3 |                 |
| send query 3   |                 |
|                | process query 3 |
| receive rows 3 |                 |

In both cases, the PostgreSQL server is executing the queries sequentially - pipelining just allows both sides of the connection to work concurrently when possible.

Pipelining happens automatically when futures are polled concurrently (for example, by using the futures join combinator):

use futures_util::future;
use std::future::Future;
use tokio_postgres::{Client, Error, Statement};

async fn pipelined_prepare(
    client: &Client,
) -> Result<(Statement, Statement), Error>
{
    future::try_join(
        client.prepare("SELECT * FROM foo"),
        client.prepare("INSERT INTO bar (id, name) VALUES ($1, $2)")
    ).await
}

§Runtime

The client works with arbitrary AsyncRead + AsyncWrite streams. Convenience APIs are provided to handle the connection process, but these are gated by the runtime Cargo feature, which is enabled by default. If disabled, all dependence on the tokio runtime is removed.

§SSL/TLS support

TLS support is implemented via external libraries. Client::connect and Config::connect take a TLS implementation as an argument. The NoTls type in this crate can be used when TLS is not required. Otherwise, the postgres-openssl and postgres-native-tls crates provide implementations backed by the openssl and native-tls crates, respectively.

§Features

The following features can be enabled from Cargo.toml:

FeatureDescriptionExtra dependenciesDefault
runtimeEnable convenience API for the connection process based on the tokio crate.tokio 1.0 with the features net and timeyes
array-implsEnables ToSql and FromSql trait impls for arrays-no
with-bit-vec-0_6Enable support for the bit-vec crate.bit-vec 0.6no
with-chrono-0_4Enable support for the chrono crate.chrono 0.4no
with-eui48-0_4Enable support for the 0.4 version of the eui48 crate. This is deprecated and will be removed.eui48 0.4no
with-eui48-1Enable support for the 1.0 version of the eui48 crate.eui48 1.0no
with-geo-types-0_6Enable support for the 0.6 version of the geo-types crate.geo-types 0.6no
with-geo-types-0_7Enable support for the 0.7 version of the geo-types crate.geo-types 0.7no
with-jiff-0_1Enable support for the 0.1 version of the jiff crate.jiff 0.1no
with-serde_json-1Enable support for the serde_json crate.serde_json 1.0no
with-uuid-0_8Enable support for the uuid crate.uuid 0.8no
with-uuid-1Enable support for the uuid crate.uuid 1.0no
with-time-0_2Enable support for the 0.2 version of the time crate.time 0.2no
with-time-0_3Enable support for the 0.3 version of the time crate.time 0.3no

Re-exports§

pub use crate::config::Config;
pub use crate::error::Error;
pub use crate::row::Row;
pub use crate::row::SimpleQueryRow;
pub use crate::tls::NoTls;

Modules§

binary_copy
Utilities for working with the PostgreSQL binary copy format.
config
Connection configuration.
error
Errors.
row
Rows.
tls
TLS support.
types
Types.

Structs§

CancelToken
The capability to request cancellation of in-progress queries on a connection.
Client
An asynchronous PostgreSQL client.
Column
Information about a column of a query.
Connection
A connection to a PostgreSQL database.
CopyInSink
A sink for COPY ... FROM STDIN query data.
CopyOutStream
A stream of COPY ... TO STDOUT query data.
Notification
An asynchronous notification.
Portal
A portal.
RowStream
A stream of table rows.
SimpleColumn
Information about a column of a single query row.
SimpleQueryStream
A stream of simple query results.
Socket
The standard stream type used by the crate.
Statement
A prepared statement.
Transaction
A representation of a PostgreSQL database transaction.
TransactionBuilder
A builder for database transactions.

Enums§

AsyncMessage
An asynchronous message from the server.
IsolationLevel
The isolation level of a database transaction.
SimpleQueryMessage
Message returned by the SimpleQuery stream.

Traits§

GenericClient
A trait allowing abstraction over connections and transactions.
ToStatement
A trait abstracting over prepared and unprepared statements.

Functions§

connect
A convenience function which parses a connection string and connects to the database.

Results

Settings
Help

Type "Connect" not found. Showing results for closest type name "context" instead.

    function
    tokio_postgres::connect
    A convenience function which parses a connection string …
    trait method
    tokio_postgres::tls::TlsConnect::connect
    Returns a future performing a TLS handshake over the …
    method
    tokio_postgres::config::Config::connect
    Opens a connection to a PostgreSQL database.
    method
    tokio_postgres::tls::NoTls::connect
    struct
    tokio_postgres::Connection
    A connection to a PostgreSQL database.
    method
    tokio_postgres::config::Config::connect_raw
    Connects to a PostgreSQL database over an arbitrary stream.
    method
    tokio_postgres::config::Config::connect_timeout
    Sets the timeout applied to socket-level connection …
    assoc const
    tokio_postgres::error::SqlState::CONNECTION_FAILURE
    08006
    assoc const
    tokio_postgres::error::SqlState::CONNECTION_EXCEPTION
    08000
    assoc const
    tokio_postgres::error::SqlState::CONNECTION_DOES_NOT_EXIST
    08003
    trait
    tokio_postgres::tls::TlsConnect
    An asynchronous function wrapping a stream in a TLS …
    assoc type
    tokio_postgres::tls::MakeTlsConnect::TlsConnect
    The TlsConnect implementation created by this type.
    method
    tokio_postgres::config::Config::get_connect_timeout
    Gets the connection timeout, if one has been set with the …
    assoc const
    tokio_postgres::error::SqlState::CANNOT_CONNECT_NOW
    57P03
    trait
    tokio_postgres::tls::MakeTlsConnect
    A constructor of TlsConnectors.
    trait method
    tokio_postgres::tls::MakeTlsConnect::make_tls_connect
    Creates a new TlsConnector.
    method
    tokio_postgres::tls::NoTls::make_tls_connect
    assoc const
    tokio_postgres::error::SqlState::TOO_MANY_CONNECTIONS
    53300
    assoc const
    tokio_postgres::error::SqlState::FDW_UNABLE_TO_ESTABLISH_CONNECTION
    HV00N
    assoc const
    tokio_postgres::error::SqlState::SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION
    08001
    assoc const
    tokio_postgres::error::SqlState::SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION
    08004
    method
    tokio_postgres::Connection::try_poll
    Pin<&mut F>, &mut Context -> Poll
    method
    tokio_postgres::tls::NoTlsFuture::try_poll
    Pin<&mut F>, &mut Context -> Poll
    method
    tokio_postgres::tls::NoTlsFuture::poll
    Pin<&mut NoTlsFuture>, &mut Context -> Poll<Future::Output>
    method
    tokio_postgres::CopyOutStream::poll_next
    Pin<&mut CopyOutStream>, &mut Context -> Poll<Option<Stream::Item>>
    method
    tokio_postgres::RowStream::poll_next
    Pin<&mut RowStream>, &mut Context -> Poll<Option<Stream::Item>>
    method
    tokio_postgres::SimpleQueryStream::poll_next
    Pin<&mut SimpleQueryStream>, &mut Context -> Poll<Option<Stream::Item>>
    method
    tokio_postgres::binary_copy::BinaryCopyOutStream::poll_next
    Pin<&mut BinaryCopyOutStream>, &mut Context -> Poll<Option<Stream::Item>>
    method
    tokio_postgres::Socket::poll_flush
    Pin<&mut Socket>, &mut Context -> Poll<Result<()>>
    method
    tokio_postgres::tls::NoTlsStream::poll_flush
    Pin<&mut NoTlsStream>, &mut Context -> Poll<Result<()>>
    method
    tokio_postgres::Socket::poll_shutdown
    Pin<&mut Socket>, &mut Context -> Poll<Result<()>>
    method
    tokio_postgres::tls::NoTlsStream::poll_shutdown
    Pin<&mut NoTlsStream>, &mut Context -> Poll<Result<()>>
    method
    tokio_postgres::CopyOutStream::try_poll_next
    Pin<&mut S>, &mut Context -> Poll<Option<Result>>
    method
    tokio_postgres::RowStream::try_poll_next
    Pin<&mut S>, &mut Context -> Poll<Option<Result>>
    method
    tokio_postgres::SimpleQueryStream::try_poll_next
    Pin<&mut S>, &mut Context -> Poll<Option<Result>>
    method
    tokio_postgres::binary_copy::BinaryCopyOutStream::try_poll_next
    Pin<&mut S>, &mut Context -> Poll<Option<Result>>
    method
    tokio_postgres::Socket::poll_read
    Pin<&mut Socket>, &mut Context, &mut ReadBuf -> Poll<Result<()>>
    method
    tokio_postgres::tls::NoTlsStream::poll_read
    Pin<&mut NoTlsStream>, &mut Context, &mut ReadBuf -> Poll<Result<()>>
    method
    tokio_postgres::Socket::poll_write
    Pin<&mut Socket>, &mut Context, &[u8] -> Poll<Result<usize>>
    method
    tokio_postgres::tls::NoTlsStream::poll_write
    Pin<&mut NoTlsStream>, &mut Context, &[u8] -> Poll<Result<usize>>
    method
    tokio_postgres::CopyInSink::poll_close
    Pin<&mut CopyInSink<T>>, &mut Context -> Poll<Result<(), Error>>
    method
    tokio_postgres::CopyInSink::poll_flush
    Pin<&mut CopyInSink<T>>, &mut Context -> Poll<Result<(), Error>>
    method
    tokio_postgres::CopyInSink::poll_ready
    Pin<&mut CopyInSink<T>>, &mut Context -> Poll<Result<(), Error>>
    method
    tokio_postgres::CopyInSink::poll_finish
    Pin<&mut CopyInSink<T>>, &mut Context -> Poll<Result<u64, Error>>
    A poll-based version of finish.
    method
    tokio_postgres::Connection::poll
    Pin<&mut Connection<S, T>>, &mut Context -> Poll<Result<(), Error>>
    method
    tokio_postgres::Connection::poll_message
    &mut Connection<S, T>, &mut Context -> Poll<Option<Result<AsyncMessage, Error>>>
    Polls for asynchronous messages from the server.
No results :(
Try on DuckDuckGo?

Or try looking in one of these:
  • The Rust Reference for technical details about the language.
  • Rust By Example for expository code examples.
  • The Rust Book for introductions to language features and the language itself.
  • Docs.rs for documentation of crates released on crates.io.