forked from databendlabs/databend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.rs
More file actions
236 lines (214 loc) · 7.38 KB
/
Copy pathexecutor.rs
File metadata and controls
236 lines (214 loc) · 7.38 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
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
236
// Copyright 2021 Datafuse Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use databend_common_ast::Span;
use databend_common_ast::ast::Expr;
use databend_common_exception::ErrorCode;
use databend_common_exception::Result;
use crate::ir::ColumnAccess;
use crate::ir::IterRef;
use crate::ir::LabelRef;
use crate::ir::ScriptIR;
use crate::ir::SetRef;
use crate::ir::VarRef;
pub trait Client {
type Var: Clone;
type Set: Clone;
#[allow(async_fn_in_trait)]
async fn query(&self, query: &str) -> Result<Self::Set>;
fn var_to_ast(&self, scalar: &Self::Var) -> Result<Expr>;
fn read_from_set(&self, block: &Self::Set, row: usize, col: &ColumnAccess)
-> Result<Self::Var>;
fn num_rows(&self, block: &Self::Set) -> usize;
fn is_true(&self, scalar: &Self::Var) -> Result<bool>;
fn format_error(&self, value: &Self::Var) -> Result<String>;
}
#[derive(Debug, Clone)]
pub enum ReturnValue<C: Client> {
Var(C::Var),
Set(C::Set),
}
#[derive(Debug)]
struct Cursor {
set: SetRef,
row: usize,
len: usize,
}
#[derive(Debug)]
pub struct Executor<C: Client> {
span: Span,
client: C,
code: Vec<ScriptIR>,
vars: HashMap<VarRef, C::Var>,
sets: HashMap<SetRef, C::Set>,
iters: HashMap<IterRef, Cursor>,
label_to_pc: HashMap<LabelRef, usize>,
return_value: Option<ReturnValue<C>>,
pc: usize,
}
impl<C: Client> Executor<C> {
pub fn load(span: Span, client: C, code: Vec<ScriptIR>) -> Self {
assert!(!code.is_empty());
let mut label_to_pc = HashMap::new();
for (pc, line) in code.iter().enumerate() {
if let ScriptIR::Label { label } = line {
label_to_pc.insert(label.clone(), pc);
}
}
Executor {
span,
client,
code,
vars: HashMap::new(),
sets: HashMap::new(),
iters: HashMap::new(),
label_to_pc,
return_value: None,
pc: 0,
}
}
pub async fn run(&mut self, max_steps: usize) -> Result<Option<ReturnValue<C>>> {
for _ in 0..max_steps {
if self.pc >= self.code.len() {
return Ok(self.return_value.take());
}
self.step().await?;
}
Err(ErrorCode::ScriptExecutionError(format!(
"Execution of script has exceeded the limit of {} steps, \
which usually means you may have an infinite loop. Otherwise, \
You can increase the limit with `set script_max_steps = {};`.",
max_steps,
max_steps * 10
))
.set_span(self.span))
}
async fn step(&mut self) -> Result<()> {
let line = self
.code
.get(self.pc)
.ok_or_else(|| {
ErrorCode::ScriptExecutionError(format!("pc out of bounds: {}", self.pc))
})?
.clone();
match &line {
ScriptIR::Query { stmt, to_set } => {
let sql = stmt
.subst(|var| self.client.var_to_ast(self.get_var(&var)?))?
.to_string();
let block = self
.client
.query(&sql)
.await
.map_err(|err| err.set_span(stmt.span))?;
self.sets.insert(to_set.clone(), block);
}
ScriptIR::Iter { set, to_iter } => {
let block = self.get_set(set)?;
let cursor = Cursor {
set: set.clone(),
row: 0,
len: self.client.num_rows(block),
};
self.iters.insert(to_iter.clone(), cursor);
}
ScriptIR::Read {
iter,
column,
to_var,
} => {
let cursor = self.get_iter(iter)?;
let block = self.get_set(&cursor.set)?;
let scalar = self.client.read_from_set(block, cursor.row, column)?;
self.vars.insert(to_var.clone(), scalar);
}
ScriptIR::Next { iter } => {
let cursor = self.get_iter_mut(iter)?;
assert!(cursor.row < cursor.len);
cursor.row += 1;
}
ScriptIR::Label { .. } => {}
ScriptIR::JumpIfEnded { iter, to_label } => {
let cursor = self.get_iter(iter)?;
if cursor.row >= cursor.len {
self.goto(to_label)?;
}
}
ScriptIR::JumpIfTrue {
condition,
to_label,
} => {
let scalar = self.get_var(condition)?;
if self.client.is_true(scalar)? {
self.goto(to_label)?;
}
}
ScriptIR::Goto { to_label } => {
self.goto(to_label)?;
}
ScriptIR::Return => {
self.goto_end();
}
ScriptIR::ReturnVar { var } => {
self.return_value = Some(ReturnValue::Var(self.get_var(var)?.clone()));
self.goto_end();
}
ScriptIR::ReturnSet { set } => {
self.return_value = Some(ReturnValue::Set(self.get_set(set)?.clone()));
self.goto_end();
}
ScriptIR::Throw { span, message } => {
let msg = if let Some(var) = message {
let value = self.get_var(var)?;
self.client.format_error(value)?
} else {
"Script threw an error".to_string()
};
return Err(ErrorCode::ScriptExecutionError(msg).set_span(*span));
}
}
self.pc += 1;
Ok(())
}
fn get_var(&self, var: &VarRef) -> Result<&C::Var> {
self.vars
.get(var)
.ok_or_else(|| ErrorCode::ScriptExecutionError(format!("unknown var: {var}")))
}
fn get_set(&self, set: &SetRef) -> Result<&C::Set> {
self.sets
.get(set)
.ok_or_else(|| ErrorCode::ScriptExecutionError(format!("unknown set: {set}")))
}
fn get_iter(&self, iter: &IterRef) -> Result<&Cursor> {
self.iters
.get(iter)
.ok_or_else(|| ErrorCode::ScriptExecutionError(format!("unknown iter: {iter}")))
}
fn get_iter_mut(&mut self, iter: &IterRef) -> Result<&mut Cursor> {
self.iters
.get_mut(iter)
.ok_or_else(|| ErrorCode::ScriptExecutionError(format!("unknown iter: {iter}")))
}
fn goto(&mut self, label: &LabelRef) -> Result<()> {
self.pc = *self
.label_to_pc
.get(label)
.ok_or_else(|| ErrorCode::ScriptExecutionError(format!("unknown label: {label}")))?;
Ok(())
}
fn goto_end(&mut self) {
self.pc = self.code.len();
}
}