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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use crate::executor::execute::ExecResult;
use crate::executor::query::QueryResult;
use crate::executor::statement::StatementInput;
use crate::executor::table::TableDescResult;
use crate::executor::SupportDatabase;
use crate::extension::odbc::OdbcColumn;
use crate::{Convert, TryConvert};
use dameng_helper::DmAdapter;
use either::Either;
use odbc_api::buffers::{AnySlice, BufferDescription, ColumnarAnyBuffer};
use odbc_api::handles::StatementImpl;
use odbc_api::{
ColumnDescription, Connection, Cursor, CursorImpl, ParameterCollectionRef, ResultSetMetadata,
};
use std::ops::IndexMut;
pub trait ConnectionTrait {
fn execute<S>(&self, stmt: S) -> anyhow::Result<ExecResult>
where
S: StatementInput;
fn query<S>(&self, stmt: S) -> anyhow::Result<QueryResult>
where
S: StatementInput;
fn show_table(&self, table_name: Vec<String>) -> anyhow::Result<TableDescResult>;
fn begin(&self) -> anyhow::Result<()>;
fn finish(&self) -> anyhow::Result<()>;
fn commit(&self) -> anyhow::Result<()>;
fn rollback(&self) -> anyhow::Result<()>;
}
#[allow(missing_debug_implementations)]
pub struct OdbcDbConnection<'a> {
pub conn: Connection<'a>,
pub options: Options,
}
#[derive(Debug)]
pub struct Options {
pub database: SupportDatabase,
pub max_batch_size: usize,
pub max_str_len: usize,
pub max_binary_len: usize,
}
impl Options {
pub const MAX_BATCH_SIZE: usize = 1 << 8;
pub const MAX_STR_LEN: usize = 1024 * 1024;
pub const MAX_BINARY_LEN: usize = 1024 * 1024;
pub fn new(database: SupportDatabase) -> Self {
Options {
database,
max_batch_size: Self::MAX_BATCH_SIZE,
max_str_len: Self::MAX_STR_LEN,
max_binary_len: Self::MAX_BINARY_LEN,
}
}
fn check(mut self) -> Self {
if self.max_batch_size == 0 {
self.max_str_len = Self::MAX_BATCH_SIZE
}
if self.max_str_len == 0 {
self.max_str_len = Self::MAX_STR_LEN
}
if self.max_binary_len == 0 {
self.max_binary_len = Self::MAX_BINARY_LEN
}
self
}
}
impl<'a> ConnectionTrait for OdbcDbConnection<'a> {
fn execute<S>(&self, stmt: S) -> anyhow::Result<ExecResult>
where
S: StatementInput,
{
let sql = stmt.to_sql().to_string();
match stmt.try_convert().unwrap() {
Either::Left(params) => self.exec_result(sql, ¶ms[..]),
Either::Right(()) => self.exec_result(sql, ()),
}
}
fn query<S>(&self, stmt: S) -> anyhow::Result<QueryResult>
where
S: StatementInput,
{
let sql = stmt.to_sql().to_string();
match stmt.try_convert().unwrap() {
Either::Left(params) => self.query_result(&sql, ¶ms[..]),
Either::Right(()) => self.query_result(&sql, ()),
}
}
fn show_table(&self, table_name: Vec<String>) -> anyhow::Result<TableDescResult> {
self.table_desc(table_name)
}
fn begin(&self) -> anyhow::Result<()> {
Ok(self.conn.set_autocommit(false)?)
}
fn finish(&self) -> anyhow::Result<()> {
self.conn.set_autocommit(true)?;
Ok(())
}
fn commit(&self) -> anyhow::Result<()> {
self.conn.commit()?;
Ok(())
}
fn rollback(&self) -> anyhow::Result<()> {
self.conn.rollback()?;
Ok(())
}
}
impl<'a> OdbcDbConnection<'a> {
pub fn new(conn: Connection<'a>, options: Options) -> anyhow::Result<Self> {
let options = options.check();
let connection = Self { conn, options };
Ok(connection)
}
fn exec_result<S: Into<String>>(
&self,
sql: S,
params: impl ParameterCollectionRef,
) -> anyhow::Result<ExecResult> {
let mut stmt = self.conn.preallocate()?;
stmt.execute(&sql.into(), params)?;
let row_op = stmt.row_count()?;
let result = row_op
.map(|r| ExecResult { rows_affected: r })
.unwrap_or_default();
Ok(result)
}
fn query_result(
&self,
sql: &str,
params: impl ParameterCollectionRef,
) -> anyhow::Result<QueryResult> {
let mut cursor = self
.conn
.execute(sql, params)?
.ok_or_else(|| anyhow!("query error"))?;
let mut query_result = Self::get_cursor_columns(&mut cursor)?;
debug!("columns:{:?}", query_result.columns);
let descs = query_result.columns.iter().map(|c| {
<(&OdbcColumn, &Options) as TryConvert<BufferDescription>>::try_convert((
c,
&self.options,
))
.unwrap()
});
let row_set_buffer =
ColumnarAnyBuffer::try_from_description(self.options.max_batch_size, descs).unwrap();
let mut row_set_cursor = cursor.bind_buffer(row_set_buffer).unwrap();
let mut total_row = vec![];
while let Some(row_set) = row_set_cursor.fetch()? {
for index in 0..query_result.columns.len() {
let column_view: AnySlice = row_set.column(index);
let column_types: Vec<_> = column_view.convert();
if index == 0 {
for c in column_types.into_iter() {
total_row.push(vec![c]);
}
} else {
for (col_index, c) in column_types.into_iter().enumerate() {
let row = total_row.index_mut(col_index);
row.push(c)
}
}
}
}
query_result.data = total_row;
Ok(query_result)
}
fn get_cursor_columns(cursor: &mut CursorImpl<StatementImpl>) -> anyhow::Result<QueryResult> {
let mut query_result = QueryResult::default();
for index in 0..cursor.num_result_cols()?.try_into()? {
let mut column_description = ColumnDescription::default();
cursor.describe_col(index + 1, &mut column_description)?;
let column = OdbcColumn::new(
column_description.name_to_string()?,
column_description.data_type,
column_description.could_be_nullable(),
);
query_result.columns.push(column);
}
Ok(query_result)
}
fn table_desc(&self, table_names: Vec<String>) -> anyhow::Result<TableDescResult> {
let db = &self.options.database;
match db {
SupportDatabase::Dameng => {
let sql = CursorImpl::get_table_sql(table_names);
let cursor = self
.conn
.execute(&sql, ())?
.ok_or_else(|| anyhow!("query error"))?;
cursor.get_table_desc()
}
_ => {
bail!("current not support database:{:?}", db)
}
}
}
}