Struct postgres::Connection
[−]
[src]
pub struct Connection { // some fields omitted }
A connection to a Postgres database.
Methods
impl Connection
[src]
fn connect<T>(params: T, ssl: &SslMode) -> Result<Connection, ConnectError> where 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 the username if not specified.
Connection via Unix sockets is supported with the unix_socket
feature. To connect to the server via Unix sockets, host
should be
set to the absolute path of the directory containing the socket file.
Since /
is a reserved character in URLs, the path should be URL
encoded. If the path contains non-UTF 8 characters, a ConnectParams
struct should be created manually and passed in. Note that Postgres
does not support SSL over Unix sockets.
Examples
let url = "postgresql://postgres:hunter2@localhost:2994/foodb"; let conn = try!(Connection::connect(url, &SslMode::None));
let url = "postgresql://postgres@%2Frun%2Fpostgres"; let conn = try!(Connection::connect(url, &SslMode::None));
let params = ConnectParams { target: ConnectTarget::Unix(some_crazy_path), port: None, user: Some(UserInfo { user: "postgres".to_string(), password: None }), database: None, options: vec![], }; let conn = try!(Connection::connect(params, &SslMode::None));
fn set_notice_handler(&self, handler: Box<HandleNotice>) -> Box<HandleNotice>
Sets the notice handler for the connection, returning the old handler.
fn notifications<'a>(&'a self) -> Notifications<'a>
Returns an iterator over asynchronous notification messages.
Use the LISTEN
command to register this connection for notifications.
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>>
Creates a new prepared statement.
A statement may contain parameters, specified by $n
where n
is the
index of the parameter in the list provided at execution time,
1-indexed.
The statement is associated with the connection that created it and may not outlive that connection.
Example
let maybe_stmt = conn.prepare("SELECT foo FROM bar WHERE baz = $1"); let stmt = match maybe_stmt { Ok(stmt) => stmt, Err(err) => panic!("Error preparing statement: {:?}", err) };
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>>
Creates cached prepared statement.
Like prepare
, except that the statement is only prepared once over
the lifetime of the connection and then cached. If the same statement
is going to be used frequently, caching it can improve performance by
reducing the number of round trips to the Postgres backend.
Example
let stmt = try!(conn.prepare_cached("SELECT foo FROM bar WHERE baz = $1")); for row in try!(stmt.query(&[&x])) { println!("foo: {}", row.get::<_, String>(0)); }
fn transaction<'a>(&'a self) -> Result<Transaction<'a>>
Begins a new transaction.
Returns a Transaction
object which should be used instead of
the connection for the duration of the transaction. The transaction
is active until the Transaction
object falls out of scope.
Note
A transaction will roll back by default. The set_commit
,
set_rollback
, and commit
methods alter this behavior.
Panics
Panics if a transaction is already active.
Example
let trans = try!(conn.transaction()); try!(trans.execute("UPDATE foo SET bar = 10", &[])); // ... try!(trans.commit());
fn set_transaction_isolation(&self, level: IsolationLevel) -> Result<()>
Sets the isolation level which will be used for future transactions.
Note
This will not change the behavior of an active transaction.
fn transaction_isolation(&self) -> Result<IsolationLevel>
Returns the isolation level which will be used for future transactions.
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64>
A convenience function for queries that are only run once.
If an error is returned, it could have come from either the preparation or execution of the statement.
On success, returns the number of rows modified or 0 if not applicable.
Panics
Panics if the number of parameters provided does not match the number expected.
fn batch_execute(&self, query: &str) -> Result<()>
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 for
execution of batches of non-dynamic statements - for example, creation
of a schema for a fresh database.
Warning
Prepared statements should be used for any SQL statement which contains user-specified data, as it provides functionality to safely embed that data in the statement. Do not form statements via string concatenation and feed them into this method.
Example
fn init_db(conn: &Connection) -> Result<()> { 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); ") }
fn cancel_data(&self) -> CancelData
Returns information used to cancel pending queries.
Used with the cancel_query
function. The object returned can be used
to cancel any query executed by the connection it was created from.
fn parameter(&self, param: &str) -> Option<String>
Returns the value of the specified Postgres backend parameter, such as
timezone
or server_version
.
fn is_desynchronized(&self) -> bool
Returns whether or not the stream has been desynchronized due to an error in the communication channel with the server.
If this has occurred, all further queries will immediately return an error.
fn is_active(&self) -> bool
Determines if the Connection
is currently "active", that is, if there
are no active transactions.
The transaction
method can only be called on the active Connection
or Transaction
.
fn finish(self) -> Result<()>
Consumes the connection, closing it.
Functionally equivalent to the Drop
implementation for Connection
except that it returns any error encountered to the caller.
Trait Implementations
impl Debug for Connection
[src]
impl GenericConnection for Connection
[src]
fn prepare<'a>(&'a self, query: &str) -> Result<Statement<'a>>
Like Connection::prepare
.
fn prepare_cached<'a>(&'a self, query: &str) -> Result<Statement<'a>>
Like Connection::prepare_cached
.
fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64>
Like Connection::execute
.
fn transaction<'a>(&'a self) -> Result<Transaction<'a>>
Like Connection::transaction
.
fn batch_execute(&self, query: &str) -> Result<()>
Like Connection::batch_execute
.
fn is_active(&self) -> bool
Like Connection::is_active
.