forked from datafusion-contrib/datafusion-dft
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtpch.rs
More file actions
341 lines (318 loc) · 11 KB
/
tpch.rs
File metadata and controls
341 lines (318 loc) · 11 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 crate::args::TpchFormat;
use crate::config::AppConfig;
use color_eyre::{eyre, Result};
use datafusion::{arrow::record_batch::RecordBatch, datasource::listing::ListingTableUrl};
use datafusion_app::{
config::merge_configs, extensions::DftSessionStateBuilder, local::ExecutionContext,
};
use log::info;
use object_store::ObjectStore;
use parquet::arrow::ArrowWriter;
use tpchgen::generators::{
CustomerGenerator, LineItemGenerator, NationGenerator, OrderGenerator, PartGenerator,
PartSuppGenerator, RegionGenerator, SupplierGenerator,
};
use tpchgen_arrow::{
CustomerArrow, LineItemArrow, NationArrow, OrderArrow, PartArrow, PartSuppArrow, RegionArrow,
SupplierArrow,
};
use url::Url;
#[cfg(feature = "vortex")]
use {
datafusion::arrow::compute::concat_batches,
vortex::{arrow::FromArrowArray, stream::ArrayStreamAdapter, ArrayRef},
vortex_file::VortexWriteOptions,
};
enum GeneratorType {
Customer,
Order,
LineItem,
Nation,
Part,
PartSupp,
Region,
Supplier,
}
impl TryFrom<&str> for GeneratorType {
type Error = color_eyre::Report;
fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
// `/` suffix is used so that the final path part is interpretted as a directory
match value {
"customer/" => Ok(Self::Customer),
"orders/" => Ok(Self::Order),
"lineitem/" => Ok(Self::LineItem),
"nation/" => Ok(Self::Nation),
"part/" => Ok(Self::Part),
"partsupp/" => Ok(Self::PartSupp),
"region/" => Ok(Self::Region),
"supplier/" => Ok(Self::Supplier),
_ => Err(eyre::Report::msg(format!("unknown generator type {value}"))),
}
}
}
fn create_tpch_dirs(config: &AppConfig) -> Result<Vec<(GeneratorType, Url)>> {
info!("...configured DB directory is {:?}", config.db.path);
// `/` suffix is used so that the final path part is interpretted as a directory
let tpch_dir = config
.db
.path
.join("tables/")?
.join("dft/")?
.join("tpch/")?;
let needed_dirs = [
"customer/",
"orders/",
"lineitem/",
"nation/",
"part/",
"partsupp/",
"region/",
"supplier/",
];
let mut table_paths = Vec::new();
for dir in needed_dirs {
let table_path = tpch_dir.join(dir)?;
info!("table path {:?} for table {dir}", table_path.path());
table_paths.push((GeneratorType::try_from(dir)?, table_path))
}
Ok(table_paths)
}
async fn write_batches_to_parquet<I>(
mut batches: std::iter::Peekable<I>,
table_path: &Url,
table_type: &str,
store: Arc<dyn ObjectStore>,
) -> Result<()>
where
I: Iterator<Item = RecordBatch>,
{
let first = batches.peek().ok_or(eyre::Error::msg(format!(
"unable to generate {table_type} TPC-H data"
)))?;
let file_url = table_path.join("data.parquet")?;
info!("...file URL '{file_url}'");
let mut buf: Vec<u8> = Vec::new();
{
let mut writer = ArrowWriter::try_new(&mut buf, Arc::clone(first.schema_ref()), None)?;
info!("...writing {table_type} batches");
for batch in batches {
writer.write(&batch)?;
}
writer.finish()?;
}
let file_path = object_store::path::Path::from_url_path(file_url.path())?;
info!("...putting to file path {}", file_path);
store.put(&file_path, buf.into()).await?;
Ok(())
}
#[cfg(feature = "vortex")]
async fn write_batches_to_vortex<I>(
batches: std::iter::Peekable<I>,
table_path: &Url,
table_type: &str,
store: Arc<dyn ObjectStore>,
) -> Result<()>
where
I: Iterator<Item = RecordBatch>,
{
let batches_vec: Vec<RecordBatch> = batches.collect();
if batches_vec.is_empty() {
return Err(eyre::Error::msg(format!(
"unable to generate {table_type} TPC-H data"
)));
}
let file_url = table_path.join("data.vortex")?;
info!("...file URL '{file_url}'");
// Concatenate all batches into a single batch
let schema = batches_vec[0].schema();
let concatenated = concat_batches(&schema, &batches_vec)?;
// Convert to Vortex array
let vortex_array = ArrayRef::from_arrow(concatenated, false);
let dtype = vortex_array.dtype().clone();
// Create a stream adapter
let stream = ArrayStreamAdapter::new(
dtype,
futures::stream::iter(std::iter::once(Ok(vortex_array))),
);
// Write to a buffer
let mut buf: Vec<u8> = Vec::new();
info!("...writing {table_type} batches to vortex format");
VortexWriteOptions::default()
.write(&mut buf, stream)
.await
.map_err(|e| eyre::Error::msg(format!("Failed to write Vortex file: {}", e)))?;
let file_path = object_store::path::Path::from_url_path(file_url.path())?;
info!("...putting to file path {}", file_path);
store.put(&file_path, buf.into()).await?;
Ok(())
}
async fn write_batches<I>(
batches: std::iter::Peekable<I>,
table_path: &Url,
table_type: &str,
store: Arc<dyn ObjectStore>,
format: &TpchFormat,
) -> Result<()>
where
I: Iterator<Item = RecordBatch>,
{
match format {
TpchFormat::Parquet => {
write_batches_to_parquet(batches, table_path, table_type, store).await
}
#[cfg(feature = "vortex")]
TpchFormat::Vortex => write_batches_to_vortex(batches, table_path, table_type, store).await,
}
}
pub async fn generate(config: AppConfig, scale_factor: f64, format: TpchFormat) -> Result<()> {
let merged_exec_config = merge_configs(config.shared.clone(), config.cli.execution.clone());
let session_state_builder = DftSessionStateBuilder::try_new(Some(merged_exec_config.clone()))?
.with_extensions()
.await?;
let session_state = session_state_builder.build()?;
let execution_ctx = ExecutionContext::try_new(
&merged_exec_config,
session_state,
crate::APP_NAME,
env!("CARGO_PKG_VERSION"),
)?;
let tables_path = config.db.path.join("tables")?;
let tables_url = ListingTableUrl::parse(tables_path)?;
let store_url = tables_url.object_store();
let store = execution_ctx
.session_ctx()
.runtime_env()
.object_store(store_url)?;
info!("configured db store: {store:?}");
info!("generating TPC-H data");
let table_paths = create_tpch_dirs(&config)?;
for (table, table_path) in table_paths {
match table {
GeneratorType::Customer => {
info!("...generating customers");
let arrow_generator =
CustomerArrow::new(CustomerGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Customer",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::Order => {
info!("...generating orders");
let arrow_generator = OrderArrow::new(OrderGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Order",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::LineItem => {
info!("...generating LineItems");
let arrow_generator =
LineItemArrow::new(LineItemGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"LineItem",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::Nation => {
info!("...generating Nations");
let arrow_generator = NationArrow::new(NationGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Nation",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::Part => {
info!("...generating Parts");
let arrow_generator = PartArrow::new(PartGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Part",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::PartSupp => {
info!("...generating PartSupps");
let arrow_generator =
PartSuppArrow::new(PartSuppGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"PartSupp",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::Region => {
info!("...generating Regions");
let arrow_generator = RegionArrow::new(RegionGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Region",
Arc::clone(&store),
&format,
)
.await?;
}
GeneratorType::Supplier => {
info!("...generating Suppliers");
let arrow_generator =
SupplierArrow::new(SupplierGenerator::new(scale_factor, 1, 1));
write_batches(
arrow_generator.peekable(),
&table_path,
"Supplier",
Arc::clone(&store),
&format,
)
.await?;
}
}
}
let tpch_dir = config
.db
.path
.join("tables/")?
.join("dft/")?
.join("tpch/")?;
println!("TPC-H dataset saved to: {}", tpch_dir);
Ok(())
}