forked from databendlabs/databend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsert.rs
More file actions
318 lines (302 loc) · 12.8 KB
/
Copy pathinsert.rs
File metadata and controls
318 lines (302 loc) · 12.8 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// 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::sync::Arc;
use databend_common_ast::ast::CopyIntoTableOptions;
use databend_common_ast::ast::Identifier;
use databend_common_ast::ast::InsertSource;
use databend_common_ast::ast::InsertStmt;
use databend_common_ast::ast::Statement;
use databend_common_catalog::session_type::SessionType;
use databend_common_exception::ErrorCode;
use databend_common_exception::Result;
use databend_common_expression::DataSchemaRef;
use databend_common_expression::FieldIndex;
use databend_common_expression::TableField;
use databend_common_expression::TableSchema;
use databend_common_expression::TableSchemaRefExt;
use databend_common_meta_app::principal::FileFormatOptionsReader;
use databend_common_meta_app::principal::FileFormatParams;
use databend_common_storage::StageFilesInfo;
use super::util::TableIdentifier;
use crate::BindContext;
use crate::DefaultExprBinder;
use crate::binder::Binder;
use crate::binder::StagePathAccess;
use crate::binder::StageResolver;
use crate::binder::validate_stage_files_path_traversal;
use crate::normalize_identifier;
use crate::plans::CopyIntoTableMode;
use crate::plans::Insert;
use crate::plans::InsertInputSource;
use crate::plans::InsertValue;
use crate::plans::Plan;
use crate::plans::StreamingLoadPlan;
pub const STAGE_PLACEHOLDER: &str = "_databend_load";
impl Binder {
pub fn schema_project(
&self,
schema: &Arc<TableSchema>,
columns: &[Identifier],
entity_name: &str,
) -> Result<Arc<TableSchema>> {
let fields = if columns.is_empty() {
schema
.fields()
.iter()
.filter(|f| f.computed_expr().is_none())
.cloned()
.collect::<Vec<_>>()
} else {
columns
.iter()
.map(|ident| {
let field_name = &normalize_identifier(ident, &self.name_resolution_ctx).name;
let (_, field) =
Self::try_resolve_field_in_schema(schema, field_name, entity_name)?;
if field.computed_expr().is_some() {
Err(ErrorCode::BadArguments(format!(
"The value specified for computed column '{}' is not allowed",
field.name()
)))
} else {
Ok(field.clone())
}
})
.collect::<Result<Vec<_>>>()?
};
Ok(TableSchemaRefExt::create(fields))
}
pub(in crate::planner::binder) fn try_resolve_field_in_schema<'a>(
schema: &'a Arc<TableSchema>,
field_name: &str,
entity_name: &str,
) -> Result<(FieldIndex, &'a TableField)> {
match schema.column_with_name(field_name) {
None => Err(ErrorCode::BadArguments(format!(
"Table \"{}\" does not have a column with name \"{}\"",
entity_name, field_name
))),
Some(v) => Ok(v),
}
}
#[async_backtrace::framed]
pub(in crate::planner::binder) async fn bind_insert(
&mut self,
bind_context: &mut BindContext,
stmt: &InsertStmt,
) -> Result<Plan> {
let InsertStmt {
with,
table,
columns,
source,
overwrite,
..
} = stmt;
self.init_cte(bind_context, with)?;
let table_identifier = TableIdentifier::new_with_ref(self, table, &None);
let (catalog_name, database_name, table_name, branch_name) = (
table_identifier.catalog_name(),
table_identifier.database_name(),
table_identifier.table_name(),
table_identifier.branch_name(),
);
let table = self
.ctx
.get_table_with_branch(
&catalog_name,
&database_name,
&table_name,
branch_name.as_deref(),
)
.await
.map_err(|err| table_identifier.not_found_suggest_error(err))?;
let required_values_schema = self.schema_project(
&table.schema(),
columns,
&format!("{database_name}.{table_name}"),
)?;
let input_source: Result<InsertInputSource> = match source.clone() {
InsertSource::Values { rows } => {
let mut new_rows = Vec::with_capacity(rows.len());
for row in rows {
let new_row = bind_context
.exprs_to_scalar(
&row,
&Arc::new(required_values_schema.clone().into()),
self.ctx.clone(),
&self.name_resolution_ctx,
self.metadata.clone(),
)
.await?;
new_rows.push(new_row);
}
Ok(InsertInputSource::Values(InsertValue::Values {
rows: new_rows,
}))
}
InsertSource::RawValues { rest_str, start } => {
let values_str = rest_str.trim_end_matches(';').trim_start().to_owned();
match self.ctx.get_stage_attachment() {
Some(attachment) => {
// TODO(zhyass): Support INSERT INTO table branch FROM stage.
// Planned to be implemented in the next PR.
if branch_name.is_some() {
return Err(ErrorCode::Unimplemented(
"Insert into branch from stage is not supported yet",
));
}
return self
.bind_copy_from_attachment(
bind_context,
attachment,
catalog_name,
database_name,
table_name,
required_values_schema,
&values_str,
CopyIntoTableMode::Insert {
overwrite: *overwrite,
},
)
.await;
}
None => Ok(InsertInputSource::Values(InsertValue::RawValues {
data: rest_str,
start,
})),
}
}
InsertSource::Select { query } => {
let statement = Statement::Query(query);
let select_plan = self.bind_statement(bind_context, &statement).await?;
Ok(InsertInputSource::SelectPlan(Box::new(select_plan)))
}
InsertSource::LoadFile {
value,
format_options,
location,
} => {
let settings = self.ctx.get_settings();
let file_format_params = FileFormatParams::try_from_reader(
FileFormatOptionsReader::from_ast(&format_options),
false,
)?;
if matches!(file_format_params, FileFormatParams::Lance(_)) {
return Err(ErrorCode::IllegalFileFormat(
"LANCE file format is only supported in COPY INTO <location>".to_string(),
));
}
match location.as_str() {
STAGE_PLACEHOLDER => {
if self.ctx.get_session_type() != SessionType::HTTPStreamingLoad {
return Err(ErrorCode::BadArguments(
"placeholder @_databend_upload in query handler: should be used in streaming_load handler or replaced in client.",
));
}
let (required_source_schema, values_consts) = if let Some(value) = value {
self.prepared_values(value, &required_values_schema, settings)
.await?
} else {
(required_values_schema.clone(), vec![])
};
let required_values_schema: DataSchemaRef =
Arc::new(required_values_schema.clone().into());
let default_exprs = if file_format_params.need_field_default() {
Some(
DefaultExprBinder::try_new(self.ctx.clone())?
.auto_increment_table_id(table.get_id())
.prepare_default_values(&required_values_schema)?,
)
} else {
None
};
Ok(InsertInputSource::StreamingLoad(StreamingLoadPlan {
file_format: Box::new(file_format_params),
required_values_schema,
values_consts,
block_thresholds: table.get_block_thresholds(),
default_exprs,
// fill it in HTTP handler
receiver: Default::default(),
required_source_schema,
}))
}
loc => {
// TODO(zhyass): Support INSERT INTO table branch FROM stage.
// Planned to be implemented in the next PR.
if branch_name.is_some() {
return Err(ErrorCode::Unimplemented(
"Insert into branch from stage is not supported yet",
));
}
let (mut stage_info, path) = StageResolver::from_table_context(
self.ctx.clone(),
databend_common_users::UserApiProvider::instance(),
databend_common_config::GlobalConfig::instance()
.storage
.allow_insecure,
)?
.resolve_stage_location(loc, StagePathAccess::Read)
.await?;
stage_info.file_format_params = file_format_params;
let files_info = StageFilesInfo {
path,
files: None,
pattern: None,
};
validate_stage_files_path_traversal(
self.ctx.get_settings().as_ref(),
&files_info.path,
files_info.files.as_deref(),
false,
)?;
let options = CopyIntoTableOptions {
purge: true,
force: true,
..Default::default()
};
return self
.bind_copy_from_upload(
bind_context,
catalog_name,
database_name,
table_name,
required_values_schema,
value,
stage_info,
files_info,
options,
CopyIntoTableMode::Insert {
overwrite: *overwrite,
},
)
.await;
}
}
}
};
let plan = Insert {
catalog: catalog_name,
database: database_name,
table: table_name,
branch: branch_name,
schema: required_values_schema,
overwrite: *overwrite,
source: input_source?,
table_info: None,
};
Ok(Plan::Insert(Box::new(plan)))
}
}