Structpostgres::Connection [−][src]
pub struct Connection(_);
A connection to a Postgres database.
Methods
implConnection
[src]
fnconnect<T>(params: T, tls:TlsMode) ->Result<Connection>where
T:IntoConnectParams,
[src]
T:IntoConnectParams,
Creates a new connection to a Postgres database.
Most applications can use a URL string in the normal format:
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 theusername if not specified.
To connect to the server via Unix sockets,host
should be set to theabsolute path of the directory containing the socket file. Since/
isa reserved character in URLs, the path should be URL encoded. If thepath contains non-UTF 8 characters, aConnectParams
struct should becreated manually and passed in. Note that Postgres does not support TLSover Unix sockets.
Examples
To connect over TCP:
usepostgres::{Connection,TlsMode};leturl="postgresql://postgres:hunter2@localhost:5433:2994/foodb";letconn=Connection::connect(url,TlsMode::None).unwrap();
To connect over a Unix socket located in/run/postgres
:
usepostgres::{Connection,TlsMode};leturl="postgresql://postgres@%2Frun%2Fpostgres";letconn=Connection::connect(url,TlsMode::None).unwrap();
To connect with a manually constructedConnectParams
:
usepostgres::{Connection,TlsMode};usepostgres::params::{ConnectParams,Host};letparams=ConnectParams::builder() .user("postgres",None) .build(Host::Unix(some_crazy_path));letconn=Connection::connect(params,TlsMode::None).unwrap();
fnexecute(&self, query: &str, params:&[&ToSql]) ->Result<u64>
[src]
Executes a statement, returning the number of rows modified.
A statement may contain parameters, specified by$n
wheren
is theindex of the parameter in the list provided, 1-indexed.
If the statement does not modify any rows (e.g. SELECT), 0 is returned.
If the same statement will be repeatedly executed (perhaps withdifferent query parameters), consider using theprepare
andprepare_cached
methods.
Panics
Panics if the number of parameters provided does not match the numberexpected.
Example
letrows_updated=conn.execute("UPDATE foo SET bar = $1 WHERE baz = $2",&[&bar,&baz]) .unwrap();println!("{} rows updated",rows_updated);
fnquery(&self, query: &str, params:&[&ToSql]) ->Result<Rows>
[src]
Executes a statement, returning the resulting rows.
A statement may contain parameters, specified by$n
wheren
is theindex of the parameter in the list provided, 1-indexed.
If the same statement will be repeatedly executed (perhaps withdifferent query parameters), consider using theprepare
andprepare_cached
methods.
Panics
Panics if the number of parameters provided does not match the numberexpected.
Example
forrowin&conn.query("SELECT foo FROM bar WHERE baz = $1",&[&baz]).unwrap() {letfoo:i32=row.get("foo");println!("foo: {}",foo);}
fntransaction<'a>(&'a self) ->Result<Transaction<'a>>
[src]
Begins a new transaction.
Returns aTransaction
object which should be used instead ofthe connection for the duration of the transaction. The transactionis active until theTransaction
object falls out of scope.
Note
A transaction will roll back by default. Theset_commit
,set_rollback
, andcommit
methods alter this behavior.
Panics
Panics if a transaction is already active.
Example
lettrans=conn.transaction().unwrap();trans.execute("UPDATE foo SET bar = 10",&[]).unwrap();// ...trans.commit().unwrap();
fntransaction_with<'a>(&'a self, config: &Config) ->Result<Transaction<'a>>
[src]
Begins a new transaction with the specified configuration.
fnprepare<'a>(&'a self, query: &str) ->Result<Statement<'a>>
[src]
Creates a new prepared statement.
If the same statement will be executed repeatedly, explicitly preparingit can improve performance.
The statement is associated with the connection that created it and maynot outlive that connection.
Example
letstmt=conn.prepare("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();for (bar,baz)inupdates {stmt.execute(&[bar,baz]).unwrap();}
fnprepare_cached<'a>(&'a self, query: &str) ->Result<Statement<'a>>
[src]
Creates a cached prepared statement.
Likeprepare
, except that the statement is only prepared once overthe lifetime of the connection and then cached. If the same statementis going to be prepared frequently, caching it can improve performanceby reducing the number of round trips to the Postgres backend.
Example
letstmt=conn.prepare_cached("UPDATE foo SET bar = $1 WHERE baz = $2").unwrap();for (bar,baz)inupdates {stmt.execute(&[bar,baz]).unwrap();}
fntransaction_isolation(&self) ->Result<IsolationLevel>
[src]
Returns the isolation level which will be used for future transactions.
This is a simple wrapper aroundSHOW TRANSACTION ISOLATION LEVEL
.
fnset_transaction_config(&self, config: &Config) ->Result<()>
[src]
Sets the configuration that will be used for future transactions.
fnbatch_execute(&self, query: &str) ->Result<()>
[src]
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 forexecution of batches of non-dynamic statements - for example, creationof a schema for a fresh database.
Warning
Prepared statements should be used for any SQL statement which containsuser-specified data, as it provides functionality to safely embed thatdata in the statement. Do not form statements via string concatenationand feed them into this method.
Example
conn.batch_execute(" CREATE TABLE person ( id SERIAL PRIMARY KEY, name NOT NULL ); CREATE TABLE purchase ( id SERIAL PRIMARY KEY, person INT NOT NULL REFERENCES person (id), time TIMESTAMPTZ NOT NULL, ); CREATE INDEX ON purchase (time); ").unwrap();
fnnotifications<'a>(&'a self) ->Notifications<'a>
[src]
Returns a structure providing access to asynchronous notifications.
Use theLISTEN
command to register this connection for notifications.
fncancel_data(&self) ->CancelData
[src]
Returns information used to cancel pending queries.
Used with thecancel_query
function. The object returned can be usedto cancel any query executed by the connection it was created from.
fnparameter(&self, param: &str) ->Option<String>
[src]
Returns the value of the specified Postgres backend parameter, such astimezone
orserver_version
.
fnset_notice_handler(&self, handler:Box<HandleNotice>) ->Box<HandleNotice>
[src]
Sets the notice handler for the connection, returning the old handler.
fnis_desynchronized(&self) ->bool
[src]
Returns whether or not the stream has been desynchronized due to anerror in the communication channel with the server.
If this has occurred, all further queries will immediately return anerror.
fnis_active(&self) ->bool
[src]
Determines if theConnection
is currently "active", that is, if thereare no active transactions.
Thetransaction
method can only be called on the activeConnection
orTransaction
.
fnfinish(self) ->Result<()>
[src]
Consumes the connection, closing it.
Functionally equivalent to theDrop
implementation forConnection
except that it returns any error encountered to the caller.
Trait Implementations
implDebug forConnection
[src]
implGenericConnection forConnection
[src]
fnexecute(&self, query: &str, params:&[&ToSql]) ->Result<u64>
[src]
LikeConnection::execute
.
fnquery<'a>(&'a self, query: &str, params:&[&ToSql]) ->Result<Rows>
[src]
LikeConnection::query
.
fnprepare<'a>(&'a self, query: &str) ->Result<Statement<'a>>
[src]
LikeConnection::prepare
.
fnprepare_cached<'a>(&'a self, query: &str) ->Result<Statement<'a>>
[src]
LikeConnection::prepare_cached
.
fntransaction<'a>(&'a self) ->Result<Transaction<'a>>
[src]
LikeConnection::transaction
.
fnbatch_execute(&self, query: &str) ->Result<()>
[src]
LikeConnection::batch_execute
.
fnis_active(&self) ->bool
[src]
LikeConnection::is_active
.