Struct Connection

Source
pub struct Connection { /* private fields */ }

Implementations§

§

impl Connection

pub fn send_query(&self, command: &str) -> Result

Submits a command to the server without waiting for the result(s).

See PQsendQuery.

pub fn send_query_params( &self, command: &str, param_types: &[Oid], param_values: &[Option<&[u8]>], param_formats: &[Format], result_format: Format, ) -> Result

Submits a command and separate parameters to the server without waiting for the result(s).

See PQsendQueryParams.

pub fn send_prepare( &self, name: Option<&str>, query: &str, param_types: &[Oid], ) -> Result

Sends a request to create a prepared statement with the given parameters, without waiting for completion.

See PQsendPrepare.

pub fn send_query_prepared( &self, name: Option<&str>, param_values: &[Option<&[u8]>], param_formats: &[Format], result_format: Format, ) -> Result

Sends a request to execute a prepared statement with given parameters, without waiting for the result(s).

See PQsendQueryPrepared.

pub fn send_describe_prepared(&self, name: Option<&str>) -> Result

Submits a request to obtain information about the specified prepared statement, without waiting for completion.

See PQsendDescribePortal.

pub fn send_describe_portal(&self, name: Option<&str>) -> Result

Submits a request to obtain information about the specified portal, without waiting for completion.

See PQsendDescribePortal.

pub fn result(&self) -> Option<PQResult>

Waits for the next result a prior send_* call, and returns it.

See PQgetResult.

pub fn consume_input(&self) -> Result

If input is available from the server, consume it.

See PQconsumeInput.

Examples found in repository?
examples/testlibpq2.rs (line 78)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}

pub fn is_busy(&self) -> bool

Returns true if a command is busy, that is, Result would block waiting for input.

See PQisBusy.

pub fn set_non_blocking(&self, non_blocking: bool) -> Result

Sets the nonblocking status of the connection.

See PQsetnonblocking.

pub fn is_non_blocking(&self) -> bool

Returns the blocking status of the database connection.

See PQisnonblocking.

pub fn flush(&self) -> Result

Attempts to flush any queued output data to the server.

See PQflush.

§

impl Connection

pub fn cancel(&self) -> Cancel

Creates a data structure containing the information needed to cancel a command issued through a particular database connection.

See PQgetCancel.

§

impl Connection

pub fn new(dsn: &str) -> Result<Self>

Makes a new connection to the database server.

See PQconnectdb.

Examples found in repository?
examples/testlibpq2.rs (line 42)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}
More examples
Hide additional examples
examples/testlibpq.rs (line 17)
6fn main() -> libpq::errors::Result {
7    /*
8     * If the user supplies a parameter on the command line, use it as the
9     * conninfo string; otherwise default to setting dbname=postgres and using
10     * environment variables or defaults for all other connection parameters.
11     */
12    let conninfo = std::env::args()
13        .nth(1)
14        .unwrap_or_else(|| "dbname = postgres".to_string());
15
16    /* Make a connection to the database */
17    let conn = libpq::Connection::new(&conninfo)?;
18
19    /* Set always-secure search path, so malicious users can't take control. */
20    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
21    if res.status() != libpq::Status::TuplesOk {
22        panic!("SET failed: {:?}", conn.error_message());
23    }
24
25    /*
26     * Our test case here involves using a cursor, for which we must be inside
27     * a transaction block.  We could do the whole thing with a single
28     * PQexec() of "select * from pg_database", but that's too trivial to make
29     * a good example.
30     */
31
32    /* Start a transaction block */
33    let res = conn.exec("BEGIN");
34    if res.status() != libpq::Status::CommandOk {
35        panic!("BEGIN command failed: {:?}", conn.error_message());
36    }
37
38    /*
39     * Fetch rows from pg_database, the system catalog of databases
40     */
41    let res = conn.exec("DECLARE myportal CURSOR FOR select * from pg_database");
42    if res.status() != libpq::Status::CommandOk {
43        panic!("DECLARE CURSOR failed: {:?}", conn.error_message());
44    }
45
46    let res = conn.exec("FETCH ALL in myportal");
47    if res.status() != libpq::Status::TuplesOk {
48        panic!("FETCH ALL failed: {:?}", conn.error_message());
49    }
50
51    /* first, print out the attribute names */
52    let nfields = res.nfields();
53    for i in 0..nfields {
54        print!("{:15}", res.field_name(i)?.unwrap_or_default());
55    }
56    println!("\n");
57
58    /* next, print out the rows */
59    for i in 0..res.ntuples() {
60        for j in 0..nfields {
61            let s = res
62                .value(i, j)
63                .map(|x| String::from_utf8(x.to_vec()).unwrap())
64                .unwrap_or_default();
65            print!("{s:15}");
66        }
67        println!();
68    }
69
70    /* close the portal ... we don't bother to check for errors ... */
71    conn.exec("CLOSE myportal");
72
73    /* end the transaction */
74    conn.exec("END");
75
76    Ok(())
77}
examples/testlibpq3.rs (line 44)
33fn main() -> Result<(), Box<dyn std::error::Error>> {
34    /*
35     * If the user supplies a parameter on the command line, use it as the
36     * conninfo string; otherwise default to setting dbname=postgres and using
37     * environment variables or defaults for all other connection parameters.
38     */
39    let conninfo = std::env::args()
40        .nth(1)
41        .unwrap_or_else(|| "dbname = postgres".to_string());
42
43    /* Make a connection to the database */
44    let conn = libpq::Connection::new(&conninfo)?;
45
46    /* Set always-secure search path, so malicious users can't take control. */
47    let res = conn.exec("SET search_path = testlibpq3");
48    if res.status() != libpq::Status::CommandOk {
49        panic!("SET failed: {:?}", conn.error_message());
50    }
51
52    /*
53     * The point of this program is to illustrate use of PQexecParams() with
54     * out-of-line parameters, as well as binary transmission of data.
55     *
56     * This first example transmits the parameters as text, but receives the
57     * results in binary format.  By using out-of-line parameters we can avoid
58     * a lot of tedious mucking about with quoting and escaping, even though
59     * the data is text.  Notice how we don't have to do anything special with
60     * the quote mark in the parameter value.
61     */
62
63    /* Here is our out-of-line parameter value */
64    let param_values = [Some("joe's place\0".as_bytes())];
65
66    let res = conn.exec_params(
67        "SELECT * FROM test1 WHERE t = $1",
68        &[], /* let the backend deduce param type */
69        param_values.as_slice(),
70        &[],                   /* default to all text params */
71        libpq::Format::Binary, /* ask for binary results */
72    );
73
74    if res.status() != libpq::Status::TuplesOk {
75        panic!("SELECT failed: {:?}", conn.error_message());
76    }
77
78    show_binary_results(&res)?;
79
80    /*
81     * In this second example we transmit an integer parameter in binary form,
82     * and again retrieve the results in binary form.
83     *
84     * Although we tell PQexecParams we are letting the backend deduce
85     * parameter type, we really force the decision by casting the parameter
86     * symbol in the query text.  This is a good safety measure when sending
87     * binary parameters.
88     */
89
90    /* Convert integer value "2" to network byte order */
91    let binary_int_val = htonl(2);
92
93    /* Set up parameter arrays for PQexecParams */
94    let param_values = [Some(binary_int_val.as_slice())];
95    let param_formats = vec![libpq::Format::Binary];
96
97    let res = conn.exec_params(
98        "SELECT * FROM test1 WHERE i = $1::int4",
99        &[], /* let the backend deduce param type */
100        &param_values,
101        &param_formats,
102        libpq::Format::Binary, /* ask for binary results */
103    );
104
105    if res.status() != libpq::Status::TuplesOk {
106        panic!("SELECT failed: {:?}", conn.error_message());
107    }
108
109    show_binary_results(&res)?;
110
111    Ok(())
112}

pub fn with_params( params: &HashMap<&str, &str>, expand_dbname: bool, ) -> Result<Self>

Makes a new connection to the database server.

See PQconnectdbParams.

pub fn start(conninfo: &str) -> Result<Self>

Make a connection to the database server in a nonblocking manner.

See PQconnectStart.

pub fn start_params( params: &HashMap<String, String>, expand_dbname: bool, ) -> Result<Self>

Make a connection to the database server in a nonblocking manner.

See PQconnectStartParams.

pub fn set_db( host: Option<&str>, port: Option<&str>, options: Option<&str>, tty: Option<&str>, db_name: Option<&str>, ) -> Result<Self>

Makes a new connection to the database server.

See PQsetdb.

Examples found in repository?
examples/testlo.rs (line 24)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 4 {
11        panic!(
12            "usage: {} database_name in_filename out_filename",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20
21    /*
22     * set up the connection
23     */
24    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
25
26    /* Set always-secure search path, so malicious users can't take control. */
27    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
28    if res.status() != libpq::Status::TuplesOk {
29        panic!("SET failed: {:?}", conn.error_message());
30    }
31
32    conn.exec("begin");
33    println!("importing file \"{in_filename}\" ...");
34    let lobj_oid = libpq::lo::import(&conn, &in_filename);
35
36    println!("\tas large object {lobj_oid}.");
37
38    println!("picking out bytes 1000-2000 of the large object");
39    pickout(&conn, lobj_oid, 1_000, 1_000)?;
40
41    println!("overwriting bytes 1000-2000 of the large object with X's");
42    overwrite(&conn, lobj_oid, 1_000, 1_000)?;
43
44    println!("exporting large object to file \"{out_filename}\" ...");
45    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
46
47    conn.exec("end");
48
49    Ok(())
50}
More examples
Hide additional examples
examples/testlo64.rs (line 25)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 5 {
11        panic!(
12            "usage: {} database_name in_filename out_filename out_filename2",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20    let out_filename2 = args.next().unwrap();
21
22    /*
23     * set up the connection
24     */
25    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
26
27    /* Set always-secure search path, so malicious users can't take control. */
28    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
29    if res.status() != libpq::Status::TuplesOk {
30        panic!("SET failed: {:?}", conn.error_message());
31    }
32
33    conn.exec("begin");
34
35    println!("importing file \"{in_filename}\" ...");
36    let lobj_oid = libpq::lo::import(&conn, &in_filename);
37
38    println!("\tas large object {lobj_oid}.");
39
40    println!("picking out bytes 4294967000-4294968000 of the large object");
41    pickout(&conn, lobj_oid, 4_294_967_000, 1_000)?;
42
43    println!("overwriting bytes 4294967000-4294968000 of the large object with X's");
44    overwrite(&conn, lobj_oid, 4_294_967_000, 1_000)?;
45
46    println!("exporting large object to file \"{out_filename}\" ...");
47    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
48
49    println!("truncating to 3294968000 bytes");
50    my_truncate(&conn, lobj_oid, 3_294_968_000)?;
51
52    println!("exporting truncated large object to file \"{out_filename2}\" ...");
53    libpq::lo::export(&conn, &out_filename2, lobj_oid)?;
54
55    conn.exec("end");
56
57    Ok(())
58}
examples/testlibpq4.rs (line 29)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let mut args = std::env::args();
9
10    if args.len() < 4 {
11        panic!(
12            "usage: {} table_name db_name1 db_name2\n      compares two tables in two databases",
13            args.next().unwrap()
14        );
15    }
16
17    let _tbl_name = args.nth(1).unwrap();
18    let db_name1 = args.next().unwrap();
19    let db_name2 = args.next().unwrap();
20
21    /*
22     * begin, by setting the parameters for a backend connection if the
23     * parameters are None, then the system will try to use reasonable
24     * defaults by looking up environment variables or, failing that, using
25     * hardwired constants
26     */
27
28    /* make a connection to the database */
29    let conn1 = libpq::Connection::set_db(None, None, None, None, Some(&db_name1))?;
30    check_prepare_conn(&conn1, &db_name1);
31
32    let conn2 = libpq::Connection::set_db(None, None, None, None, Some(&db_name2))?;
33    check_prepare_conn(&conn2, &db_name2);
34
35    /* start a transaction block */
36    let res1 = conn1.exec("BEGIN");
37    if res1.status() != libpq::Status::CommandOk {
38        panic!("BEGIN command failed");
39    }
40
41    /*
42     * fetch instances from the pg_database, the system catalog of databases
43     */
44    let res1 = conn1.exec("DECLARE myportal CURSOR FOR select * from pg_database");
45    if res1.status() != libpq::Status::CommandOk {
46        panic!("DECLARE CURSOR command failed");
47    }
48
49    let res1 = conn1.exec("FETCH ALL in myportal");
50    if res1.status() != libpq::Status::TuplesOk {
51        panic!("FETCH ALL command didn't return tuples properly");
52    }
53
54    /* first, print out the attribute names */
55    let nfields = res1.nfields();
56    for i in 0..nfields {
57        print!("{:15}", res1.field_name(i)?.unwrap_or_default());
58    }
59    println!("\n");
60
61    /* next, print out the instances */
62    for i in 0..res1.ntuples() {
63        for j in 0..nfields {
64            let s = res1
65                .value(i, j)
66                .map(|x| String::from_utf8(x.to_vec()).unwrap())
67                .unwrap_or_default();
68            print!("{s:15}");
69        }
70        println!();
71    }
72
73    /* close the portal */
74    conn1.exec("CLOSE myportal");
75
76    /* end the transaction */
77    conn1.exec("END");
78
79    Ok(())
80}

pub fn login( host: Option<&str>, port: Option<&str>, options: Option<&str>, tty: Option<&str>, db_name: Option<&str>, login: Option<&str>, pwd: Option<&str>, ) -> Result<Self>

Makes a new connection to the database server.

See PQsetdbLogin.

pub fn poll(&self) -> Status

pub fn reset(&self)

Resets the communication channel to the server.

See PQreset.

pub fn reset_start(&self)

Reset the communication channel to the server, in a nonblocking manner.

See PQresetStart.

pub fn reset_poll(&self) -> Status

pub fn ping_params( params: &HashMap<String, String>, expand_dbname: bool, ) -> Status

Reports the status of the server.

It accepts connection parameters identical to those of libpq::Connection::with_params. It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.

See PQpingParams.

pub fn ping(dsn: &str) -> Status

Reports the status of the server.

It accepts connection parameters identical to those of libpq::Connection::new. It is not necessary to supply correct user name, password, or database name values to obtain the server status; however, if incorrect values are provided, the server will log a failed connection attempt.

See PQping.

pub fn info(&self) -> Result<HashMap<String, Info>>

Return the connection options used for the connection

See PQconninfo.

§

impl Connection

pub fn client_encoding(&self) -> Encoding

Returns the client encoding.

See PQclientEncoding.

pub fn set_client_encoding(&self, encoding: Encoding)

Sets the client encoding.

See PQsetClientEncoding.

pub fn set_error_verbosity(&self, verbosity: Verbosity) -> Verbosity

Determines the verbosity of messages returned by libpq::Connection::error_message and libpq::Result::error_message.

See PQsetErrorVerbosity.

§

impl Connection

pub fn put_copy_data(&self, buffer: &[u8]) -> Result

Sends data to the server during libpq::Status::CopyIn state.

See PQputCopyData.

pub fn put_copy_end(&self, errormsg: Option<&str>) -> Result

Sends end-of-data indication to the server during libpq::Status::CopyIn state.

See PQputCopyEnd.

pub fn copy_data(&self, async: bool) -> Result<PqBytes>

Receives data from the server during libpq::Status::CopyOut or libpq::Status::CopyBoth state.

On success, this method returns PqBytes.

See PQgetCopyData

§

impl Connection

pub fn exec(&self, query: &str) -> PQResult

Submits a command to the server and waits for the result.

See PQexec.

Examples found in repository?
examples/testlo.rs (line 27)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 4 {
11        panic!(
12            "usage: {} database_name in_filename out_filename",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20
21    /*
22     * set up the connection
23     */
24    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
25
26    /* Set always-secure search path, so malicious users can't take control. */
27    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
28    if res.status() != libpq::Status::TuplesOk {
29        panic!("SET failed: {:?}", conn.error_message());
30    }
31
32    conn.exec("begin");
33    println!("importing file \"{in_filename}\" ...");
34    let lobj_oid = libpq::lo::import(&conn, &in_filename);
35
36    println!("\tas large object {lobj_oid}.");
37
38    println!("picking out bytes 1000-2000 of the large object");
39    pickout(&conn, lobj_oid, 1_000, 1_000)?;
40
41    println!("overwriting bytes 1000-2000 of the large object with X's");
42    overwrite(&conn, lobj_oid, 1_000, 1_000)?;
43
44    println!("exporting large object to file \"{out_filename}\" ...");
45    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
46
47    conn.exec("end");
48
49    Ok(())
50}
More examples
Hide additional examples
examples/testlo64.rs (line 28)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 5 {
11        panic!(
12            "usage: {} database_name in_filename out_filename out_filename2",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20    let out_filename2 = args.next().unwrap();
21
22    /*
23     * set up the connection
24     */
25    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
26
27    /* Set always-secure search path, so malicious users can't take control. */
28    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
29    if res.status() != libpq::Status::TuplesOk {
30        panic!("SET failed: {:?}", conn.error_message());
31    }
32
33    conn.exec("begin");
34
35    println!("importing file \"{in_filename}\" ...");
36    let lobj_oid = libpq::lo::import(&conn, &in_filename);
37
38    println!("\tas large object {lobj_oid}.");
39
40    println!("picking out bytes 4294967000-4294968000 of the large object");
41    pickout(&conn, lobj_oid, 4_294_967_000, 1_000)?;
42
43    println!("overwriting bytes 4294967000-4294968000 of the large object with X's");
44    overwrite(&conn, lobj_oid, 4_294_967_000, 1_000)?;
45
46    println!("exporting large object to file \"{out_filename}\" ...");
47    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
48
49    println!("truncating to 3294968000 bytes");
50    my_truncate(&conn, lobj_oid, 3_294_968_000)?;
51
52    println!("exporting truncated large object to file \"{out_filename2}\" ...");
53    libpq::lo::export(&conn, &out_filename2, lobj_oid)?;
54
55    conn.exec("end");
56
57    Ok(())
58}
examples/testlibpq2.rs (line 45)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}
examples/testlibpq4.rs (line 36)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let mut args = std::env::args();
9
10    if args.len() < 4 {
11        panic!(
12            "usage: {} table_name db_name1 db_name2\n      compares two tables in two databases",
13            args.next().unwrap()
14        );
15    }
16
17    let _tbl_name = args.nth(1).unwrap();
18    let db_name1 = args.next().unwrap();
19    let db_name2 = args.next().unwrap();
20
21    /*
22     * begin, by setting the parameters for a backend connection if the
23     * parameters are None, then the system will try to use reasonable
24     * defaults by looking up environment variables or, failing that, using
25     * hardwired constants
26     */
27
28    /* make a connection to the database */
29    let conn1 = libpq::Connection::set_db(None, None, None, None, Some(&db_name1))?;
30    check_prepare_conn(&conn1, &db_name1);
31
32    let conn2 = libpq::Connection::set_db(None, None, None, None, Some(&db_name2))?;
33    check_prepare_conn(&conn2, &db_name2);
34
35    /* start a transaction block */
36    let res1 = conn1.exec("BEGIN");
37    if res1.status() != libpq::Status::CommandOk {
38        panic!("BEGIN command failed");
39    }
40
41    /*
42     * fetch instances from the pg_database, the system catalog of databases
43     */
44    let res1 = conn1.exec("DECLARE myportal CURSOR FOR select * from pg_database");
45    if res1.status() != libpq::Status::CommandOk {
46        panic!("DECLARE CURSOR command failed");
47    }
48
49    let res1 = conn1.exec("FETCH ALL in myportal");
50    if res1.status() != libpq::Status::TuplesOk {
51        panic!("FETCH ALL command didn't return tuples properly");
52    }
53
54    /* first, print out the attribute names */
55    let nfields = res1.nfields();
56    for i in 0..nfields {
57        print!("{:15}", res1.field_name(i)?.unwrap_or_default());
58    }
59    println!("\n");
60
61    /* next, print out the instances */
62    for i in 0..res1.ntuples() {
63        for j in 0..nfields {
64            let s = res1
65                .value(i, j)
66                .map(|x| String::from_utf8(x.to_vec()).unwrap())
67                .unwrap_or_default();
68            print!("{s:15}");
69        }
70        println!();
71    }
72
73    /* close the portal */
74    conn1.exec("CLOSE myportal");
75
76    /* end the transaction */
77    conn1.exec("END");
78
79    Ok(())
80}
81
82fn check_prepare_conn(conn: &libpq::Connection, _db_name: &str) {
83    if conn.status() != libpq::connection::Status::Ok {
84        panic!("{:?}", conn.error_message());
85    }
86
87    /* Set always-secure search path, so malicious users can't take control. */
88    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
89    if res.status() != libpq::Status::TuplesOk {
90        panic!("SET failed: {:?}", conn.error_message());
91    }
92}
examples/testlibpq.rs (line 20)
6fn main() -> libpq::errors::Result {
7    /*
8     * If the user supplies a parameter on the command line, use it as the
9     * conninfo string; otherwise default to setting dbname=postgres and using
10     * environment variables or defaults for all other connection parameters.
11     */
12    let conninfo = std::env::args()
13        .nth(1)
14        .unwrap_or_else(|| "dbname = postgres".to_string());
15
16    /* Make a connection to the database */
17    let conn = libpq::Connection::new(&conninfo)?;
18
19    /* Set always-secure search path, so malicious users can't take control. */
20    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
21    if res.status() != libpq::Status::TuplesOk {
22        panic!("SET failed: {:?}", conn.error_message());
23    }
24
25    /*
26     * Our test case here involves using a cursor, for which we must be inside
27     * a transaction block.  We could do the whole thing with a single
28     * PQexec() of "select * from pg_database", but that's too trivial to make
29     * a good example.
30     */
31
32    /* Start a transaction block */
33    let res = conn.exec("BEGIN");
34    if res.status() != libpq::Status::CommandOk {
35        panic!("BEGIN command failed: {:?}", conn.error_message());
36    }
37
38    /*
39     * Fetch rows from pg_database, the system catalog of databases
40     */
41    let res = conn.exec("DECLARE myportal CURSOR FOR select * from pg_database");
42    if res.status() != libpq::Status::CommandOk {
43        panic!("DECLARE CURSOR failed: {:?}", conn.error_message());
44    }
45
46    let res = conn.exec("FETCH ALL in myportal");
47    if res.status() != libpq::Status::TuplesOk {
48        panic!("FETCH ALL failed: {:?}", conn.error_message());
49    }
50
51    /* first, print out the attribute names */
52    let nfields = res.nfields();
53    for i in 0..nfields {
54        print!("{:15}", res.field_name(i)?.unwrap_or_default());
55    }
56    println!("\n");
57
58    /* next, print out the rows */
59    for i in 0..res.ntuples() {
60        for j in 0..nfields {
61            let s = res
62                .value(i, j)
63                .map(|x| String::from_utf8(x.to_vec()).unwrap())
64                .unwrap_or_default();
65            print!("{s:15}");
66        }
67        println!();
68    }
69
70    /* close the portal ... we don't bother to check for errors ... */
71    conn.exec("CLOSE myportal");
72
73    /* end the transaction */
74    conn.exec("END");
75
76    Ok(())
77}
examples/testlibpq3.rs (line 47)
33fn main() -> Result<(), Box<dyn std::error::Error>> {
34    /*
35     * If the user supplies a parameter on the command line, use it as the
36     * conninfo string; otherwise default to setting dbname=postgres and using
37     * environment variables or defaults for all other connection parameters.
38     */
39    let conninfo = std::env::args()
40        .nth(1)
41        .unwrap_or_else(|| "dbname = postgres".to_string());
42
43    /* Make a connection to the database */
44    let conn = libpq::Connection::new(&conninfo)?;
45
46    /* Set always-secure search path, so malicious users can't take control. */
47    let res = conn.exec("SET search_path = testlibpq3");
48    if res.status() != libpq::Status::CommandOk {
49        panic!("SET failed: {:?}", conn.error_message());
50    }
51
52    /*
53     * The point of this program is to illustrate use of PQexecParams() with
54     * out-of-line parameters, as well as binary transmission of data.
55     *
56     * This first example transmits the parameters as text, but receives the
57     * results in binary format.  By using out-of-line parameters we can avoid
58     * a lot of tedious mucking about with quoting and escaping, even though
59     * the data is text.  Notice how we don't have to do anything special with
60     * the quote mark in the parameter value.
61     */
62
63    /* Here is our out-of-line parameter value */
64    let param_values = [Some("joe's place\0".as_bytes())];
65
66    let res = conn.exec_params(
67        "SELECT * FROM test1 WHERE t = $1",
68        &[], /* let the backend deduce param type */
69        param_values.as_slice(),
70        &[],                   /* default to all text params */
71        libpq::Format::Binary, /* ask for binary results */
72    );
73
74    if res.status() != libpq::Status::TuplesOk {
75        panic!("SELECT failed: {:?}", conn.error_message());
76    }
77
78    show_binary_results(&res)?;
79
80    /*
81     * In this second example we transmit an integer parameter in binary form,
82     * and again retrieve the results in binary form.
83     *
84     * Although we tell PQexecParams we are letting the backend deduce
85     * parameter type, we really force the decision by casting the parameter
86     * symbol in the query text.  This is a good safety measure when sending
87     * binary parameters.
88     */
89
90    /* Convert integer value "2" to network byte order */
91    let binary_int_val = htonl(2);
92
93    /* Set up parameter arrays for PQexecParams */
94    let param_values = [Some(binary_int_val.as_slice())];
95    let param_formats = vec![libpq::Format::Binary];
96
97    let res = conn.exec_params(
98        "SELECT * FROM test1 WHERE i = $1::int4",
99        &[], /* let the backend deduce param type */
100        &param_values,
101        &param_formats,
102        libpq::Format::Binary, /* ask for binary results */
103    );
104
105    if res.status() != libpq::Status::TuplesOk {
106        panic!("SELECT failed: {:?}", conn.error_message());
107    }
108
109    show_binary_results(&res)?;
110
111    Ok(())
112}

pub fn exec_params( &self, command: &str, param_types: &[Oid], param_values: &[Option<&[u8]>], param_formats: &[Format], result_format: Format, ) -> PQResult

Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text.

See PQexecParams.

Examples found in repository?
examples/testlibpq3.rs (lines 66-72)
33fn main() -> Result<(), Box<dyn std::error::Error>> {
34    /*
35     * If the user supplies a parameter on the command line, use it as the
36     * conninfo string; otherwise default to setting dbname=postgres and using
37     * environment variables or defaults for all other connection parameters.
38     */
39    let conninfo = std::env::args()
40        .nth(1)
41        .unwrap_or_else(|| "dbname = postgres".to_string());
42
43    /* Make a connection to the database */
44    let conn = libpq::Connection::new(&conninfo)?;
45
46    /* Set always-secure search path, so malicious users can't take control. */
47    let res = conn.exec("SET search_path = testlibpq3");
48    if res.status() != libpq::Status::CommandOk {
49        panic!("SET failed: {:?}", conn.error_message());
50    }
51
52    /*
53     * The point of this program is to illustrate use of PQexecParams() with
54     * out-of-line parameters, as well as binary transmission of data.
55     *
56     * This first example transmits the parameters as text, but receives the
57     * results in binary format.  By using out-of-line parameters we can avoid
58     * a lot of tedious mucking about with quoting and escaping, even though
59     * the data is text.  Notice how we don't have to do anything special with
60     * the quote mark in the parameter value.
61     */
62
63    /* Here is our out-of-line parameter value */
64    let param_values = [Some("joe's place\0".as_bytes())];
65
66    let res = conn.exec_params(
67        "SELECT * FROM test1 WHERE t = $1",
68        &[], /* let the backend deduce param type */
69        param_values.as_slice(),
70        &[],                   /* default to all text params */
71        libpq::Format::Binary, /* ask for binary results */
72    );
73
74    if res.status() != libpq::Status::TuplesOk {
75        panic!("SELECT failed: {:?}", conn.error_message());
76    }
77
78    show_binary_results(&res)?;
79
80    /*
81     * In this second example we transmit an integer parameter in binary form,
82     * and again retrieve the results in binary form.
83     *
84     * Although we tell PQexecParams we are letting the backend deduce
85     * parameter type, we really force the decision by casting the parameter
86     * symbol in the query text.  This is a good safety measure when sending
87     * binary parameters.
88     */
89
90    /* Convert integer value "2" to network byte order */
91    let binary_int_val = htonl(2);
92
93    /* Set up parameter arrays for PQexecParams */
94    let param_values = [Some(binary_int_val.as_slice())];
95    let param_formats = vec![libpq::Format::Binary];
96
97    let res = conn.exec_params(
98        "SELECT * FROM test1 WHERE i = $1::int4",
99        &[], /* let the backend deduce param type */
100        &param_values,
101        &param_formats,
102        libpq::Format::Binary, /* ask for binary results */
103    );
104
105    if res.status() != libpq::Status::TuplesOk {
106        panic!("SELECT failed: {:?}", conn.error_message());
107    }
108
109    show_binary_results(&res)?;
110
111    Ok(())
112}

pub fn prepare( &self, name: Option<&str>, query: &str, param_types: &[Oid], ) -> PQResult

Submits a request to create a prepared statement with the given parameters, and waits for completion.

See PQprepare.

pub fn exec_prepared( &self, name: Option<&str>, param_values: &[Option<&[u8]>], param_formats: &[Format], result_format: Format, ) -> PQResult

Sends a request to execute a prepared statement with given parameters, and waits for the result.

See PQexecPrepared.

pub fn describe_prepared(&self, name: Option<&str>) -> PQResult

Submits a request to obtain information about the specified prepared statement, and waits for completion.

See PQdescribePrepared.

pub fn describe_portal(&self, name: Option<&str>) -> PQResult

Submits a request to obtain information about the specified portal, and waits for completion.

See PQdescribePortal.

pub fn escape_literal(&self, str: &str) -> Result<PqString>

Escape a string for use within an SQL command.

On success, this method returns PqString. See PQescapeLiteral.

pub fn escape_identifier(&self, str: &str) -> Result<PqString>

Escapes a string for use as an SQL identifier, such as a table, column, or function name.

On success, this method returns PqString.

See PQescapeIdentifier.

pub fn escape_string(&self, from: &str) -> Result<String>

Escape string literals, much like libpq::Connection::literal.

On success, this method returns String.

See PQescapeStringConn.

pub fn escape_bytea(&self, from: &[u8]) -> Result<PqBytes>

Escapes binary data for use within an SQL command with the type bytea.

On success, this method returns PqBytes.

See PQescapeByteaConn.

§

impl Connection

pub fn gss_enc_in_use(&self) -> bool

Return true if GSSAPI encryption is in use

pub fn gss_context(&self) -> *const c_void

Returns GSSAPI context if GSSAPI is in use

§Safety

This function returns a void* pointer.

§

impl Connection

pub unsafe fn set_notice_processor( &self, proc: NoticeProcessor, arg: *mut c_void, ) -> NoticeProcessor

§Safety

This function takes a void* pointer as argument.

pub unsafe fn set_notice_receiver( &self, proc: NoticeReceiver, arg: *mut c_void, ) -> NoticeReceiver

§Safety

This function takes a void* pointer as argument.

§

impl Connection

pub fn notifies(&self) -> Option<Notify>

Returns the next notification from a list of unhandled notification messages received from the server.

Examples found in repository?
examples/testlibpq2.rs (line 79)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}
§

impl Connection

pub fn set_single_row_mode(&self) -> Result

Select single-row mode for the currently-executing query.

See PQsetSingleRowMode.

§

impl Connection

pub fn init_openssl(do_ssl: bool, do_crypto: bool)

Allows applications to select which security libraries to initialize.

See PQinitOpenSSL.

pub fn init_ssl(do_ssl: bool)

Allows applications to select which security libraries to initialize.

See PQinitSSL.

§

impl Connection

pub fn db(&self) -> Result<String>

Returns the database name of the connection.

See PQdb.

pub fn user(&self) -> Result<String>

Returns the user name of the connection.

See PQuser.

pub fn pass(&self) -> Result<Option<String>>

Returns the password of the connection.

See PQpass.

pub fn host(&self) -> Result<String>

Returns the server host name of the active connection.

This can be a host name, an IP address, or a directory path if the connection is via Unix socket. (The path case can be distinguished because it will always be an absolute path, beginning with /.)

See PQhost.

pub fn hostaddr(&self) -> Result<String>

Available on crate feature v12 only.

Returns the server IP address of the active connection.

This can be the address that a host name resolved to, or an IP address provided through the hostaddr parameter.

See PQhostaddr.

pub fn port(&self) -> Result<String>

Returns the port of the active connection.

See PQport.

pub fn tty(&self) -> Result<Option<String>>

👎Deprecated: the server no longer pays attention to the TTY setting, but the function remains for backward compatibility.

Returns the debug TTY of the connection.

See PQtty.

pub fn options(&self) -> Result<Option<String>>

Returns the command-line options passed in the connection request.

See PQoptions.

pub fn status(&self) -> Status

Returns the status of the connection.

See PQstatus.

Examples found in repository?
examples/testlibpq4.rs (line 83)
82fn check_prepare_conn(conn: &libpq::Connection, _db_name: &str) {
83    if conn.status() != libpq::connection::Status::Ok {
84        panic!("{:?}", conn.error_message());
85    }
86
87    /* Set always-secure search path, so malicious users can't take control. */
88    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
89    if res.status() != libpq::Status::TuplesOk {
90        panic!("SET failed: {:?}", conn.error_message());
91    }
92}

pub fn transaction_status(&self) -> Status

Returns the current in-transaction status of the server.

See PQtransactionStatus.

pub fn parameter_status(&self, param: &str) -> Result<String>

Looks up a current parameter setting of the server.

See PQparameterStatus.

pub fn protocol_version(&self) -> i32

Interrogates the frontend/backend protocol being used.

See PQprotocolVersion.

pub fn server_version(&self) -> i32

Returns an integer representing the server version.

See PQserverVersion.

pub fn error_message(&self) -> Option<&str>

Returns the error message most recently generated by an operation on the connection.

See PQerrorMessage.

§Implemenatation Notes:

PQerrorMessage returns a localizable string, which depends on the locale settings and is it not guaranteed to be UTF-8 encoded.

Since rust strings are UTF-8 encoded, if the error message cannot be converted to UTF-8, the returned string will not be the actual error message but “PQerrorMessage internal error: the error message is not UTF-8”. You can get the actual error message, by changing your locale settings an UTF-8 compatible one.

Examples found in repository?
examples/testlibpq4.rs (line 84)
82fn check_prepare_conn(conn: &libpq::Connection, _db_name: &str) {
83    if conn.status() != libpq::connection::Status::Ok {
84        panic!("{:?}", conn.error_message());
85    }
86
87    /* Set always-secure search path, so malicious users can't take control. */
88    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
89    if res.status() != libpq::Status::TuplesOk {
90        panic!("SET failed: {:?}", conn.error_message());
91    }
92}
More examples
Hide additional examples
examples/testlo.rs (line 29)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 4 {
11        panic!(
12            "usage: {} database_name in_filename out_filename",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20
21    /*
22     * set up the connection
23     */
24    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
25
26    /* Set always-secure search path, so malicious users can't take control. */
27    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
28    if res.status() != libpq::Status::TuplesOk {
29        panic!("SET failed: {:?}", conn.error_message());
30    }
31
32    conn.exec("begin");
33    println!("importing file \"{in_filename}\" ...");
34    let lobj_oid = libpq::lo::import(&conn, &in_filename);
35
36    println!("\tas large object {lobj_oid}.");
37
38    println!("picking out bytes 1000-2000 of the large object");
39    pickout(&conn, lobj_oid, 1_000, 1_000)?;
40
41    println!("overwriting bytes 1000-2000 of the large object with X's");
42    overwrite(&conn, lobj_oid, 1_000, 1_000)?;
43
44    println!("exporting large object to file \"{out_filename}\" ...");
45    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
46
47    conn.exec("end");
48
49    Ok(())
50}
examples/testlo64.rs (line 30)
7fn main() -> libpq::errors::Result {
8    let mut args = std::env::args();
9
10    if args.len() < 5 {
11        panic!(
12            "usage: {} database_name in_filename out_filename out_filename2",
13            args.next().unwrap()
14        );
15    }
16
17    let database = args.nth(1).unwrap();
18    let in_filename = args.next().unwrap();
19    let out_filename = args.next().unwrap();
20    let out_filename2 = args.next().unwrap();
21
22    /*
23     * set up the connection
24     */
25    let conn = libpq::Connection::set_db(None, None, None, None, Some(&database))?;
26
27    /* Set always-secure search path, so malicious users can't take control. */
28    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
29    if res.status() != libpq::Status::TuplesOk {
30        panic!("SET failed: {:?}", conn.error_message());
31    }
32
33    conn.exec("begin");
34
35    println!("importing file \"{in_filename}\" ...");
36    let lobj_oid = libpq::lo::import(&conn, &in_filename);
37
38    println!("\tas large object {lobj_oid}.");
39
40    println!("picking out bytes 4294967000-4294968000 of the large object");
41    pickout(&conn, lobj_oid, 4_294_967_000, 1_000)?;
42
43    println!("overwriting bytes 4294967000-4294968000 of the large object with X's");
44    overwrite(&conn, lobj_oid, 4_294_967_000, 1_000)?;
45
46    println!("exporting large object to file \"{out_filename}\" ...");
47    libpq::lo::export(&conn, &out_filename, lobj_oid)?;
48
49    println!("truncating to 3294968000 bytes");
50    my_truncate(&conn, lobj_oid, 3_294_968_000)?;
51
52    println!("exporting truncated large object to file \"{out_filename2}\" ...");
53    libpq::lo::export(&conn, &out_filename2, lobj_oid)?;
54
55    conn.exec("end");
56
57    Ok(())
58}
59
60fn pickout(
61    conn: &libpq::Connection,
62    lobj_id: libpq::Oid,
63    start: i64,
64    len: usize,
65) -> libpq::errors::Result {
66    let lobj = libpq::lo::open(conn, lobj_id, libpq::lo::Inv::READ)?;
67
68    lobj.lseek64(start, libpq::lo::Seek::Set)?;
69
70    if lobj.tell64()? != start {
71        panic!("error in lo_tell64: {:?}", conn.error_message());
72    }
73
74    let mut nread = 0;
75
76    while len - nread > 0 {
77        let mut buf = lobj.read(len - nread)?;
78        let nbytes = buf.len();
79        buf.insert(nbytes, '\0');
80        eprint!(">>> {buf}");
81        nread += nbytes;
82        if nbytes == 0 {
83            break; /* no more data? */
84        }
85    }
86    eprintln!();
87
88    Ok(())
89}
examples/testlibpq2.rs (line 47)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}
examples/testlibpq.rs (line 22)
6fn main() -> libpq::errors::Result {
7    /*
8     * If the user supplies a parameter on the command line, use it as the
9     * conninfo string; otherwise default to setting dbname=postgres and using
10     * environment variables or defaults for all other connection parameters.
11     */
12    let conninfo = std::env::args()
13        .nth(1)
14        .unwrap_or_else(|| "dbname = postgres".to_string());
15
16    /* Make a connection to the database */
17    let conn = libpq::Connection::new(&conninfo)?;
18
19    /* Set always-secure search path, so malicious users can't take control. */
20    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
21    if res.status() != libpq::Status::TuplesOk {
22        panic!("SET failed: {:?}", conn.error_message());
23    }
24
25    /*
26     * Our test case here involves using a cursor, for which we must be inside
27     * a transaction block.  We could do the whole thing with a single
28     * PQexec() of "select * from pg_database", but that's too trivial to make
29     * a good example.
30     */
31
32    /* Start a transaction block */
33    let res = conn.exec("BEGIN");
34    if res.status() != libpq::Status::CommandOk {
35        panic!("BEGIN command failed: {:?}", conn.error_message());
36    }
37
38    /*
39     * Fetch rows from pg_database, the system catalog of databases
40     */
41    let res = conn.exec("DECLARE myportal CURSOR FOR select * from pg_database");
42    if res.status() != libpq::Status::CommandOk {
43        panic!("DECLARE CURSOR failed: {:?}", conn.error_message());
44    }
45
46    let res = conn.exec("FETCH ALL in myportal");
47    if res.status() != libpq::Status::TuplesOk {
48        panic!("FETCH ALL failed: {:?}", conn.error_message());
49    }
50
51    /* first, print out the attribute names */
52    let nfields = res.nfields();
53    for i in 0..nfields {
54        print!("{:15}", res.field_name(i)?.unwrap_or_default());
55    }
56    println!("\n");
57
58    /* next, print out the rows */
59    for i in 0..res.ntuples() {
60        for j in 0..nfields {
61            let s = res
62                .value(i, j)
63                .map(|x| String::from_utf8(x.to_vec()).unwrap())
64                .unwrap_or_default();
65            print!("{s:15}");
66        }
67        println!();
68    }
69
70    /* close the portal ... we don't bother to check for errors ... */
71    conn.exec("CLOSE myportal");
72
73    /* end the transaction */
74    conn.exec("END");
75
76    Ok(())
77}
examples/testlibpq3.rs (line 49)
33fn main() -> Result<(), Box<dyn std::error::Error>> {
34    /*
35     * If the user supplies a parameter on the command line, use it as the
36     * conninfo string; otherwise default to setting dbname=postgres and using
37     * environment variables or defaults for all other connection parameters.
38     */
39    let conninfo = std::env::args()
40        .nth(1)
41        .unwrap_or_else(|| "dbname = postgres".to_string());
42
43    /* Make a connection to the database */
44    let conn = libpq::Connection::new(&conninfo)?;
45
46    /* Set always-secure search path, so malicious users can't take control. */
47    let res = conn.exec("SET search_path = testlibpq3");
48    if res.status() != libpq::Status::CommandOk {
49        panic!("SET failed: {:?}", conn.error_message());
50    }
51
52    /*
53     * The point of this program is to illustrate use of PQexecParams() with
54     * out-of-line parameters, as well as binary transmission of data.
55     *
56     * This first example transmits the parameters as text, but receives the
57     * results in binary format.  By using out-of-line parameters we can avoid
58     * a lot of tedious mucking about with quoting and escaping, even though
59     * the data is text.  Notice how we don't have to do anything special with
60     * the quote mark in the parameter value.
61     */
62
63    /* Here is our out-of-line parameter value */
64    let param_values = [Some("joe's place\0".as_bytes())];
65
66    let res = conn.exec_params(
67        "SELECT * FROM test1 WHERE t = $1",
68        &[], /* let the backend deduce param type */
69        param_values.as_slice(),
70        &[],                   /* default to all text params */
71        libpq::Format::Binary, /* ask for binary results */
72    );
73
74    if res.status() != libpq::Status::TuplesOk {
75        panic!("SELECT failed: {:?}", conn.error_message());
76    }
77
78    show_binary_results(&res)?;
79
80    /*
81     * In this second example we transmit an integer parameter in binary form,
82     * and again retrieve the results in binary form.
83     *
84     * Although we tell PQexecParams we are letting the backend deduce
85     * parameter type, we really force the decision by casting the parameter
86     * symbol in the query text.  This is a good safety measure when sending
87     * binary parameters.
88     */
89
90    /* Convert integer value "2" to network byte order */
91    let binary_int_val = htonl(2);
92
93    /* Set up parameter arrays for PQexecParams */
94    let param_values = [Some(binary_int_val.as_slice())];
95    let param_formats = vec![libpq::Format::Binary];
96
97    let res = conn.exec_params(
98        "SELECT * FROM test1 WHERE i = $1::int4",
99        &[], /* let the backend deduce param type */
100        &param_values,
101        &param_formats,
102        libpq::Format::Binary, /* ask for binary results */
103    );
104
105    if res.status() != libpq::Status::TuplesOk {
106        panic!("SELECT failed: {:?}", conn.error_message());
107    }
108
109    show_binary_results(&res)?;
110
111    Ok(())
112}

pub fn socket(&self) -> Result<i32>

Obtains the file descriptor number of the connection socket to the server.

See PQsocket.

Examples found in repository?
examples/testlibpq2.rs (line 61)
32fn main() -> Result<(), Box<dyn std::error::Error>> {
33    /*
34     * If the user supplies a parameter on the command line, use it as the
35     * conninfo string; otherwise default to setting dbname=postgres and using
36     * environment variables or defaults for all other connection parameters.
37     */
38    let conninfo = std::env::args()
39        .nth(1)
40        .unwrap_or_else(|| "dbname = postgres".to_string());
41
42    let conn = libpq::Connection::new(&conninfo)?;
43
44    /* Set always-secure search path, so malicious users can't take control. */
45    let res = conn.exec("SELECT pg_catalog.set_config('search_path', '', false)");
46    if res.status() != libpq::Status::TuplesOk {
47        panic!("SET failed: {:?}", conn.error_message());
48    }
49
50    /*
51     * Issue LISTEN command to enable notifications from the rule's NOTIFY.
52     */
53    let res = conn.exec("LISTEN TBL2");
54    if res.status() != libpq::Status::CommandOk {
55        panic!("LISTEN command failed: {:?}", conn.error_message());
56    }
57
58    /* Quit after four notifies are received. */
59    let mut nnotifies = 0;
60
61    let sock = conn.socket()?;
62
63    let mut poll = mio::Poll::new()?;
64    let mut events = mio::Events::with_capacity(1);
65    poll.registry().register(
66        &mut mio::unix::SourceFd(&sock),
67        mio::Token(0),
68        mio::Interest::READABLE,
69    )?;
70
71    while nnotifies < 4 {
72        /*
73         * Sleep until something happens on the connection.
74         */
75        poll.poll(&mut events, None)?;
76
77        /* Now check for input */
78        conn.consume_input()?;
79        while let Some(notify) = conn.notifies() {
80            eprintln!(
81                "ASYNC NOTIFY of '{}' received from backend PID {}",
82                notify.relname()?,
83                notify.be_pid()
84            );
85            nnotifies += 1;
86            conn.consume_input()?;
87        }
88    }
89
90    eprintln!("Done.");
91
92    Ok(())
93}

pub fn backend_pid(&self) -> u32

Returns the process ID (PID) of the backend process handling this connection.

See PQbackendPID.

pub fn needs_password(&self) -> bool

Returns true if the connection authentication method required a password, but none was available. Returns false if not.

See PQconnectionNeedsPassword.

pub fn used_password(&self) -> bool

Returns true if the connection authentication method used a password. Returns false if not.

See PQconnectionUsedPassword.

pub fn ssl_in_use(&self) -> bool

Returns true if the connection uses SSL, false if not.

See PQsslInUse.

pub fn ssl_attribute(&self, attribute: Attribute) -> Result<Option<String>>

Returns SSL-related information about the connection.

See PQsslAttribute.

pub fn ssl_attribute_names(&self) -> Result<Vec<Attribute>>

Return an array of SSL attribute names available.

See PQsslAttributeNames.

pub unsafe fn ssl_struct(&self, struct_name: &str) -> *const c_void

Return a pointer to an SSL-implementation-specific object describing the connection.

See PQsslStruct.

§Safety

This function returns a void* pointer.

pub unsafe fn ssl(&self) -> *const c_void

Returns the SSL structure used in the connection, or null if SSL is not in use.

See PQgetssl.

§Safety

This function returns a void* pointer.

§

impl Connection

pub fn is_thread_safe() -> bool

Returns the thread safety status of the libpq library.

See PQisthreadsafe.

§

impl Connection

pub fn trace(&self, file: File)

Available on Unix only.

Enables tracing of the client/server communication to a debugging file stream.

See PQtrace.

pub fn untrace(&self)

Available on Unix only.

Disables tracing started by libpq::Connection::trace.

See PQuntrace.

pub fn trace_set_flags(&self, flags: Flags)

Available on crate feature v14 only.

Controls the tracing behavior of client/server communication.

Source§

impl Connection

Source

pub fn encrypt_password( &self, passwd: &str, user: &str, algorithm: Option<&str>, ) -> Result<PqString>

Prepares the encrypted form of a PostgreSQL password.

On success, this method returns PqString.

See PQencryptPasswordConn.

Source

pub fn send_flush_request(&self) -> Result

Available on crate feature v14 only.

Alias for pipeline::flush_request.

Trait Implementations§

Source§

impl Clone for Connection

Source§

fn clone(&self) -> Connection

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Connection

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Send for Connection

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.