-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvertica_query.rs
74 lines (64 loc) · 2.72 KB
/
vertica_query.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! A program executing a query and printing the result as csv to standard out. Requires
//! `anyhow` and `csv` crate.
use anyhow::Error;
use odbc_api::{buffers::TextRowSet, Cursor, Environment, ConnectionOptions, ResultSetMetadata};
use std::io::stdout;
/// Maximum number of rows fetched with one row set. Fetching batches of rows is usually much
/// faster than fetching individual rows.
const BATCH_SIZE: usize = 5000;
fn main() -> Result<(), Error> {
// Write csv to standard out
let out = stdout();
let mut writer = csv::Writer::from_writer(out);
// If you do not do anything fancy it is recommended to have only one Environment in the
// entire process.
let environment = Environment::new()?;
for driver_info in environment.drivers()? {
print!("Driver: ");
println!("{:#?}", driver_info);
}
for data_source in environment.data_sources()? {
print!("Data Source: ");
println!("{:#?}", data_source);
}
// Connect using a DSN. Alternatively we could have used a connection string
let connection = environment.connect(
"Dev1Vertica",
"ro_user",
"password",
ConnectionOptions::default(),
)?;
// Execute a one of query without any parameters.
match connection.execute("SELECT * FROM your_schema.your_table", ())? {
Some(mut cursor) => {
// Write the column names to stdout
let headline : Vec<String> = cursor.column_names()?.collect::<Result<_,_>>()?;
writer.write_record(headline)?;
// Use schema in cursor to initialize a text buffer large enough to hold the largest
// possible strings for each column up to an upper limit of 4KiB.
let mut buffers = TextRowSet::for_cursor(BATCH_SIZE, &mut cursor, Some(4096))?;
// Bind the buffer to the cursor. It is now being filled with every call to fetch.
let mut row_set_cursor = cursor.bind_buffer(&mut buffers)?;
// Iterate over batches
while let Some(batch) = row_set_cursor.fetch()? {
// Within a batch, iterate over every row
for row_index in 0..batch.num_rows() {
// Within a row iterate over every column
let record = (0..batch.num_cols()).map(|col_index| {
batch
.at(col_index, row_index)
.unwrap_or(&[])
});
// Writes row as csv
writer.write_record(record)?;
}
}
}
None => {
eprintln!(
"Query came back empty. No output has been created."
);
}
}
Ok(())
}