Movatterモバイル変換


[0]ホーム

URL:


Docs.rs

[][src]Structpostgres::Client

pub struct Client { /* fields omitted */ }

A synchronous PostgreSQL client.

Methods

implClient[src]

pub fnconnect<T>(params: &str, tls_mode: T) ->Result<Client,Error>where
    T:MakeTlsConnect<Socket> + 'static +Send,
    T::TlsConnect:Send,
    T::Stream:Send,
    <T::TlsConnect asTlsConnect<Socket>>::Future:Send
[src]

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

See the documentation forConfig for information about the connection syntax.

pub fnconfigure() ->Config[src]

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

pub fnexecute<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<u64,Error>where
    T:ToStatement
[src]

Executes a statement, returning the number of rows modified.

A statement may contain parameters, specified by$n, wheren is the index of the parameter of the listprovided, 1-indexed.

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

Thequery argument can either be aStatement, or a raw query string. If the same statement will berepeatedly executed (perhaps with different query parameters), consider preparing the statement up frontwith theprepare method.

Panics

Panics if the number of parameters provided does not match the number expected.

Example

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letbar=1i32;letbaz=true;letrows_updated=client.execute("UPDATE foo SET bar = $1 WHERE baz = $2",&[&bar,&baz],)?;println!("{} rows updated",rows_updated);

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

Executes a statement, returning the resulting rows.

A statement may contain parameters, specified by$n, wheren is the index of the parameter of the listprovided, 1-indexed.

Thequery argument can either be aStatement, or a raw query string. If the same statement will berepeatedly executed (perhaps with different query parameters), consider preparing the statement up frontwith theprepare method.

Panics

Panics if the number of parameters provided does not match the number expected.

Examples

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letbaz=true;forrowinclient.query("SELECT foo FROM bar WHERE baz = $1",&[&baz])? {letfoo:i32=row.get("foo");println!("foo: {}",foo);}

pub fnquery_one<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<Row,Error>where
    T:ToStatement
[src]

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, wheren is the index of the parameter of the listprovided, 1-indexed.

Thequery argument can either be aStatement, or a raw query string. If the same statement will berepeatedly executed (perhaps with different query parameters), consider preparing the statement up frontwith theprepare method.

Panics

Panics if the number of parameters provided does not match the number expected.

Examples

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letbaz=true;letrow=client.query_one("SELECT foo FROM bar WHERE baz = $1",&[&baz])?;letfoo:i32=row.get("foo");println!("foo: {}",foo);

pub fnquery_opt<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<Option<Row>,Error>where
    T:ToStatement
[src]

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, wheren is the index of the parameter of the listprovided, 1-indexed.

Thequery argument can either be aStatement, or a raw query string. If the same statement will berepeatedly executed (perhaps with different query parameters), consider preparing the statement up frontwith theprepare method.

Panics

Panics if the number of parameters provided does not match the number expected.

Examples

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letbaz=true;letrow=client.query_opt("SELECT foo FROM bar WHERE baz = $1",&[&baz])?;matchrow {Some(row)=> {letfoo:i32=row.get("foo");println!("foo: {}",foo);    }None=>println!("no matching foo"),}

pub fnquery_raw<'a, T: ?Sized, I>(
    &mut self,
    query:&T,
    params: I
) ->Result<RowIter,Error>where
    T:ToStatement,
    I:IntoIterator<Item = &'a dynToSql>,
    I::IntoIter:ExactSizeIterator
[src]

A maximally-flexible version ofquery.

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

Panics

Panics if the number of parameters provided does not match the number expected.

Examples

usepostgres::{Client,NoTls};usefallible_iterator::FallibleIterator;usestd::iter;letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letbaz=true;letmutit=client.query_raw("SELECT foo FROM bar WHERE baz = $1",iter::once(&bazas_))?;whileletSome(row)=it.next()? {letfoo:i32=row.get("foo");println!("foo: {}",foo);}

If you have a type likeVec<T> whereT: ToSql Rust will not know how to use it as params. To get aroundthis the type must explicitly be converted to&dyn ToSql.

usepostgres::types::ToSql;usefallible_iterator::FallibleIterator;letparams:Vec<String>=vec!["first param".into(),"second param".into(),];letmutit=client.query_raw("SELECT foo FROM bar WHERE biz = $1 AND baz = $2",params.iter().map(|p|pas&dynToSql),)?;whileletSome(row)=it.next()? {letfoo:i32=row.get("foo");println!("foo: {}",foo);}

pub fnprepare(&mut self, query: &str) ->Result<Statement,Error>[src]

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

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letstatement=client.prepare("SELECT name FROM people WHERE id = $1")?;foridin0..10 {letrows=client.query(&statement,&[&id])?;letname:&str=rows[0].get(0);println!("name: {}",name);}

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

Likeprepare, 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 beinferred. For example,client.prepare_typed(query, &[]) is equivalent toclient.prepare(query).

Examples

usepostgres::{Client,NoTls};usepostgres::types::Type;letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letstatement=client.prepare_typed("SELECT name FROM people WHERE id = $1",&[Type::INT8],)?;foridin0..10 {letrows=client.query(&statement,&[&id])?;letname:&str=rows[0].get(0);println!("name: {}",name);}

pub fncopy_in<T: ?Sized>(&mut self, query:&T) ->Result<CopyInWriter,Error>where
    T:ToStatement
[src]

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

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

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

Examples

usepostgres::{Client,NoTls};usestd::io::Write;letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letmutwriter=client.copy_in("COPY people FROM stdin")?;writer.write_all(b"1\tjohn\n2\tjane\n")?;writer.finish()?;

pub fncopy_out<T: ?Sized>(&mut self, query:&T) ->Result<CopyOutReader,Error>where
    T:ToStatement
[src]

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

Thequery argument can either be aStatement, or a raw query string. PostgreSQL does not support parametersinCOPY statements, so this method does not take any.

Examples

usepostgres::{Client,NoTls};usestd::io::Read;letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letmutreader=client.copy_out("COPY people TO stdout")?;letmutbuf=vec![];reader.read_to_end(&mutbuf)?;

pub fnsimple_query(
    &mut self,
    query: &str
) ->Result<Vec<SimpleQueryMessage>,Error>
[src]

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 thatpoint. 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 theFromSql trait. Rather than simply returning the rows, thismethod returns a sequence of an enum which indicates either the completion of one of the commands, or a row ofdata. This preserves the framing between the separate statements in the request.

This is a simple convenience method oversimple_query_iter.

Warning

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

pub fnbatch_execute(&mut self, query: &str) ->Result<(),Error>[src]

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 thatpoint. 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 thefunctionality to safely embed that data in the request. Do not form statements via string concatenation and passthem to this method!

pub fntransaction(&mut self) ->Result<Transaction,Error>[src]

Begins a new database transaction.

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

Examples

usepostgres::{Client,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letmuttransaction=client.transaction()?;transaction.execute("UPDATE foo SET bar = 10",&[])?;// ...transaction.commit()?;

pub fnbuild_transaction(&mut self) ->TransactionBuilder[src]

Returns a builder for a transaction with custom settings.

Unlike thetransaction method, the builder can be used to control the transaction's isolation level and otherattributes.

Examples

usepostgres::{Client,IsolationLevel,NoTls};letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letmuttransaction=client.build_transaction()    .isolation_level(IsolationLevel::RepeatableRead)    .start()?;transaction.execute("UPDATE foo SET bar = 10",&[])?;// ...transaction.commit()?;

pub fncancel_token(&self) ->CancelToken[src]

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

Examples

usepostgres::{Client,NoTls};usepostgres::error::SqlState;usestd::thread;usestd::time::Duration;letmutclient=Client::connect("host=localhost user=postgres",NoTls)?;letcancel_token=client.cancel_token();thread::spawn(move|| {// Abort the query after 5s.thread::sleep(Duration::from_secs(5));cancel_token.cancel_query(NoTls);});matchclient.simple_query("SELECT long_running_query()") {Err(e)ife.code()==Some(&SqlState::QUERY_CANCELED)=> {// Handle canceled query.    }Err(err)=>returnErr(err.into()),Ok(rows)=> {// ...    }}// ...

pub fnis_closed(&self) ->bool[src]

Determines if the client's connection has already closed.

If this returnstrue, the client is no longer usable.

Trait Implementations

implGenericClient forClient[src]

fnexecute<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<u64,Error>where
    T:ToStatement
[src]

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

fnquery_one<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<Row,Error>where
    T:ToStatement
[src]

fnquery_opt<T: ?Sized>(
    &mut self,
    query:&T,
    params:&[&(dynToSql +Sync)]
) ->Result<Option<Row>,Error>where
    T:ToStatement
[src]

fnquery_raw<'a, T: ?Sized, I>(
    &mut self,
    query:&T,
    params: I
) ->Result<RowIter,Error>where
    T:ToStatement,
    I:IntoIterator<Item = &'a dynToSql>,
    I::IntoIter:ExactSizeIterator
[src]

fnprepare(&mut self, query: &str) ->Result<Statement,Error>[src]

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

fncopy_in<T: ?Sized>(&mut self, query:&T) ->Result<CopyInWriter,Error>where
    T:ToStatement
[src]

fncopy_out<T: ?Sized>(&mut self, query:&T) ->Result<CopyOutReader,Error>where
    T:ToStatement
[src]

fnsimple_query(
    &mut self,
    query: &str
) ->Result<Vec<SimpleQueryMessage>,Error>
[src]

fnbatch_execute(&mut self, query: &str) ->Result<(),Error>[src]

fntransaction(&mut self) ->Result<Transaction,Error>[src]

Auto Trait Implementations

impl !RefUnwindSafe forClient

implSend forClient

implSync forClient

implUnpin forClient

impl !UnwindSafe forClient

Blanket Implementations

impl<T>Any for Twhere
    T: 'static + ?Sized
[src]

fntype_id(&self) ->TypeId[src]

impl<T>Borrow<T> for Twhere
    T: ?Sized
[src]

fnborrow(&self) ->&T[src]

impl<T>BorrowMut<T> for Twhere
    T: ?Sized
[src]

fnborrow_mut(&mut self) ->&mutT[src]

impl<T>From<T> for T[src]

fnfrom(t: T) -> T[src]

impl<T, U>Into<U> for Twhere
    U:From<T>, 
[src]

fninto(self) -> U[src]

impl<T> Same<T> for T

typeOutput = T

Should always beSelf

impl<T, U>TryFrom<U> for Twhere
    U:Into<T>, 
[src]

typeError =Infallible

The type returned in the event of a conversion error.

fntry_from(value: U) ->Result<T, <T asTryFrom<U>>::Error>[src]

impl<T, U>TryInto<U> for Twhere
    U:TryFrom<T>, 
[src]

typeError = <U asTryFrom<T>>::Error

The type returned in the event of a conversion error.

fntry_into(self) ->Result<U, <U asTryFrom<T>>::Error>[src]

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

fnvzip(self) -> V


[8]ページ先頭

©2009-2025 Movatter.jp