datafusion/execution/context/json.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use datafusion_common::TableReference;
19use datafusion_datasource_json::source::plan_to_json;
20use std::sync::Arc;
21
22use super::super::options::{NdJsonReadOptions, ReadOptions};
23use super::{DataFilePaths, DataFrame, ExecutionPlan, Result, SessionContext};
24
25impl SessionContext {
26 /// Creates a [`DataFrame`] for reading an JSON data source.
27 ///
28 /// For more control such as reading multiple files, you can use
29 /// [`read_table`](Self::read_table) with a [`super::ListingTable`].
30 ///
31 /// For an example, see [`read_csv`](Self::read_csv)
32 pub async fn read_json<P: DataFilePaths>(
33 &self,
34 table_paths: P,
35 options: NdJsonReadOptions<'_>,
36 ) -> Result<DataFrame> {
37 self._read_type(table_paths, options).await
38 }
39
40 /// Registers a JSON file as a table that it can be referenced
41 /// from SQL statements executed against this context.
42 pub async fn register_json(
43 &self,
44 table_ref: impl Into<TableReference>,
45 table_path: impl AsRef<str>,
46 options: NdJsonReadOptions<'_>,
47 ) -> Result<()> {
48 let listing_options = options
49 .to_listing_options(&self.copied_config(), self.copied_table_options());
50
51 self.register_type_check(table_path.as_ref(), &listing_options.file_extension)?;
52
53 self.register_listing_table(
54 table_ref,
55 table_path,
56 listing_options,
57 options.schema.map(|s| Arc::new(s.to_owned())),
58 None,
59 )
60 .await?;
61 Ok(())
62 }
63
64 /// Executes a query and writes the results to a partitioned JSON file.
65 pub async fn write_json(
66 &self,
67 plan: Arc<dyn ExecutionPlan>,
68 path: impl AsRef<str>,
69 ) -> Result<()> {
70 plan_to_json(self.task_ctx(), plan, path).await
71 }
72}