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
use std::sync::Arc;
use async_trait::async_trait;
use log::debug;
use sqlparser::ast::{Expr, Query, SelectItem, SetExpr, Statement};
use sqlparser::dialect::GenericDialect;
use sqlparser::parser::Parser;
use crate::table::object_store::table_from_list_bucket;
use crate::utils::uri_parse::ParsedUri;
use crate::{
BinaryCallbackWrapper, EnvironmentConfig, FileObjectFilter,
LakestreamError, ObjectStore, ObjectStoreTable, Table, TableCallback,
};
#[derive(Clone)]
pub struct ObjectStoreHandler {}
impl ObjectStoreHandler {
pub fn new(_configs: Option<Vec<EnvironmentConfig>>) -> Self {
// creating with config will be used in future
ObjectStoreHandler {}
}
pub async fn list_objects(
&self,
uri: &str,
config: &EnvironmentConfig,
selected_columns: Option<Vec<&str>>,
recursive: bool,
max_files: Option<u32>,
filter: &Option<FileObjectFilter>,
callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
let parsed_uri = ParsedUri::from_uri(uri, true);
if let Some(bucket) = &parsed_uri.bucket {
// list files in a bucket
debug!("Listing files in bucket {}", bucket);
let table = self
.list_files_in_bucket(
parsed_uri, // FROM
config.clone(),
&selected_columns, // SELECT
recursive, // true in case Query is used
max_files, // LIMIT
filter, // WHERE
callback, // callback is a custom function
// applied to what gets selected (via ROW addition)
)
.await?;
Ok(table)
} else {
if let Some(scheme) = &parsed_uri.scheme {
if scheme == "s3" {
debug!("Listing buckets on S3");
return self
.list_buckets(
uri,
config,
&selected_columns,
max_files,
callback,
)
.await;
}
}
Err(LakestreamError::NoBucketInUri(uri.to_string()))
}
}
pub async fn list_buckets(
&self,
uri: &str,
config: &EnvironmentConfig,
selected_columns: &Option<Vec<&str>>,
max_files: Option<u32>,
callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
let parsed_uri = ParsedUri::from_uri(uri, true);
if let Some(_) = &parsed_uri.bucket {
return Err(LakestreamError::NoBucketInUri(uri.to_string()));
}
// Clone the original config and update the settings
let mut updated_config = config.clone();
updated_config.set(
"uri".to_string(),
format!("{}://", parsed_uri.scheme.unwrap()),
);
table_from_list_bucket(
updated_config,
selected_columns,
max_files,
callback,
)
.await
}
pub async fn get_object(
&self,
uri: &str,
config: &EnvironmentConfig,
callback: Option<BinaryCallbackWrapper>,
) -> Result<Option<Vec<u8>>, LakestreamError> {
let parsed_uri = ParsedUri::from_uri(uri, false);
if let Some(bucket) = &parsed_uri.bucket {
// Get the object from the bucket
let bucket_uri = if let Some(scheme) = &parsed_uri.scheme {
format!("{}://{}", scheme, bucket)
} else {
format!("localfs://{}", bucket)
};
let key = parsed_uri.path.as_deref().unwrap();
let object_store =
ObjectStore::new(&bucket_uri, config.clone()).unwrap();
// NOTE: initial callback implementation for get_object. In future updates the callback
// mechanism will be pushed to the underlying object store methods, so we can add
// chunking as well for increased performance and ability to handle big files that not
// fit in memory
if let Some(callback) = callback {
let mut data = Vec::new();
object_store.get_object(key, &mut data).await?;
callback.call(data).await?;
Ok(None)
} else {
let mut data = Vec::new();
object_store.get_object(key, &mut data).await?;
Ok(Some(data))
}
} else {
Err(LakestreamError::NoBucketInUri(uri.to_string()))
}
}
async fn list_files_in_bucket(
&self,
parsed_uri: ParsedUri,
config: EnvironmentConfig,
selected_columns: &Option<Vec<&str>>,
recursive: bool,
max_files: Option<u32>,
filter: &Option<FileObjectFilter>,
callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
let bucket_uri = if let Some(scheme) = &parsed_uri.scheme {
format!("{}://{}", scheme, parsed_uri.bucket.as_ref().unwrap())
} else {
format!("localfs://{}", parsed_uri.bucket.as_ref().unwrap())
};
let object_store = ObjectStore::new(&bucket_uri, config).unwrap();
object_store
.list_files(
parsed_uri.path.as_deref(),
selected_columns,
recursive,
max_files,
filter,
callback,
)
.await
}
pub async fn execute_query(
&self,
statement: &str,
config: &EnvironmentConfig,
callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
let dialect = GenericDialect {};
let parsed = Parser::parse_sql(&dialect, statement);
match parsed {
Ok(statements) => {
if let Some(Statement::Query(query)) =
statements.into_iter().next()
{
self.handle_select_statement(&query, config, callback).await
} else {
Err(LakestreamError::InternalError(
"Unsupported query statement".to_string(),
))
}
}
Err(_e) => Err(LakestreamError::InternalError(
"Failed to parse query statement".to_string(),
)),
}
}
async fn handle_select_statement(
&self,
query: &Query,
config: &EnvironmentConfig,
callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
if let SetExpr::Select(select) = &*query.body {
let selected_columns = if select
.projection
.iter()
.any(|item| matches!(item, SelectItem::Wildcard(_)))
{
// wildcard: e.g. SELECT * FROM "uri"
None
} else {
Some(
select
.projection
.iter()
.filter_map(|item| {
match item {
SelectItem::UnnamedExpr(Expr::Identifier(
ident,
)) => Some(ident.value.as_str()), // Directly use the reference
_ => {
log::warn!(
"Skipping non-identifier selection: \
{:?}",
item
);
None
}
}
})
.collect::<Vec<&str>>(),
) // Collect as Vec<&str>
};
if let Some(table) = select.from.first() {
// assume the query is of the form 'SELECT * FROM "uri"'
// TODOs:
// 1. directories vs files
// in this first implementation, everything is treated as a directory,
// while we should distinguish between files and directories
// directories -> call list_objects()
// files -> treat as a database file (e.g. .sql, .parquet)
//
// 2. handle the following SQL clauses:
// non-wildcards in the SELECT statementA, e.g. 'SELECT name, size FROM "uri"'
// WHERE clauses, e.g. 'SELECT * FROM "uri" WHERE size > 100'
// ORDER BY, LIMIT and OFFSET clauses
let mut uri = table.relation.to_string();
// check for and remove leading and trailing quotes
if (uri.starts_with('"') && uri.ends_with('"'))
|| (uri.starts_with('\'') && uri.ends_with('\''))
{
uri = uri[1..uri.len() - 1].to_string(); // Remove the first and last characters
}
// Extract the LIMIT value if present
let limit = match &query.limit {
Some(sqlparser::ast::Expr::Value(
sqlparser::ast::Value::Number(n, _),
)) => n.parse::<u32>().ok(),
_ => None,
};
let result = self
.list_objects(
&uri,
config,
selected_columns,
true,
limit,
&None,
callback.clone(),
)
.await;
match result {
Err(LakestreamError::NoBucketInUri(_)) => {
// uri does not point to a bucket or (virtual) directory
// assume it to be a pointer to a database file (e.g. .sql, .parquet)
return self
.query_object(&uri, config, query, callback)
.await;
}
_ => return result, // TODO: query should return Table
}
}
}
//}
Err(LakestreamError::InternalError(
"Query does not match 'SELECT * FROM uri' pattern".to_string(),
))
}
async fn query_object(
&self,
_uri: &str,
_config: &EnvironmentConfig,
_query: &Query,
_callback: Option<Arc<dyn TableCallback>>,
) -> Result<Box<dyn Table>, LakestreamError> {
// Logic to treat the URI as a database file and query it
// This is a placeholder for the actual implementation.
Err(LakestreamError::InternalError(
"Querying object not implemented".to_string(),
))
}
}
#[async_trait(?Send)]
pub trait ObjectStoreBackend: Send {
fn new(config: EnvironmentConfig) -> Result<Self, LakestreamError>
where
Self: Sized;
async fn list_buckets(
config: EnvironmentConfig,
max_files: Option<u32>,
table: &mut ObjectStoreTable,
) -> Result<(), LakestreamError>;
}