1use std::collections::HashMap;
25use std::sync::Arc;
26
27use datafusion::arrow::array::{RecordBatch, UInt64Array};
28use datafusion::arrow::datatypes::{DataType, Field, Schema, SchemaRef};
29use datafusion::arrow::ipc::writer::{FileWriter, IpcWriteOptions};
30use datafusion::arrow::ipc::MetadataVersion;
31use datafusion::common::config::{CsvOptions, JsonOptions, TableParquetOptions};
32use datafusion::common::file_options::csv_writer::CsvWriterOptions;
33use datafusion::common::parsers::CompressionTypeVariant;
34use datafusion::common::tree_node::{TreeNode, TreeNodeRecursion};
35use datafusion::dataframe::DataFrame;
36use datafusion::datasource::file_format::arrow::ArrowFormat;
37use datafusion::datasource::file_format::csv::{CsvFormat, CsvSerializer};
38use datafusion::datasource::file_format::file_type_to_format;
39use datafusion::datasource::file_format::json::{JsonFormat, JsonSerializer};
40use datafusion::datasource::file_format::parquet::ParquetFormat;
41use datafusion::datasource::file_format::write::BatchSerializer;
42use datafusion::datasource::listing::ListingTable;
43use datafusion::datasource::source_as_provider;
44use datafusion::error::{DataFusionError, Result};
45use datafusion::execution::context::SessionState;
46use datafusion::execution::runtime_env::RuntimeEnv;
47use datafusion::logical_expr::dml::CopyTo;
48use datafusion::logical_expr::{LogicalPlan, WriteOp};
49use datafusion::parquet::arrow::arrow_writer::ArrowWriterOptions;
50use datafusion::parquet::arrow::ArrowWriter;
51use datafusion::parquet::file::properties::WriterPropertiesBuilder;
52use datafusion::prelude::{SessionConfig, SessionContext};
53use futures::TryStreamExt;
54use object_store::path::Path as ObjectPath;
55use object_store::{ObjectStore, ObjectStoreExt, PutPayload};
56use url::Url;
57
58pub const URL: &str = "memory://uploads/";
60
61const FORMATS: &str = ".parquet, .csv, .json and .arrow";
63
64pub fn store(runtime: &RuntimeEnv) -> Option<Arc<dyn ObjectStore>> {
66 let url = Url::parse(URL).expect("a valid URL");
67 runtime.object_store_registry.get_store(&url).ok()
68}
69
70pub fn takes_copy(state: &SessionState) -> bool {
74 cfg!(target_arch = "wasm32")
75 || (store(state.runtime_env()).is_some() && !copies_to_disk(state.config()))
76}
77
78#[derive(Debug)]
80struct CopyToDisk(bool);
81
82pub fn set_copy_to_disk(ctx: &SessionContext, on: bool) {
87 let state = ctx.state_ref();
88 let mut state = state.write();
89 state.config_mut().set_extension(Arc::new(CopyToDisk(on)));
90}
91
92pub fn copies_to_disk(config: &SessionConfig) -> bool {
95 config.get_extension::<CopyToDisk>().is_some_and(|on| on.0)
96}
97
98pub fn is_file_name(name: &str) -> bool {
103 !name.is_empty()
104 && !name.starts_with('.')
105 && name
106 .chars()
107 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
108}
109
110enum Place<'a> {
112 File(&'a str),
114 NotAName,
116 Elsewhere,
118}
119
120fn place(location: &str) -> Place<'_> {
121 let name = match location.strip_prefix(URL) {
122 Some(name) => name,
123 None if matches!(Url::parse(location), Ok(url) if url.scheme().len() > 1) => {
125 return Place::Elsewhere
126 }
127 None => location.strip_prefix("./").unwrap_or(location),
128 };
129 if is_file_name(name) {
130 Place::File(name)
131 } else {
132 Place::NotAName
133 }
134}
135
136pub async fn existing(runtime: &RuntimeEnv, location: &str) -> Option<String> {
140 let Place::File(name) = place(location) else {
141 return None;
142 };
143 let store = store(runtime)?;
144 store.head(&ObjectPath::from(name)).await.ok()?;
145 Some(format!("{URL}{name}"))
146}
147
148pub fn copy_target(runtime: &RuntimeEnv, target: &str) -> Result<String> {
151 let works = "COPY … TO 'name.parquet' (or .csv, .json, .arrow) keeps the file in this \
152 session, where FROM 'name.parquet' reads it";
153 if store(runtime).is_none() {
154 return Err(DataFusionError::Plan(format!(
155 "COPY … TO '{target}' has nowhere to write: a browser has no disk, and this \
156 session keeps no files. Run the query and export its result instead"
157 )));
158 }
159 match place(target) {
160 Place::File(name) => Ok(format!("{URL}{name}")),
161 Place::NotAName => Err(DataFusionError::Plan(format!(
162 "COPY … TO '{target}' cannot be written here: a browser has no disk, so a file \
163 is kept in the session under a name of letters, digits, '.', '_' and '-', with \
164 no folder. {works}"
165 ))),
166 Place::Elsewhere => Err(DataFusionError::Plan(format!(
167 "COPY … TO '{target}' cannot be written from a browser, which writes only this \
168 session's files. {works}"
169 ))),
170 }
171}
172
173pub fn check_copy_format(target: &str, stored_as: Option<&str>) -> Result<()> {
177 if stored_as.is_some() {
178 return Ok(());
179 }
180 let extension = target.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
181 match extension.as_deref() {
182 Some("parquet" | "csv" | "json" | "jsonl" | "ndjson" | "arrow") => Ok(()),
183 _ => Err(DataFusionError::Plan(format!(
184 "COPY … TO '{target}' names no format a browser session writes: end the name \
185 in {}, or say STORED AS PARQUET (or CSV, JSON, ARROW)",
186 FORMATS.replace(" and ", " or ")
187 ))),
188 }
189}
190
191pub async fn copy_to(ctx: &SessionContext, copy: &CopyTo) -> Result<DataFrame> {
195 let state = ctx.state();
196 let url = copy_target(state.runtime_env(), ©.output_url)?;
197 let name = &url[URL.len()..];
198 if !copy.partition_by.is_empty() {
199 return Err(DataFusionError::Plan(
200 "COPY … PARTITIONED BY writes a directory of files, and a browser session keeps \
201 single files; leave PARTITIONED BY out"
202 .into(),
203 ));
204 }
205 let mut options: HashMap<String, String> = copy.options.clone();
207 match options
208 .remove("single_file_output")
209 .as_deref()
210 .map(str::trim)
211 {
212 None | Some("true") => {}
213 Some(_) => {
214 return Err(DataFusionError::Plan(
215 "COPY … TO writes one file in a browser session; leave single_file_output out"
216 .into(),
217 ))
218 }
219 }
220 let format = file_type_to_format(©.file_type)?.create(&state, &options)?;
221 let format = match format.downcast_ref::<ursa_io::parquet_footer::ValidParquet>() {
223 Some(checked) => Arc::clone(checked.inner()),
224 None => format,
225 };
226 let writer = if let Some(csv) = format.downcast_ref::<CsvFormat>() {
227 Writer::csv(csv.options())?
228 } else if let Some(json) = format.downcast_ref::<JsonFormat>() {
229 Writer::json(json.options())?
230 } else if let Some(parquet) = format.downcast_ref::<ParquetFormat>() {
231 Writer::Parquet(Box::new(parquet.options().clone()))
232 } else if format.is::<ArrowFormat>() {
233 Writer::Arrow
234 } else {
235 return Err(DataFusionError::Plan(format!(
236 "COPY … TO writes {FORMATS} files in a browser session, and '{}' is none of them",
237 copy.file_type.get_ext()
238 )));
239 };
240
241 let schema: SchemaRef = Arc::clone(copy.input.schema().inner());
242 let frame = DataFrame::new(state, copy.input.as_ref().clone());
243 let batches: Vec<RecordBatch> = frame.execute_stream().await?.try_collect().await?;
244 let rows: usize = batches.iter().map(RecordBatch::num_rows).sum();
245 let bytes = writer.write(&schema, batches)?;
246
247 let store = store(ctx.state().runtime_env().as_ref())
248 .ok_or_else(|| DataFusionError::Internal("the session's files are gone".into()))?;
249 store
250 .put(&ObjectPath::from(name), PutPayload::from(bytes))
251 .await
252 .map_err(|e| DataFusionError::External(Box::new(e)))?;
253
254 let count = Arc::new(Schema::new(vec![Field::new(
255 "count",
256 DataType::UInt64,
257 false,
258 )]));
259 let batch = RecordBatch::try_new(count, vec![Arc::new(UInt64Array::from(vec![rows as u64]))])?;
260 ctx.read_batch(batch)
261}
262
263pub fn check_insert(plan: &LogicalPlan) -> Result<()> {
266 let mut refused = None;
267 plan.apply(|node| {
268 if let LogicalPlan::Dml(dml) = node {
269 let files = source_as_provider(&dml.target)
270 .is_ok_and(|table| table.downcast_ref::<ListingTable>().is_some());
271 if files && matches!(dml.op, WriteOp::Insert(_)) {
272 refused = Some(dml.table_name.to_string());
273 return Ok(TreeNodeRecursion::Stop);
274 }
275 }
276 Ok(TreeNodeRecursion::Continue)
277 })?;
278 match refused {
279 None => Ok(()),
280 Some(table) => Err(DataFusionError::Plan(format!(
281 "INSERT INTO {table} cannot run in a browser session: {table} is a table of \
282 files, and a browser cannot append to them. COPY (SELECT …) TO 'name.parquet' \
283 writes a file, and CREATE TABLE … AS keeps rows in the session"
284 ))),
285 }
286}
287
288enum Writer {
290 Csv(CsvSerializer),
291 Json,
292 Parquet(Box<TableParquetOptions>),
293 Arrow,
294}
295
296impl Writer {
297 fn csv(options: &CsvOptions) -> Result<Writer> {
298 let options = CsvWriterOptions::try_from(options)?;
299 uncompressed("CSV", options.compression)?;
300 let header = options.writer_options.header();
301 Ok(Writer::Csv(
302 CsvSerializer::new()
303 .with_builder(options.writer_options)
304 .with_header(header),
305 ))
306 }
307
308 fn json(options: &JsonOptions) -> Result<Writer> {
309 uncompressed("JSON", options.compression)?;
310 Ok(Writer::Json)
311 }
312
313 fn write(self, schema: &SchemaRef, mut batches: Vec<RecordBatch>) -> Result<Vec<u8>> {
316 let mut bytes = Vec::new();
317 match self {
318 Writer::Csv(serializer) => {
319 if batches.is_empty() {
320 batches.push(RecordBatch::new_empty(Arc::clone(schema)));
321 }
322 for (i, batch) in batches.into_iter().enumerate() {
323 bytes.extend_from_slice(&serializer.serialize(batch, i == 0)?);
324 }
325 }
326 Writer::Json => {
328 let serializer = JsonSerializer::new();
329 for (i, batch) in batches.into_iter().enumerate() {
330 bytes.extend_from_slice(&serializer.serialize(batch, i == 0)?);
331 }
332 }
333 Writer::Parquet(options) => {
334 let mut options = *options;
337 if !options.global.skip_arrow_metadata {
338 options.arrow_schema(schema);
339 }
340 let properties = WriterPropertiesBuilder::try_from(&options)?.build();
341 let options = ArrowWriterOptions::new()
342 .with_properties(properties)
343 .with_skip_arrow_metadata(true);
344 let mut writer =
345 ArrowWriter::try_new_with_options(&mut bytes, Arc::clone(schema), options)?;
346 for batch in &batches {
347 writer.write(batch)?;
348 }
349 writer.close()?;
350 }
351 Writer::Arrow => {
356 let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)?;
357 let mut writer = FileWriter::try_new_with_options(&mut bytes, schema, options)?;
358 for batch in &batches {
359 writer.write(batch)?;
360 }
361 writer.finish()?;
362 }
363 }
364 Ok(bytes)
365 }
366}
367
368fn uncompressed(format: &str, compression: CompressionTypeVariant) -> Result<()> {
371 if compression == CompressionTypeVariant::UNCOMPRESSED {
372 return Ok(());
373 }
374 Err(DataFusionError::Plan(format!(
375 "COPY … TO does not write compressed {format} in a browser session; leave the \
376 compression out, or write a .parquet file, which is compressed"
377 )))
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn places() {
386 assert!(matches!(place("pos.parquet"), Place::File("pos.parquet")));
387 assert!(matches!(place("./pos.parquet"), Place::File("pos.parquet")));
388 assert!(matches!(
389 place("memory://uploads/pos.parquet"),
390 Place::File("pos.parquet")
391 ));
392 for not in [
393 "out/pos.parquet",
394 "/tmp/pos.parquet",
395 "../pos.parquet",
396 "my file.csv",
397 "p*.csv",
398 ".hidden",
399 "",
400 "memory://uploads/a/b.csv",
401 "memory://uploads/",
402 ] {
403 assert!(matches!(place(not), Place::NotAName), "{not}");
404 }
405 for elsewhere in [
406 "https://example.com/pos.parquet",
407 "s3://bucket/pos.parquet",
408 "memory://other/pos.parquet",
409 "file:///tmp/pos.parquet",
410 ] {
411 assert!(matches!(place(elsewhere), Place::Elsewhere), "{elsewhere}");
412 }
413 }
414}