Skip to main content

datafusion_cli/object_storage/
stdin.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Exposes the process's standard input as a `stdin://` object store so that
6//! piped data (e.g. `cat data.csv | datafusion-cli`) can be queried via
7//! `CREATE EXTERNAL TABLE ... LOCATION '/dev/stdin'`.
8
9use std::io::{IsTerminal, Read};
10use std::sync::Arc;
11
12use datafusion::common::exec_datafusion_err;
13use datafusion::config::ConfigFileType;
14use datafusion::error::Result;
15use datafusion::execution::context::SessionState;
16use futures::TryStreamExt;
17
18use object_store::memory::InMemory;
19use object_store::path::Path as ObjectStorePath;
20use object_store::{ObjectStore, ObjectStoreExt};
21use url::Url;
22
23/// Marker [`SessionConfig`] extension recording that the session reads its SQL
24/// commands from stdin (the interactive or piped REPL). stdin cannot then also
25/// serve as a data source: reading it for table data would silently consume
26/// the remaining SQL statements.
27///
28/// [`SessionConfig`]: datafusion::execution::context::SessionConfig
29#[derive(Debug)]
30pub struct StdinCarriesCommands;
31
32/// Filesystem paths that refer to the process's standard input.
33///
34/// These are intentionally limited to the well known pseudo-files exposed by
35/// the operating system so that ordinary files are never accidentally treated
36/// as stdin.
37const STDIN_LOCATIONS: [&str; 3] = ["/dev/stdin", "/dev/fd/0", "/proc/self/fd/0"];
38
39/// Returns `true` if `path` refers to the process's standard input.
40///
41/// Re-exported as [`crate::object_storage::is_stdin_location`] so the CLI entry
42/// point can detect when it reads its SQL from stdin via `-f /dev/stdin` and
43/// avoid also offering stdin as a `LOCATION '/dev/stdin'` data source.
44pub fn is_stdin_location(path: &str) -> bool {
45    STDIN_LOCATIONS.contains(&path)
46}
47
48/// Utilities for exposing the process's standard input as an object store.
49///
50/// stdin is surfaced as a `stdin://` object store and dispatched alongside the
51/// other schemes (`s3`, `gs`, `http`, ...) so that reading piped data flows
52/// through the normal object-store/listing code path, conceptually similar to
53/// DuckDB's `PipeFileSystem`.
54pub(crate) struct StdinUtils;
55
56impl StdinUtils {
57    /// The URL scheme used to expose stdin as an object store, mirroring how
58    /// `s3`, `gs`, `http`, etc. are addressed.
59    pub(crate) const SCHEME: &'static str = "stdin";
60
61    /// Rewrites the well known stdin pseudo-paths (e.g. `/dev/stdin`) to a
62    /// canonical `stdin://` URL so that reading from standard input flows
63    /// through the same object-store/listing code path as any other scheme.
64    /// Non-stdin locations are returned unchanged.
65    ///
66    /// The listing layer filters candidate files by extension, so the canonical
67    /// object is named with the extension matching the declared `STORED AS`
68    /// format. The name thereby also records which format stdin was consumed
69    /// as: a later stdin-backed table declaring a different format resolves to
70    /// a path the buffered store does not contain and is rejected by
71    /// [`Self::get_or_create`].
72    pub(crate) fn rewrite_location(
73        location: &str,
74        format: Option<&ConfigFileType>,
75    ) -> String {
76        if !is_stdin_location(location) {
77            return location.to_string();
78        }
79
80        let object_name = match format {
81            Some(ConfigFileType::CSV) => "stdin.csv",
82            Some(ConfigFileType::JSON) => "stdin.json",
83            Some(ConfigFileType::PARQUET) => "stdin.parquet",
84            _ => "stdin",
85        };
86        format!("{}:///{object_name}", Self::SCHEME)
87    }
88
89    /// Returns the object store backing the `stdin://` scheme, buffering all of
90    /// standard input when the store is first constructed and reusing that
91    /// buffer for any subsequent `stdin://` table created in the same session.
92    ///
93    /// stdin is a one-shot stream: it can only be read once. The object store
94    /// registry keys by scheme/authority, so every `stdin://` URL maps to the
95    /// same store. Without this guard, a second `CREATE EXTERNAL TABLE ...
96    /// LOCATION '/dev/stdin'` would re-read (now-EOF) stdin, build an empty
97    /// store, and overwrite the populated one, silently emptying the earlier
98    /// table. Reusing the already-registered store avoids that.
99    ///
100    /// A later stdin-backed table declaring a different `STORED AS` format
101    /// resolves to an object the store does not contain (the object name
102    /// records the format stdin was consumed as) and is rejected with a clear
103    /// error — both reading the buffer as another format and re-reading stdin
104    /// would be silently wrong.
105    pub(crate) async fn get_or_create(
106        state: &SessionState,
107        url: &Url,
108    ) -> Result<Arc<dyn ObjectStore>> {
109        let Ok(existing) = state.runtime_env().object_store_registry.get_store(url)
110        else {
111            return Self::object_store(state, url).await;
112        };
113
114        let path = ObjectStorePath::from_url_path(url.path())?;
115        if existing.head(&path).await.is_err() {
116            let buffered = existing
117                .list(None)
118                .try_next()
119                .await
120                .ok()
121                .flatten()
122                .map(|meta| format!(" as '{}'", meta.location))
123                .unwrap_or_default();
124            return Err(exec_datafusion_err!(
125                "stdin was already read{buffered} by an earlier statement; all \
126                 tables backed by stdin in a session must declare the same \
127                 STORED AS format"
128            ));
129        }
130        Ok(existing)
131    }
132
133    /// Builds the object store backing the `stdin://` scheme by reading all of
134    /// standard input into memory.
135    ///
136    /// A pipe (e.g. `cat data.csv | datafusion-cli`) is not seekable and reports
137    /// a size of `0`, so it cannot be read directly by the file based formats
138    /// (CSV requires seeking, Parquet needs the footer at the end of the file).
139    /// Buffering the whole input up front sidesteps these limitations and lets
140    /// the data be read like any other object, including being scanned more than
141    /// once.
142    async fn object_store(
143        state: &SessionState,
144        url: &Url,
145    ) -> Result<Arc<dyn ObjectStore>> {
146        if state
147            .config()
148            .get_extension::<StdinCarriesCommands>()
149            .is_some()
150        {
151            return Err(exec_datafusion_err!(
152                "stdin is already being read for SQL commands, so it cannot \
153                 also supply table data; pass the query with -c/--command or \
154                 -f/--file so that stdin carries the data, e.g. \
155                 `cat data.csv | datafusion-cli -f query.sql`"
156            ));
157        }
158        if std::io::stdin().is_terminal() {
159            return Err(exec_datafusion_err!(
160                "stdin is connected to a terminal, not piped data; pipe the \
161                 input in, e.g. `cat data.csv | datafusion-cli -f query.sql`"
162            ));
163        }
164
165        let mut buffer = Vec::new();
166        std::io::stdin()
167            .lock()
168            .read_to_end(&mut buffer)
169            .map_err(|e| exec_datafusion_err!("Failed to read from stdin: {e}"))?;
170        Self::in_memory_object_store(url, buffer).await
171    }
172
173    /// Stores `data` at the path referenced by `url` in a fresh [`InMemory`]
174    /// store.
175    async fn in_memory_object_store(
176        url: &Url,
177        data: Vec<u8>,
178    ) -> Result<Arc<dyn ObjectStore>> {
179        let store = InMemory::new();
180        store
181            .put(&ObjectStorePath::from_url_path(url.path())?, data.into())
182            .await?;
183        Ok(Arc::new(store))
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190
191    use datafusion::prelude::{SessionConfig, SessionContext};
192
193    #[test]
194    fn rewrites_stdin_locations() {
195        // stdin pseudo-paths are rewritten to a `stdin://` URL carrying the
196        // extension that matches the declared format.
197        assert_eq!(
198            StdinUtils::rewrite_location("/dev/stdin", Some(&ConfigFileType::CSV)),
199            "stdin:///stdin.csv"
200        );
201        assert_eq!(
202            StdinUtils::rewrite_location("/dev/fd/0", Some(&ConfigFileType::JSON)),
203            "stdin:///stdin.json"
204        );
205        assert_eq!(
206            StdinUtils::rewrite_location(
207                "/proc/self/fd/0",
208                Some(&ConfigFileType::PARQUET)
209            ),
210            "stdin:///stdin.parquet"
211        );
212        assert_eq!(
213            StdinUtils::rewrite_location("/dev/stdin", None),
214            "stdin:///stdin"
215        );
216
217        // Ordinary locations are left untouched.
218        for location in ["/dev/stdout", "data/stdin.csv", "stdin", "s3://b/f.csv"] {
219            assert_eq!(
220                StdinUtils::rewrite_location(location, Some(&ConfigFileType::CSV)),
221                location
222            );
223        }
224    }
225
226    /// Buffers `data` into the `stdin://` object store and reads it back through
227    /// a `CREATE EXTERNAL TABLE`, returning the number of rows in the table.
228    ///
229    /// This exercises the full path used for `/dev/stdin` short of the actual
230    /// stdin read, which cannot be driven from a unit test.
231    async fn count_stdin_rows(
232        data: Vec<u8>,
233        stored_as: &str,
234        format: Option<ConfigFileType>,
235        options: &str,
236    ) -> Result<usize> {
237        let location = StdinUtils::rewrite_location("/dev/stdin", format.as_ref());
238        let url = Url::parse(&location).unwrap();
239        let store = StdinUtils::in_memory_object_store(&url, data).await?;
240
241        let ctx = SessionContext::new();
242        ctx.register_object_store(&url, store);
243        ctx.sql(&format!(
244            "CREATE EXTERNAL TABLE t STORED AS {stored_as} LOCATION '{location}' {options}"
245        ))
246        .await?
247        .collect()
248        .await?;
249
250        ctx.sql("SELECT * FROM t").await?.count().await
251    }
252
253    #[tokio::test]
254    async fn reuses_buffered_stdin_store() -> Result<()> {
255        // stdin can only be read once, so a second `stdin://` table must reuse
256        // the store buffered by the first instead of re-reading (now-empty)
257        // stdin and overwriting it.
258        //
259        // The very first read happens inside `get_or_create` -> `object_store`,
260        // which consumes the real process stdin and so cannot be driven from a
261        // unit test. Seed the registry with the store that first read would have
262        // produced (as the first `CREATE EXTERNAL TABLE` does), then drive the
263        // lookup through `get_or_create` and assert it hands back that exact
264        // store rather than rebuilding it.
265        let url = Url::parse("stdin:///stdin.csv").unwrap();
266        let path = ObjectStorePath::from_url_path(url.path())?;
267        let buffered: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
268        buffered.put(&path, b"a\n1\n2\n".to_vec().into()).await?;
269
270        let ctx = SessionContext::new();
271        ctx.register_object_store(&url, Arc::clone(&buffered));
272
273        let reused = StdinUtils::get_or_create(&ctx.state(), &url).await?;
274        assert!(
275            Arc::ptr_eq(&buffered, &reused),
276            "get_or_create must reuse the registered stdin store, not rebuild it"
277        );
278        let bytes = reused.get(&path).await?.bytes().await?;
279        assert_eq!(bytes.as_ref(), b"a\n1\n2\n");
280        Ok(())
281    }
282
283    #[tokio::test]
284    async fn rejects_second_stdin_table_with_different_format() -> Result<()> {
285        // The buffered object's name records the format stdin was consumed
286        // as; a later stdin table declaring a different format must fail with
287        // a clear error rather than a downstream "not found" (or silently
288        // misreading the bytes as another format).
289        let csv_url = Url::parse("stdin:///stdin.csv").unwrap();
290        let store =
291            StdinUtils::in_memory_object_store(&csv_url, b"a\n1\n".to_vec()).await?;
292
293        let ctx = SessionContext::new();
294        ctx.register_object_store(&csv_url, store);
295
296        let json_url = Url::parse("stdin:///stdin.json").unwrap();
297        let err = StdinUtils::get_or_create(&ctx.state(), &json_url)
298            .await
299            .unwrap_err()
300            .to_string();
301        assert!(
302            err.contains("must declare the same STORED AS format")
303                && err.contains("stdin.csv"),
304            "unexpected error: {err}"
305        );
306        Ok(())
307    }
308
309    #[tokio::test]
310    async fn errors_when_stdin_carries_commands() {
311        // Once the REPL owns stdin for SQL commands, building the stdin store
312        // must fail with a clear error instead of swallowing the remaining
313        // statements as table data.
314        let config = SessionConfig::new().with_extension(Arc::new(StdinCarriesCommands));
315        let ctx = SessionContext::new_with_config(config);
316
317        let url = Url::parse("stdin:///stdin.csv").unwrap();
318        let err = StdinUtils::get_or_create(&ctx.state(), &url)
319            .await
320            .unwrap_err();
321        assert!(
322            err.to_string().contains("SQL commands"),
323            "unexpected error: {err}"
324        );
325    }
326
327    #[tokio::test]
328    async fn stdin_object_store_reads_csv() -> Result<()> {
329        let data = b"a,b\n1,foo\n2,bar\n".to_vec();
330        let rows = count_stdin_rows(
331            data,
332            "CSV",
333            Some(ConfigFileType::CSV),
334            "OPTIONS ('format.has_header' 'true')",
335        )
336        .await?;
337        assert_eq!(rows, 2);
338        Ok(())
339    }
340
341    #[tokio::test]
342    async fn stdin_object_store_reads_json() -> Result<()> {
343        let data = b"{\"a\": 1, \"b\": \"foo\"}\n{\"a\": 2, \"b\": \"bar\"}\n".to_vec();
344        let rows = count_stdin_rows(data, "JSON", Some(ConfigFileType::JSON), "").await?;
345        assert_eq!(rows, 2);
346        Ok(())
347    }
348
349    #[tokio::test]
350    async fn stdin_object_store_reads_parquet() -> Result<()> {
351        use datafusion::arrow::array::Int32Array;
352        use datafusion::arrow::datatypes::{DataType, Field, Schema};
353        use datafusion::arrow::record_batch::RecordBatch;
354        use parquet::arrow::ArrowWriter;
355
356        // Parquet requires random access to the footer, which a real pipe cannot
357        // provide; the in-memory buffer makes this work.
358        let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
359        let batch = RecordBatch::try_new(
360            Arc::clone(&schema),
361            vec![Arc::new(Int32Array::from(vec![1, 2, 3]))],
362        )
363        .unwrap();
364
365        let mut data = Vec::new();
366        let mut writer = ArrowWriter::try_new(&mut data, schema, None).unwrap();
367        writer.write(&batch).unwrap();
368        writer.close().unwrap();
369
370        let rows =
371            count_stdin_rows(data, "PARQUET", Some(ConfigFileType::PARQUET), "").await?;
372        assert_eq!(rows, 3);
373        Ok(())
374    }
375}