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
use crate::describe::Describe;
use crate::error::Error;
use crate::sqlite::connection::explain::explain;
use crate::sqlite::connection::ConnectionState;
use crate::sqlite::statement::VirtualStatement;
use crate::sqlite::type_info::DataType;
use crate::sqlite::{Sqlite, SqliteColumn};
use either::Either;
use std::convert::identity;
pub(super) fn describe(conn: &mut ConnectionState, query: &str) -> Result<Describe<Sqlite>, Error> {
let mut statement = VirtualStatement::new(query, false)?;
let mut columns = Vec::new();
let mut nullable = Vec::new();
let mut num_params = 0;
while let Some(stmt) = statement.prepare_next(&mut conn.handle)? {
num_params += stmt.handle.bind_parameter_count();
let mut stepped = false;
let num = stmt.handle.column_count();
if num == 0 {
continue;
}
columns.reserve(num);
let (fallback, fallback_nullable) = match explain(conn, stmt.handle.sql()) {
Ok(v) => v,
Err(err) => {
log::debug!("describe: explain introspection failed: {}", err);
(vec![], vec![])
}
};
for col in 0..num {
let name = stmt.handle.column_name(col).to_owned();
let type_info = if let Some(ty) = stmt.handle.column_decltype(col) {
ty
} else {
if !stepped && stmt.handle.read_only() {
stepped = true;
let _ = stmt.handle.step();
}
let mut ty = stmt.handle.column_type_info(col);
if ty.0 == DataType::Null {
if let Some(fallback) = fallback.get(col).cloned() {
ty = fallback;
}
}
ty
};
let col_nullable = stmt.handle.column_nullable(col)?;
let exp_nullable = fallback_nullable.get(col).copied().and_then(identity);
nullable.push(exp_nullable.or(col_nullable));
columns.push(SqliteColumn {
name: name.into(),
type_info,
ordinal: col,
});
}
}
Ok(Describe {
columns,
parameters: Some(Either::Right(num_params)),
nullable,
})
}