Skip to content

Commit cb3ff28

Browse files
marshoepialmarshoepial
and
marshoepial
authored
Keep track of column typing in SQLite EXPLAIN parsing (#1323)
* NewRowid, Column opcodes, better pointer handling * Implement tracking of column typing on sqlite explain parser * fmt for sqlite column typing for explain parsing Co-authored-by: marshoepial <[email protected]>
1 parent 8bcac03 commit cb3ff28

File tree

2 files changed

+112
-19
lines changed

2 files changed

+112
-19
lines changed

sqlx-core/src/sqlite/connection/explain.rs

Lines changed: 97 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ const SQLITE_AFF_REAL: u8 = 0x45; /* 'E' */
1717
const OP_INIT: &str = "Init";
1818
const OP_GOTO: &str = "Goto";
1919
const OP_COLUMN: &str = "Column";
20+
const OP_MAKE_RECORD: &str = "MakeRecord";
21+
const OP_INSERT: &str = "Insert";
22+
const OP_IDX_INSERT: &str = "IdxInsert";
23+
const OP_OPEN_READ: &str = "OpenRead";
24+
const OP_OPEN_WRITE: &str = "OpenWrite";
25+
const OP_OPEN_EPHEMERAL: &str = "OpenEphemeral";
26+
const OP_OPEN_AUTOINDEX: &str = "OpenAutoindex";
2027
const OP_AGG_STEP: &str = "AggStep";
2128
const OP_FUNCTION: &str = "Function";
2229
const OP_MOVE: &str = "Move";
@@ -34,6 +41,7 @@ const OP_BLOB: &str = "Blob";
3441
const OP_VARIABLE: &str = "Variable";
3542
const OP_COUNT: &str = "Count";
3643
const OP_ROWID: &str = "Rowid";
44+
const OP_NEWROWID: &str = "NewRowid";
3745
const OP_OR: &str = "Or";
3846
const OP_AND: &str = "And";
3947
const OP_BIT_AND: &str = "BitAnd";
@@ -48,6 +56,21 @@ const OP_REMAINDER: &str = "Remainder";
4856
const OP_CONCAT: &str = "Concat";
4957
const OP_RESULT_ROW: &str = "ResultRow";
5058

59+
#[derive(Debug, Clone, Eq, PartialEq)]
60+
enum RegDataType {
61+
Single(DataType),
62+
Record(Vec<DataType>),
63+
}
64+
65+
impl RegDataType {
66+
fn map_to_datatype(self) -> DataType {
67+
match self {
68+
RegDataType::Single(d) => d,
69+
RegDataType::Record(_) => DataType::Null, //If we're trying to coerce to a regular Datatype, we can assume a Record is invalid for the context
70+
}
71+
}
72+
}
73+
5174
#[allow(clippy::wildcard_in_or_patterns)]
5275
fn affinity_to_type(affinity: u8) -> DataType {
5376
match affinity {
@@ -73,13 +96,19 @@ fn opcode_to_type(op: &str) -> DataType {
7396
}
7497
}
7598

99+
// Opcode Reference: https://sqlite.org/opcode.html
76100
pub(super) async fn explain(
77101
conn: &mut SqliteConnection,
78102
query: &str,
79103
) -> Result<(Vec<SqliteTypeInfo>, Vec<Option<bool>>), Error> {
80-
let mut r = HashMap::<i64, DataType>::with_capacity(6);
104+
// Registers
105+
let mut r = HashMap::<i64, RegDataType>::with_capacity(6);
106+
// Map between pointer and register
81107
let mut r_cursor = HashMap::<i64, Vec<i64>>::with_capacity(6);
108+
// Rows that pointers point to
109+
let mut p = HashMap::<i64, HashMap<i64, DataType>>::with_capacity(6);
82110

111+
// Nullable columns
83112
let mut n = HashMap::<i64, bool>::with_capacity(6);
84113

85114
let program =
@@ -119,15 +148,52 @@ pub(super) async fn explain(
119148
}
120149

121150
OP_COLUMN => {
122-
r_cursor.entry(p1).or_default().push(p3);
151+
//Get the row stored at p1, or NULL; get the column stored at p2, or NULL
152+
if let Some(record) = p.get(&p1) {
153+
if let Some(col) = record.get(&p2) {
154+
// insert into p3 the datatype of the col
155+
r.insert(p3, RegDataType::Single(*col));
156+
// map between pointer p1 and register p3
157+
r_cursor.entry(p1).or_default().push(p3);
158+
} else {
159+
r.insert(p3, RegDataType::Single(DataType::Null));
160+
}
161+
} else {
162+
r.insert(p3, RegDataType::Single(DataType::Null));
163+
}
164+
}
165+
166+
OP_MAKE_RECORD => {
167+
// p3 = Record([p1 .. p1 + p2])
168+
let mut record = Vec::with_capacity(p2 as usize);
169+
for reg in p1..p1 + p2 {
170+
record.push(
171+
r.get(&reg)
172+
.map(|d| d.clone().map_to_datatype())
173+
.unwrap_or(DataType::Null),
174+
);
175+
}
176+
r.insert(p3, RegDataType::Record(record));
177+
}
178+
179+
OP_INSERT | OP_IDX_INSERT => {
180+
if let Some(RegDataType::Record(record)) = r.get(&p2) {
181+
if let Some(row) = p.get_mut(&p1) {
182+
// Insert the record into wherever pointer p1 is
183+
*row = (0..).zip(record.iter().copied()).collect();
184+
}
185+
}
186+
//Noop if the register p2 isn't a record, or if pointer p1 does not exist
187+
}
123188

124-
// r[p3] = <value of column>
125-
r.insert(p3, DataType::Null);
189+
OP_OPEN_READ | OP_OPEN_WRITE | OP_OPEN_EPHEMERAL | OP_OPEN_AUTOINDEX => {
190+
//Create a new pointer which is referenced by p1
191+
p.insert(p1, HashMap::with_capacity(6));
126192
}
127193

128194
OP_VARIABLE => {
129195
// r[p2] = <value of variable>
130-
r.insert(p2, DataType::Null);
196+
r.insert(p2, RegDataType::Single(DataType::Null));
131197
n.insert(p3, true);
132198
}
133199

@@ -136,7 +202,7 @@ pub(super) async fn explain(
136202
match from_utf8(p4).map_err(Error::protocol)? {
137203
"last_insert_rowid(0)" => {
138204
// last_insert_rowid() -> INTEGER
139-
r.insert(p3, DataType::Int64);
205+
r.insert(p3, RegDataType::Single(DataType::Int64));
140206
n.insert(p3, n.get(&p3).copied().unwrap_or(false));
141207
}
142208

@@ -145,9 +211,9 @@ pub(super) async fn explain(
145211
}
146212

147213
OP_NULL_ROW => {
148-
// all values of cursor X are potentially nullable
149-
for column in &r_cursor[&p1] {
150-
n.insert(*column, true);
214+
// all registers that map to cursor X are potentially nullable
215+
for register in &r_cursor[&p1] {
216+
n.insert(*register, true);
151217
}
152218
}
153219

@@ -156,9 +222,9 @@ pub(super) async fn explain(
156222

157223
if p4.starts_with("count(") {
158224
// count(_) -> INTEGER
159-
r.insert(p3, DataType::Int64);
225+
r.insert(p3, RegDataType::Single(DataType::Int64));
160226
n.insert(p3, n.get(&p3).copied().unwrap_or(false));
161-
} else if let Some(v) = r.get(&p2).copied() {
227+
} else if let Some(v) = r.get(&p2).cloned() {
162228
// r[p3] = AGG ( r[p2] )
163229
r.insert(p3, v);
164230
let val = n.get(&p2).copied().unwrap_or(true);
@@ -169,13 +235,13 @@ pub(super) async fn explain(
169235
OP_CAST => {
170236
// affinity(r[p1])
171237
if let Some(v) = r.get_mut(&p1) {
172-
*v = affinity_to_type(p2 as u8);
238+
*v = RegDataType::Single(affinity_to_type(p2 as u8));
173239
}
174240
}
175241

176242
OP_COPY | OP_MOVE | OP_SCOPY | OP_INT_COPY => {
177243
// r[p2] = r[p1]
178-
if let Some(v) = r.get(&p1).copied() {
244+
if let Some(v) = r.get(&p1).cloned() {
179245
r.insert(p2, v);
180246

181247
if let Some(null) = n.get(&p1).copied() {
@@ -184,15 +250,16 @@ pub(super) async fn explain(
184250
}
185251
}
186252

187-
OP_OR | OP_AND | OP_BLOB | OP_COUNT | OP_REAL | OP_STRING8 | OP_INTEGER | OP_ROWID => {
253+
OP_OR | OP_AND | OP_BLOB | OP_COUNT | OP_REAL | OP_STRING8 | OP_INTEGER | OP_ROWID
254+
| OP_NEWROWID => {
188255
// r[p2] = <value of constant>
189-
r.insert(p2, opcode_to_type(&opcode));
256+
r.insert(p2, RegDataType::Single(opcode_to_type(&opcode)));
190257
n.insert(p2, n.get(&p2).copied().unwrap_or(false));
191258
}
192259

193260
OP_NOT => {
194261
// r[p2] = NOT r[p1]
195-
if let Some(a) = r.get(&p1).copied() {
262+
if let Some(a) = r.get(&p1).cloned() {
196263
r.insert(p2, a);
197264
let val = n.get(&p1).copied().unwrap_or(true);
198265
n.insert(p2, val);
@@ -202,9 +269,16 @@ pub(super) async fn explain(
202269
OP_BIT_AND | OP_BIT_OR | OP_SHIFT_LEFT | OP_SHIFT_RIGHT | OP_ADD | OP_SUBTRACT
203270
| OP_MULTIPLY | OP_DIVIDE | OP_REMAINDER | OP_CONCAT => {
204271
// r[p3] = r[p1] + r[p2]
205-
match (r.get(&p1).copied(), r.get(&p2).copied()) {
272+
match (r.get(&p1).cloned(), r.get(&p2).cloned()) {
206273
(Some(a), Some(b)) => {
207-
r.insert(p3, if matches!(a, DataType::Null) { b } else { a });
274+
r.insert(
275+
p3,
276+
if matches!(a, RegDataType::Single(DataType::Null)) {
277+
b
278+
} else {
279+
a
280+
},
281+
);
208282
}
209283

210284
(Some(v), None) => {
@@ -252,7 +326,11 @@ pub(super) async fn explain(
252326

253327
if let Some(result) = result {
254328
for i in result {
255-
output.push(SqliteTypeInfo(r.remove(&i).unwrap_or(DataType::Null)));
329+
output.push(SqliteTypeInfo(
330+
r.remove(&i)
331+
.map(|d| d.map_to_datatype())
332+
.unwrap_or(DataType::Null),
333+
));
256334
nullable.push(n.remove(&i));
257335
}
258336
}

tests/sqlite/describe.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,21 @@ async fn it_describes_insert_with_read_only() -> anyhow::Result<()> {
171171
Ok(())
172172
}
173173

174+
#[sqlx_macros::test]
175+
async fn it_describes_insert_with_returning() -> anyhow::Result<()> {
176+
let mut conn = new::<Sqlite>().await?;
177+
178+
let d = conn
179+
.describe("INSERT INTO tweet (id, text) VALUES (2, 'Hello') RETURNING *")
180+
.await?;
181+
182+
assert_eq!(d.columns().len(), 4);
183+
assert_eq!(d.column(0).type_info().name(), "INTEGER");
184+
assert_eq!(d.column(1).type_info().name(), "TEXT");
185+
186+
Ok(())
187+
}
188+
174189
#[sqlx_macros::test]
175190
async fn it_describes_bad_statement() -> anyhow::Result<()> {
176191
let mut conn = new::<Sqlite>().await?;

0 commit comments

Comments
 (0)