Skip to main content

Connection

Struct Connection 

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

Um anexo (attachment) autenticado a um banco de dados.

Implementations§

Source§

impl Connection

Source

pub fn array_desc( &mut self, tx: &Transaction, relation: &str, field: &str, ) -> Result<ArrayDesc>

Monta o ArrayDesc de uma coluna ARRAY consultando o catálogo do sistema (RDB$*), exatamente como o fbclient faz antes de uma fatia. relation/field são os nomes como armazenados (normalmente maiúsculas; um ColumnMeta de saída já os traz assim).

Source

pub fn read_array( &mut self, tx: &Transaction, array_id: u64, desc: &ArrayDesc, ) -> Result<Vec<Value>>

Lê todos os elementos de um array (op_get_slice). array_id é o id que veio na coluna (Value::Array); desc descreve o tipo e as dimensões. Devolve um valor por elemento, na ordem em que o servidor os transmite.

Source

pub fn write_array( &mut self, tx: &Transaction, desc: &ArrayDesc, values: &[Value], ) -> Result<u64>

Cria um novo array com values (op_put_slice) e devolve seu id, para usar como Value::Array num INSERT/UPDATE. O número de valores deve bater com desc.element_count().

Source§

impl Connection

Source

pub fn create_batch(&mut self, tx: &Transaction, sql: &str) -> Result<Batch>

Prepara uma instrução e cria um lote (batch) sobre ela com as opções padrão (BatchOptions::default: fail-fast, com contagens por linha). A instrução deve ter parâmetros (?) — cada Batch::add fornece uma linha de valores.

Para continuar após erros por linha e coletá-los todos, use Self::create_batch_with com BatchOptions::new().multierror(true).

Source

pub fn create_batch_with( &mut self, tx: &Transaction, sql: &str, opts: BatchOptions, ) -> Result<Batch>

Como Self::create_batch, mas com BatchOptions explícitas.

Source§

impl Connection

Source

pub fn open_blob(&mut self, tx: &Transaction, blob_id: u64) -> Result<Blob>

Abre um BLOB para leitura pelo seu id (obtido de uma coluna Value::Blob).

Source

pub fn create_blob(&mut self, tx: &Transaction) -> Result<BlobWriter>

Cria um BLOB vazio para escrita (op_create_blob2). Escreva dados com BlobWriter::write e finalize com BlobWriter::close para obter o id do blob. Em caso de erro, chame BlobWriter::cancel.

Source

pub fn write_blob(&mut self, tx: &Transaction, data: &[u8]) -> Result<u64>

Conveniência: cria um BLOB, escreve data integralmente e o fecha, devolvendo o id para usar como parâmetro de coluna BLOB.

Source

pub fn read_blob(&mut self, tx: &Transaction, blob_id: u64) -> Result<Vec<u8>>

Conveniência: abre o BLOB, lê todo o conteúdo e o fecha, devolvendo os bytes. Fecha mesmo se a leitura falhar.

Source§

impl Connection

Source

pub fn connect(config: &ConnectConfig) -> Result<Connection>

Conecta ao servidor e anexa (attach) a um banco de dados existente.

Examples found in repository?
examples/dump.rs (line 25)
11fn main() -> Result<()> {
12    let cfg = ConnectConfig::new()
13        .host(std::env::var("FB_HOST").unwrap_or_else(|_| "127.0.0.1".into()))
14        .port(
15            std::env::var("FB_PORT")
16                .ok()
17                .and_then(|p| p.parse().ok())
18                .unwrap_or(3555),
19        )
20        .database(std::env::var("FB_DB").unwrap_or_else(|_| "employee".into()))
21        .user(std::env::var("FB_USER").unwrap_or_else(|_| "SYSDBA".into()))
22        .password(std::env::var("FB_PASSWORD").expect("set FB_PASSWORD"))
23        .wire_crypt(WireCrypt::Enabled);
24
25    let mut conn = Connection::connect(&cfg)?;
26    println!("conectado: protocolo v{}", conn.protocol_version());
27    let tx = conn.begin()?;
28
29    let sql = "SELECT emp_no, first_name FROM employee WHERE emp_no = 2";
30    let stmt = conn.prepare(&tx, sql)?;
31    println!(
32        "\nstmt_type={} colunas={}",
33        stmt.stmt_type(),
34        stmt.columns().len()
35    );
36    for c in stmt.columns() {
37        println!(
38            "  [{}] name={:?} field={:?} relation={:?} alias={:?} owner={:?} type={} sub={} scale={} len={}",
39            c.index,
40            c.name(),
41            c.field,
42            c.relation,
43            c.alias,
44            c.owner,
45            c.sql_type,
46            c.sub_type,
47            c.scale,
48            c.length
49        );
50    }
51
52    stmt.drop_statement(&mut conn)?;
53    tx.commit(&mut conn)?;
54    conn.close()?;
55    Ok(())
56}
Source

pub fn create_database(config: &ConnectConfig) -> Result<Connection>

Conecta e cria um novo banco de dados, e então anexa (attach) a ele.

Source

pub fn charset(&self) -> Charset

O charset da conexão, usado para decodificar texto vindo do servidor.

Source

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

Desanexa (detach) do banco de dados e fecha o socket.

Examples found in repository?
examples/dump.rs (line 54)
11fn main() -> Result<()> {
12    let cfg = ConnectConfig::new()
13        .host(std::env::var("FB_HOST").unwrap_or_else(|_| "127.0.0.1".into()))
14        .port(
15            std::env::var("FB_PORT")
16                .ok()
17                .and_then(|p| p.parse().ok())
18                .unwrap_or(3555),
19        )
20        .database(std::env::var("FB_DB").unwrap_or_else(|_| "employee".into()))
21        .user(std::env::var("FB_USER").unwrap_or_else(|_| "SYSDBA".into()))
22        .password(std::env::var("FB_PASSWORD").expect("set FB_PASSWORD"))
23        .wire_crypt(WireCrypt::Enabled);
24
25    let mut conn = Connection::connect(&cfg)?;
26    println!("conectado: protocolo v{}", conn.protocol_version());
27    let tx = conn.begin()?;
28
29    let sql = "SELECT emp_no, first_name FROM employee WHERE emp_no = 2";
30    let stmt = conn.prepare(&tx, sql)?;
31    println!(
32        "\nstmt_type={} colunas={}",
33        stmt.stmt_type(),
34        stmt.columns().len()
35    );
36    for c in stmt.columns() {
37        println!(
38            "  [{}] name={:?} field={:?} relation={:?} alias={:?} owner={:?} type={} sub={} scale={} len={}",
39            c.index,
40            c.name(),
41            c.field,
42            c.relation,
43            c.alias,
44            c.owner,
45            c.sql_type,
46            c.sub_type,
47            c.scale,
48            c.length
49        );
50    }
51
52    stmt.drop_statement(&mut conn)?;
53    tx.commit(&mut conn)?;
54    conn.close()?;
55    Ok(())
56}
Source

pub fn ping(&mut self) -> Result<()>

Faz um round-trip de op_ping para verificar se a conexão está viva.

Source

pub fn protocol_version(&self) -> i32

A versão de protocolo negociada (número base, ex.: 18 para FB5).

Examples found in repository?
examples/dump.rs (line 26)
11fn main() -> Result<()> {
12    let cfg = ConnectConfig::new()
13        .host(std::env::var("FB_HOST").unwrap_or_else(|_| "127.0.0.1".into()))
14        .port(
15            std::env::var("FB_PORT")
16                .ok()
17                .and_then(|p| p.parse().ok())
18                .unwrap_or(3555),
19        )
20        .database(std::env::var("FB_DB").unwrap_or_else(|_| "employee".into()))
21        .user(std::env::var("FB_USER").unwrap_or_else(|_| "SYSDBA".into()))
22        .password(std::env::var("FB_PASSWORD").expect("set FB_PASSWORD"))
23        .wire_crypt(WireCrypt::Enabled);
24
25    let mut conn = Connection::connect(&cfg)?;
26    println!("conectado: protocolo v{}", conn.protocol_version());
27    let tx = conn.begin()?;
28
29    let sql = "SELECT emp_no, first_name FROM employee WHERE emp_no = 2";
30    let stmt = conn.prepare(&tx, sql)?;
31    println!(
32        "\nstmt_type={} colunas={}",
33        stmt.stmt_type(),
34        stmt.columns().len()
35    );
36    for c in stmt.columns() {
37        println!(
38            "  [{}] name={:?} field={:?} relation={:?} alias={:?} owner={:?} type={} sub={} scale={} len={}",
39            c.index,
40            c.name(),
41            c.field,
42            c.relation,
43            c.alias,
44            c.owner,
45            c.sql_type,
46            c.sub_type,
47            c.scale,
48            c.length
49        );
50    }
51
52    stmt.drop_statement(&mut conn)?;
53    tx.commit(&mut conn)?;
54    conn.close()?;
55    Ok(())
56}
Source

pub fn supports_batch(&self) -> bool

Se o protocolo negociado suporta as ops de batch (array-DML).

Source

pub fn supports_fetch_scroll(&self) -> bool

Se o protocolo negociado suporta cursores roláveis (scrollable).

Source

pub fn exec_immediate( &mut self, tx: Option<&Transaction>, sql: &str, ) -> Result<()>

Executa um comando SQL sem prepare prévio (op_exec_immediate). Use para DDL (CREATE/ALTER/DROP TABLE, índices, procedures…) ou DML sem retorno de linhas.

Passe None para deixar o driver criar e fazer commit de uma transação implícita (necessário para DDL autocommit). Passe Some(&tx) para executar dentro de uma transação existente.

Source

pub fn is_encrypted(&self) -> bool

Se a comunicação (wire) está criptografada.

Source

pub fn is_healthy(&self) -> bool

Se a conexão ainda está sã (sem erro de I/O nem desync de protocolo). O crate::Pool usa isto para descartar conexões com falha em vez de devolvê-las ao conjunto de ociosas.

Source§

impl Connection

Source

pub fn listen_events(&mut self, names: &[&str]) -> Result<EventListener>

Registra interesse nos eventos nomeados e abre o canal auxiliar por onde o servidor empurra as notificações. Use EventListener::wait para aguardar.

let mut ev = conn.listen_events(&["minha_tabela_mudou"])?;
let disparados = ev.wait(&mut conn)?;   // bloqueia até um POST
ev.cancel(&mut conn)?;
Source§

impl Connection

Source

pub fn prepare(&mut self, tx: &Transaction, sql: &str) -> Result<Statement>

Prepara uma instrução SQL dentro da transação informada.

Examples found in repository?
examples/dump.rs (line 30)
11fn main() -> Result<()> {
12    let cfg = ConnectConfig::new()
13        .host(std::env::var("FB_HOST").unwrap_or_else(|_| "127.0.0.1".into()))
14        .port(
15            std::env::var("FB_PORT")
16                .ok()
17                .and_then(|p| p.parse().ok())
18                .unwrap_or(3555),
19        )
20        .database(std::env::var("FB_DB").unwrap_or_else(|_| "employee".into()))
21        .user(std::env::var("FB_USER").unwrap_or_else(|_| "SYSDBA".into()))
22        .password(std::env::var("FB_PASSWORD").expect("set FB_PASSWORD"))
23        .wire_crypt(WireCrypt::Enabled);
24
25    let mut conn = Connection::connect(&cfg)?;
26    println!("conectado: protocolo v{}", conn.protocol_version());
27    let tx = conn.begin()?;
28
29    let sql = "SELECT emp_no, first_name FROM employee WHERE emp_no = 2";
30    let stmt = conn.prepare(&tx, sql)?;
31    println!(
32        "\nstmt_type={} colunas={}",
33        stmt.stmt_type(),
34        stmt.columns().len()
35    );
36    for c in stmt.columns() {
37        println!(
38            "  [{}] name={:?} field={:?} relation={:?} alias={:?} owner={:?} type={} sub={} scale={} len={}",
39            c.index,
40            c.name(),
41            c.field,
42            c.relation,
43            c.alias,
44            c.owner,
45            c.sql_type,
46            c.sub_type,
47            c.scale,
48            c.length
49        );
50    }
51
52    stmt.drop_statement(&mut conn)?;
53    tx.commit(&mut conn)?;
54    conn.close()?;
55    Ok(())
56}
Source§

impl Connection

Source

pub fn begin(&mut self) -> Result<Transaction>

Inicia uma transação com parâmetros padrão (snapshot, leitura e escrita, wait).

Examples found in repository?
examples/dump.rs (line 27)
11fn main() -> Result<()> {
12    let cfg = ConnectConfig::new()
13        .host(std::env::var("FB_HOST").unwrap_or_else(|_| "127.0.0.1".into()))
14        .port(
15            std::env::var("FB_PORT")
16                .ok()
17                .and_then(|p| p.parse().ok())
18                .unwrap_or(3555),
19        )
20        .database(std::env::var("FB_DB").unwrap_or_else(|_| "employee".into()))
21        .user(std::env::var("FB_USER").unwrap_or_else(|_| "SYSDBA".into()))
22        .password(std::env::var("FB_PASSWORD").expect("set FB_PASSWORD"))
23        .wire_crypt(WireCrypt::Enabled);
24
25    let mut conn = Connection::connect(&cfg)?;
26    println!("conectado: protocolo v{}", conn.protocol_version());
27    let tx = conn.begin()?;
28
29    let sql = "SELECT emp_no, first_name FROM employee WHERE emp_no = 2";
30    let stmt = conn.prepare(&tx, sql)?;
31    println!(
32        "\nstmt_type={} colunas={}",
33        stmt.stmt_type(),
34        stmt.columns().len()
35    );
36    for c in stmt.columns() {
37        println!(
38            "  [{}] name={:?} field={:?} relation={:?} alias={:?} owner={:?} type={} sub={} scale={} len={}",
39            c.index,
40            c.name(),
41            c.field,
42            c.relation,
43            c.alias,
44            c.owner,
45            c.sql_type,
46            c.sub_type,
47            c.scale,
48            c.length
49        );
50    }
51
52    stmt.drop_statement(&mut conn)?;
53    tx.commit(&mut conn)?;
54    conn.close()?;
55    Ok(())
56}
Source

pub fn begin_with( &mut self, builder: &TransactionBuilder, ) -> Result<Transaction>

Inicia uma transação com parâmetros explícitos.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
Source§

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

Source§

fn vzip(self) -> V