pub struct Connection { /* private fields */ }Expand description
Um anexo (attachment) autenticado a um banco de dados.
Implementations§
Source§impl Connection
impl Connection
Sourcepub fn array_desc(
&mut self,
tx: &Transaction,
relation: &str,
field: &str,
) -> Result<ArrayDesc>
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).
Sourcepub fn read_array(
&mut self,
tx: &Transaction,
array_id: u64,
desc: &ArrayDesc,
) -> Result<Vec<Value>>
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.
Sourcepub fn write_array(
&mut self,
tx: &Transaction,
desc: &ArrayDesc,
values: &[Value],
) -> Result<u64>
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
impl Connection
Sourcepub fn create_batch(&mut self, tx: &Transaction, sql: &str) -> Result<Batch>
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).
Sourcepub fn create_batch_with(
&mut self,
tx: &Transaction,
sql: &str,
opts: BatchOptions,
) -> Result<Batch>
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
impl Connection
Sourcepub fn open_blob(&mut self, tx: &Transaction, blob_id: u64) -> Result<Blob>
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).
Sourcepub fn create_blob(&mut self, tx: &Transaction) -> Result<BlobWriter>
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.
Sourcepub fn write_blob(&mut self, tx: &Transaction, data: &[u8]) -> Result<u64>
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§impl Connection
impl Connection
Sourcepub fn connect(config: &ConnectConfig) -> Result<Connection>
pub fn connect(config: &ConnectConfig) -> Result<Connection>
Conecta ao servidor e anexa (attach) a um banco de dados existente.
Examples found in repository?
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}Sourcepub fn create_database(config: &ConnectConfig) -> Result<Connection>
pub fn create_database(config: &ConnectConfig) -> Result<Connection>
Conecta e cria um novo banco de dados, e então anexa (attach) a ele.
Sourcepub fn charset(&self) -> Charset
pub fn charset(&self) -> Charset
O charset da conexão, usado para decodificar texto vindo do servidor.
Sourcepub fn close(self) -> Result<()>
pub fn close(self) -> Result<()>
Desanexa (detach) do banco de dados e fecha o socket.
Examples found in repository?
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}Sourcepub fn ping(&mut self) -> Result<()>
pub fn ping(&mut self) -> Result<()>
Faz um round-trip de op_ping para verificar se a conexão está viva.
Sourcepub fn protocol_version(&self) -> i32
pub fn protocol_version(&self) -> i32
A versão de protocolo negociada (número base, ex.: 18 para FB5).
Examples found in repository?
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}Sourcepub fn supports_batch(&self) -> bool
pub fn supports_batch(&self) -> bool
Se o protocolo negociado suporta as ops de batch (array-DML).
Sourcepub fn supports_fetch_scroll(&self) -> bool
pub fn supports_fetch_scroll(&self) -> bool
Se o protocolo negociado suporta cursores roláveis (scrollable).
Sourcepub fn exec_immediate(
&mut self,
tx: Option<&Transaction>,
sql: &str,
) -> Result<()>
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.
Sourcepub fn is_encrypted(&self) -> bool
pub fn is_encrypted(&self) -> bool
Se a comunicação (wire) está criptografada.
Sourcepub fn is_healthy(&self) -> bool
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
impl Connection
Sourcepub fn listen_events(&mut self, names: &[&str]) -> Result<EventListener>
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
impl Connection
Sourcepub fn prepare(&mut self, tx: &Transaction, sql: &str) -> Result<Statement>
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?
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
impl Connection
Sourcepub fn begin(&mut self) -> Result<Transaction>
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?
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}Sourcepub fn begin_with(
&mut self,
builder: &TransactionBuilder,
) -> Result<Transaction>
pub fn begin_with( &mut self, builder: &TransactionBuilder, ) -> Result<Transaction>
Inicia uma transação com parâmetros explícitos.