Struct postgres::Client

source ·
pub struct Client { /* private fields */ }
Expand description

A synchronous PostgreSQL client.

Implementations§

source§

impl Client

source

pub fn connect<T>(params: &str, tls_mode: T) -> Result<Client, Error>where T: MakeTlsConnect<Socket> + 'static + Send, T::TlsConnect: Send, T::Stream: Send, <T::TlsConnect as TlsConnect<Socket>>::Future: Send,

A convenience function which parses a configuration string into a Config and then connects to the database.

See the documentation for Config for information about the connection syntax.

source

pub fn configure() -> Config

Returns a new Config object which can be used to configure and connect to a database.

source

pub fn execute<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<u64, Error>where T: ?Sized + ToStatement,

Executes a statement, returning the number of rows modified.

A statement may contain parameters, specified by $n, where n is the index of the parameter of the list provided, 1-indexed.

If the statement does not modify any rows (e.g. SELECT), 0 is returned.

The query argument can either be a Statement, or a raw query string. If the same statement will be repeatedly executed (perhaps with different query parameters), consider preparing the statement up front with the prepare method.

Example
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let bar = 1i32;
let baz = true;
let rows_updated = client.execute(
    "UPDATE foo SET bar = $1 WHERE baz = $2",
    &[&bar, &baz],
)?;

println!("{} rows updated", rows_updated);
source

pub fn query<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Vec<Row>, Error>where T: ?Sized + ToStatement,

Executes a statement, returning the resulting rows.

A statement may contain parameters, specified by $n, where n is the index of the parameter of the list provided, 1-indexed.

The query argument can either be a Statement, or a raw query string. If the same statement will be repeatedly executed (perhaps with different query parameters), consider preparing the statement up front with the prepare method.

Examples
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let baz = true;
for row in client.query("SELECT foo FROM bar WHERE baz = $1", &[&baz])? {
    let foo: i32 = row.get("foo");
    println!("foo: {}", foo);
}
source

pub fn query_one<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Row, Error>where T: ?Sized + ToStatement,

Executes a statement which returns a single row, returning it.

Returns an error if the query does not return exactly one row.

A statement may contain parameters, specified by $n, where n is the index of the parameter of the list provided, 1-indexed.

The query argument can either be a Statement, or a raw query string. If the same statement will be repeatedly executed (perhaps with different query parameters), consider preparing the statement up front with the prepare method.

Examples
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let baz = true;
let row = client.query_one("SELECT foo FROM bar WHERE baz = $1", &[&baz])?;
let foo: i32 = row.get("foo");
println!("foo: {}", foo);
source

pub fn query_opt<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Option<Row>, Error>where T: ?Sized + ToStatement,

Executes a statement which returns zero or one rows, returning it.

Returns an error if the query returns more than one row.

A statement may contain parameters, specified by $n, where n is the index of the parameter of the list provided, 1-indexed.

The query argument can either be a Statement, or a raw query string. If the same statement will be repeatedly executed (perhaps with different query parameters), consider preparing the statement up front with the prepare method.

Examples
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let baz = true;
let row = client.query_opt("SELECT foo FROM bar WHERE baz = $1", &[&baz])?;
match row {
    Some(row) => {
        let foo: i32 = row.get("foo");
        println!("foo: {}", foo);
    }
    None => println!("no matching foo"),
}
source

pub fn query_raw<T, P, I>( &mut self, query: &T, params: I ) -> Result<RowIter<'_>, Error>where T: ?Sized + ToStatement, P: BorrowToSql, I: IntoIterator<Item = P>, I::IntoIter: ExactSizeIterator,

A maximally-flexible version of query.

It takes an iterator of parameters rather than a slice, and returns an iterator of rows rather than collecting them into an array.

Examples
use postgres::{Client, NoTls};
use fallible_iterator::FallibleIterator;
use std::iter;

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let baz = true;
let mut it = client.query_raw("SELECT foo FROM bar WHERE baz = $1", iter::once(baz))?;

while let Some(row) = it.next()? {
    let foo: i32 = row.get("foo");
    println!("foo: {}", foo);
}

If you have a type like Vec<T> where T: ToSql Rust will not know how to use it as params. To get around this the type must explicitly be converted to &dyn ToSql.

use postgres::types::ToSql;
use fallible_iterator::FallibleIterator;

let params: Vec<String> = vec![
    "first param".into(),
    "second param".into(),
];
let mut it = client.query_raw(
    "SELECT foo FROM bar WHERE biz = $1 AND baz = $2",
    params,
)?;

while let Some(row) = it.next()? {
    let foo: i32 = row.get("foo");
    println!("foo: {}", foo);
}
source

pub fn prepare(&mut self, query: &str) -> Result<Statement, Error>

Creates a new prepared statement.

Prepared statements can be executed repeatedly, and may contain query parameters (indicated by $1, $2, etc), which are set when executed. Prepared statements can only be used with the connection that created them.

Examples
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let statement = client.prepare("SELECT name FROM people WHERE id = $1")?;

for id in 0..10 {
    let rows = client.query(&statement, &[&id])?;
    let name: &str = rows[0].get(0);
    println!("name: {}", name);
}
source

pub fn prepare_typed( &mut self, query: &str, types: &[Type] ) -> Result<Statement, Error>

Like prepare, but allows the types of query parameters to be explicitly specified.

The list of types may be smaller than the number of parameters - the types of the remaining parameters will be inferred. For example, client.prepare_typed(query, &[]) is equivalent to client.prepare(query).

Examples
use postgres::{Client, NoTls};
use postgres::types::Type;

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let statement = client.prepare_typed(
    "SELECT name FROM people WHERE id = $1",
    &[Type::INT8],
)?;

for id in 0..10 {
    let rows = client.query(&statement, &[&id])?;
    let name: &str = rows[0].get(0);
    println!("name: {}", name);
}
source

pub fn copy_in<T>(&mut self, query: &T) -> Result<CopyInWriter<'_>, Error>where T: ?Sized + ToStatement,

Executes a COPY FROM STDIN statement, returning the number of rows created.

The query argument can either be a Statement, or a raw query string. The data in the provided reader is passed along to the server verbatim; it is the caller’s responsibility to ensure it uses the proper format. PostgreSQL does not support parameters in COPY statements, so this method does not take any.

The copy must be explicitly completed via the finish method. If it is not, the copy will be aborted.

Examples
use postgres::{Client, NoTls};
use std::io::Write;

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let mut writer = client.copy_in("COPY people FROM stdin")?;
writer.write_all(b"1\tjohn\n2\tjane\n")?;
writer.finish()?;
source

pub fn copy_out<T>(&mut self, query: &T) -> Result<CopyOutReader<'_>, Error>where T: ?Sized + ToStatement,

Executes a COPY TO STDOUT statement, returning a reader of the resulting data.

The query argument can either be a Statement, or a raw query string. PostgreSQL does not support parameters in COPY statements, so this method does not take any.

Examples
use postgres::{Client, NoTls};
use std::io::Read;

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let mut reader = client.copy_out("COPY people TO stdout")?;
let mut buf = vec![];
reader.read_to_end(&mut buf)?;
source

pub fn simple_query( &mut self, query: &str ) -> Result<Vec<SimpleQueryMessage>, Error>

Executes a sequence of SQL statements using the simple query protocol.

Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that point. The simple query protocol returns the values in rows as strings rather than in their binary encodings, so the associated row type doesn’t work with the FromSql trait. Rather than simply returning the rows, this method returns a sequence of an enum which indicates either the completion of one of the commands, or a row of data. This preserves the framing between the separate statements in the request.

This is a simple convenience method over simple_query_iter.

Warning

Prepared statements should be used for any query which contains user-specified data, as they provided the functionality to safely embed that data in the request. Do not form statements via string concatenation and pass them to this method!

source

pub fn is_valid(&mut self, timeout: Duration) -> Result<(), Error>

Validates the connection by performing a simple no-op query.

If the specified timeout is reached before the backend responds, an error will be returned.

source

pub fn batch_execute(&mut self, query: &str) -> Result<(), Error>

Executes a sequence of SQL statements using the simple query protocol.

Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that point. This is intended for use when, for example, initializing a database schema.

Warning

Prepared statements should be use for any query which contains user-specified data, as they provided the functionality to safely embed that data in the request. Do not form statements via string concatenation and pass them to this method!

source

pub fn transaction(&mut self) -> Result<Transaction<'_>, Error>

Begins a new database transaction.

The transaction will roll back by default - use the commit method to commit it.

Examples
use postgres::{Client, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let mut transaction = client.transaction()?;
transaction.execute("UPDATE foo SET bar = 10", &[])?;
// ...

transaction.commit()?;
source

pub fn build_transaction(&mut self) -> TransactionBuilder<'_>

Returns a builder for a transaction with custom settings.

Unlike the transaction method, the builder can be used to control the transaction’s isolation level and other attributes.

Examples
use postgres::{Client, IsolationLevel, NoTls};

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let mut transaction = client.build_transaction()
    .isolation_level(IsolationLevel::RepeatableRead)
    .start()?;
transaction.execute("UPDATE foo SET bar = 10", &[])?;
// ...

transaction.commit()?;
source

pub fn notifications(&mut self) -> Notifications<'_>

Returns a structure providing access to asynchronous notifications.

Use the LISTEN command to register this connection for notifications.

source

pub fn cancel_token(&self) -> CancelToken

Constructs a cancellation token that can later be used to request cancellation of a query running on this connection.

Examples
use postgres::{Client, NoTls};
use postgres::error::SqlState;
use std::thread;
use std::time::Duration;

let mut client = Client::connect("host=localhost user=postgres", NoTls)?;

let cancel_token = client.cancel_token();

thread::spawn(move || {
    // Abort the query after 5s.
    thread::sleep(Duration::from_secs(5));
    let _ = cancel_token.cancel_query(NoTls);
});

match client.simple_query("SELECT long_running_query()") {
    Err(e) if e.code() == Some(&SqlState::QUERY_CANCELED) => {
        // Handle canceled query.
    }
    Err(err) => return Err(err.into()),
    Ok(rows) => {
        // ...
    }
}
// ...
source

pub fn clear_type_cache(&self)

Clears the client’s type information cache.

When user-defined types are used in a query, the client loads their definitions from the database and caches them for the lifetime of the client. If those definitions are changed in the database, this method can be used to flush the local cache and allow the new, updated definitions to be loaded.

source

pub fn is_closed(&self) -> bool

Determines if the client’s connection has already closed.

If this returns true, the client is no longer usable.

source

pub fn close(self) -> Result<(), Error>

Closes the client’s connection to the server.

This is equivalent to Client’s Drop implementation, except that it returns any error encountered to the caller.

Trait Implementations§

source§

impl Drop for Client

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl GenericClient for Client

source§

fn execute<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<u64, Error>where T: ?Sized + ToStatement,

Like Client::execute.
source§

fn query<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Vec<Row>, Error>where T: ?Sized + ToStatement,

Like Client::query.
source§

fn query_one<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Row, Error>where T: ?Sized + ToStatement,

Like Client::query_one.
source§

fn query_opt<T>( &mut self, query: &T, params: &[&(dyn ToSql + Sync)] ) -> Result<Option<Row>, Error>where T: ?Sized + ToStatement,

Like Client::query_opt.
source§

fn query_raw<T, P, I>( &mut self, query: &T, params: I ) -> Result<RowIter<'_>, Error>where T: ?Sized + ToStatement, P: BorrowToSql, I: IntoIterator<Item = P>, I::IntoIter: ExactSizeIterator,

Like Client::query_raw.
source§

fn prepare(&mut self, query: &str) -> Result<Statement, Error>

Like Client::prepare.
source§

fn prepare_typed( &mut self, query: &str, types: &[Type] ) -> Result<Statement, Error>

Like Client::prepare_typed.
source§

fn copy_in<T>(&mut self, query: &T) -> Result<CopyInWriter<'_>, Error>where T: ?Sized + ToStatement,

Like Client::copy_in.
source§

fn copy_out<T>(&mut self, query: &T) -> Result<CopyOutReader<'_>, Error>where T: ?Sized + ToStatement,

Like Client::copy_out.
source§

fn simple_query( &mut self, query: &str ) -> Result<Vec<SimpleQueryMessage>, Error>

Like Client::simple_query.
source§

fn batch_execute(&mut self, query: &str) -> Result<(), Error>

Like Client::batch_execute.
source§

fn transaction(&mut self) -> Result<Transaction<'_>, Error>

Like Client::transaction.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl Send for Client

§

impl !Sync for Client

§

impl Unpin for Client

§

impl !UnwindSafe for Client

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more