Repository navigation
Expand file tree
/
Copy pathcursor.rs
More file actions
193 lines (157 loc) · 6.02 KB
/
Copy pathcursor.rs
File metadata and controls
193 lines (157 loc) · 6.02 KB
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
use std::collections::HashMap;
use std::sync::Arc;
use futures_core::future::BoxFuture;
use crate::connection::ConnectionSource;
use crate::cursor::Cursor;
use crate::executor::Execute;
use crate::pool::Pool;
use crate::postgres::protocol::{
DataRow, Message, ReadyForQuery, RowDescription, StatementId, TypeFormat,
};
use crate::postgres::{PgArguments, PgConnection, PgRow, Postgres};
pub struct PgCursor<'c, 'q> {
source: ConnectionSource<'c, PgConnection>,
query: Option<(&'q str, Option<PgArguments>)>,
columns: Arc<HashMap<Box<str>, usize>>,
formats: Arc<[TypeFormat]>,
}
impl<'c, 'q> Cursor<'c, 'q> for PgCursor<'c, 'q> {
type Database = Postgres;
fn from_pool<E>(pool: &Pool<PgConnection>, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Postgres>,
{
Self {
source: ConnectionSource::Pool(pool.clone()),
columns: Arc::default(),
formats: Arc::new([] as [TypeFormat; 0]),
query: Some(query.into_parts()),
}
}
fn from_connection<E>(conn: &'c mut PgConnection, query: E) -> Self
where
Self: Sized,
E: Execute<'q, Postgres>,
{
Self {
source: ConnectionSource::Connection(conn.into()),
columns: Arc::default(),
formats: Arc::new([] as [TypeFormat; 0]),
query: Some(query.into_parts()),
}
}
fn next(&mut self) -> BoxFuture<crate::Result<Option<PgRow<'_>>>> {
Box::pin(next(self))
}
}
fn parse_row_description(rd: RowDescription) -> (HashMap<Box<str>, usize>, Vec<TypeFormat>) {
let mut columns = HashMap::new();
let mut formats = Vec::new();
columns.reserve(rd.fields.len());
formats.reserve(rd.fields.len());
for (index, field) in rd.fields.iter().enumerate() {
if let Some(name) = &field.name {
columns.insert(name.clone(), index);
}
formats.push(field.type_format);
}
(columns, formats)
}
// Used to describe the incoming results
// We store the column map in an Arc and share it among all rows
async fn expect_desc(
conn: &mut PgConnection,
) -> crate::Result<(HashMap<Box<str>, usize>, Vec<TypeFormat>)> {
let description: Option<_> = loop {
match conn.stream.read().await? {
Message::ParseComplete | Message::BindComplete => {}
Message::RowDescription => {
break Some(RowDescription::read(conn.stream.buffer())?);
}
Message::NoData => {
break None;
}
message => {
return Err(
protocol_err!("next/describe: unexpected message: {:?}", message).into(),
);
}
}
};
Ok(description.map(parse_row_description).unwrap_or_default())
}
// A form of describe that uses the statement cache
async fn get_or_describe(
conn: &mut PgConnection,
statement: StatementId,
) -> crate::Result<(Arc<HashMap<Box<str>, usize>>, Arc<[TypeFormat]>)> {
if !conn.cache_statement_columns.contains_key(&statement)
|| !conn.cache_statement_formats.contains_key(&statement)
{
let (columns, formats) = expect_desc(conn).await?;
conn.cache_statement_columns
.insert(statement, Arc::new(columns));
conn.cache_statement_formats
.insert(statement, Arc::from(formats));
}
Ok((
Arc::clone(&conn.cache_statement_columns[&statement]),
Arc::clone(&conn.cache_statement_formats[&statement]),
))
}
async fn next<'a, 'c: 'a, 'q: 'a>(
cursor: &'a mut PgCursor<'c, 'q>,
) -> crate::Result<Option<PgRow<'a>>> {
let mut conn = cursor.source.resolve().await?;
// The first time [next] is called we need to actually execute our
// contained query. We guard against this happening on _all_ next calls
// by using [Option::take] which replaces the potential value in the Option with `None
if let Some((query, arguments)) = cursor.query.take() {
let statement = conn.run(query, arguments).await?;
// If there is a statement ID, this is a non-simple or prepared query
if let Some(statement) = statement {
// A prepared statement will re-use the previous column map if
// this query has been executed before
let (columns, formats) = get_or_describe(&mut *conn, statement).await?;
cursor.columns = columns;
cursor.formats = formats;
}
// A non-prepared query must be described each time
// We wait until we hit a RowDescription
}
loop {
match conn.stream.read().await? {
// Indicates that a phase of the extended query flow has completed
// We as SQLx don't generally care as long as it is happening
Message::ParseComplete | Message::BindComplete => {}
// Indicates that _a_ query has finished executing
Message::CommandComplete => {}
// Indicates that all queries have finished executing
Message::ReadyForQuery => {
// TODO: How should we handle an ERROR status form ReadyForQuery
let _ready = ReadyForQuery::read(conn.stream.buffer())?;
conn.is_ready = true;
break;
}
Message::RowDescription => {
let rd = RowDescription::read(conn.stream.buffer())?;
let (columns, formats) = parse_row_description(rd);
cursor.columns = Arc::new(columns);
cursor.formats = Arc::from(formats);
}
Message::DataRow => {
let data = DataRow::read(conn.stream.buffer(), &mut conn.current_row_values)?;
return Ok(Some(PgRow {
columns: Arc::clone(&cursor.columns),
formats: Arc::clone(&cursor.formats),
data,
}));
}
message => {
return Err(protocol_err!("next: unexpected message: {:?}", message).into());
}
}
}
Ok(None)
}