-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.rs
More file actions
1382 lines (1303 loc) · 53.6 KB
/
utils.rs
File metadata and controls
1382 lines (1303 loc) · 53.6 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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::models::QueryResult;
use crate::error::{ArrowSnafu, CantCastToSnafu, Result};
#[cfg(not(feature = "rest-catalog"))]
use aws_config::timeout::TimeoutConfigBuilder;
use catalog::catalog_list::CatalogListConfig;
use catalog_metastore::SchemaIdent as MetastoreSchemaIdent;
use catalog_metastore::TableIdent as MetastoreTableIdent;
use chrono::{DateTime, FixedOffset, Offset, TimeZone};
use clap::ValueEnum;
use datafusion::arrow::array::timezone::Tz;
use datafusion::arrow::array::{
Array, Decimal128Array, Int16Array, Int32Array, Int64Array, StringArray, StringBuilder,
StructArray, Time32MillisecondArray, Time32SecondArray, Time64MicrosecondArray,
Time64NanosecondArray, TimestampMicrosecondArray, TimestampMillisecondArray,
TimestampNanosecondArray, TimestampSecondArray, UInt8Array, UInt16Array, UInt32Array,
UInt64Array, UnionArray,
};
use datafusion::arrow::array::{ArrayRef, Date32Array, Date64Array};
use datafusion::arrow::compute::cast;
use datafusion::arrow::datatypes::DataType;
use datafusion::arrow::datatypes::{Field, Schema, TimeUnit};
use datafusion::arrow::error::ArrowError;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::ScalarValue;
use datafusion_common::{ResolvedTableReference, TableReference};
use datafusion_expr::{Expr, LogicalPlan};
use functions::conversion::to_timestamp::parse_timezone;
use snafu::{OptionExt, ResultExt};
use sqlparser::ast::{Ident, ObjectName};
use std::collections::HashMap;
use std::sync::Arc;
use strum::{Display, EnumString};
#[derive(Clone, Debug)]
pub struct Config {
pub embucket_version: String,
pub build_version: String,
pub warehouse_type: String,
pub sql_parser_dialect: Option<String>,
pub query_timeout_secs: u64,
pub max_concurrency_level: usize,
pub mem_pool_type: MemPoolType,
pub mem_pool_size_mb: Option<usize>,
pub mem_enable_track_consumers_pool: Option<bool>,
pub disk_pool_size_mb: Option<usize>,
pub max_concurrent_table_fetches: usize,
#[cfg(not(feature = "rest-catalog"))]
pub aws_sdk_connect_timeout_secs: u64,
#[cfg(not(feature = "rest-catalog"))]
pub aws_sdk_operation_timeout_secs: u64,
#[cfg(not(feature = "rest-catalog"))]
pub aws_sdk_operation_attempt_timeout_secs: u64,
pub iceberg_table_timeout_secs: u64,
pub iceberg_catalog_timeout_secs: u64,
}
impl From<&Config> for CatalogListConfig {
fn from(value: &Config) -> Self {
Self {
max_concurrent_table_fetches: value.max_concurrent_table_fetches,
#[cfg(not(feature = "rest-catalog"))]
aws_sdk_timeout_config: TimeoutConfigBuilder::default()
.connect_timeout(std::time::Duration::from_secs(
value.aws_sdk_connect_timeout_secs,
))
.operation_timeout(std::time::Duration::from_secs(
value.aws_sdk_operation_timeout_secs,
))
.operation_attempt_timeout(std::time::Duration::from_secs(
value.aws_sdk_operation_attempt_timeout_secs,
)),
iceberg_table_timeout_secs: value.iceberg_table_timeout_secs,
iceberg_catalog_timeout_secs: value.iceberg_catalog_timeout_secs,
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
embucket_version: "0.1.0".to_string(),
build_version: "test-version".to_string(),
warehouse_type: "DEFAULT".to_string(),
sql_parser_dialect: None,
query_timeout_secs: 1200, // 20 minutes
max_concurrency_level: 100,
mem_pool_type: MemPoolType::default(),
mem_pool_size_mb: None,
mem_enable_track_consumers_pool: None,
disk_pool_size_mb: None,
max_concurrent_table_fetches: 5,
#[cfg(not(feature = "rest-catalog"))]
aws_sdk_connect_timeout_secs: 5,
#[cfg(not(feature = "rest-catalog"))]
aws_sdk_operation_timeout_secs: 30,
#[cfg(not(feature = "rest-catalog"))]
aws_sdk_operation_attempt_timeout_secs: 10,
iceberg_table_timeout_secs: 30,
iceberg_catalog_timeout_secs: 10,
}
}
}
impl Config {
#[must_use]
pub const fn with_max_concurrency_level(mut self, level: usize) -> Self {
self.max_concurrency_level = level;
self
}
#[must_use]
pub const fn with_query_timeout(mut self, timeout_secs: u64) -> Self {
self.query_timeout_secs = timeout_secs;
self
}
}
#[derive(Copy, Clone, PartialEq, Eq, EnumString, Debug, Display, Default)]
#[strum(ascii_case_insensitive)]
pub enum DataSerializationFormat {
Arrow,
#[default]
Json,
}
/// Memory pool type for query execution.
///
/// - `Fair`: Enforces fair memory usage across all consumers, with spill-based control.
/// Suitable for concurrent workloads where no single query should dominate memory resources.
///
/// - `Greedy`: Allows aggressive memory consumption up to the limit.
/// Once the pool is full, all consumers are blocked until memory is freed.
/// Suitable for simpler or single-query workloads.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Default)]
pub enum MemPoolType {
/// Enforces fair memory usage across all consumers.
/// Spills memory from large consumers to maintain fairness.
Fair,
/// Allows each consumer to use memory freely until the pool is exhausted.
/// All consumers are blocked when the memory limit is reached.
#[default]
Greedy,
}
#[must_use]
pub fn is_logical_plan_effectively_empty(plan: &LogicalPlan) -> bool {
match plan {
LogicalPlan::EmptyRelation(e) => !e.produce_one_row,
LogicalPlan::Projection(proj) => is_logical_plan_effectively_empty(&proj.input),
LogicalPlan::SubqueryAlias(alias) => is_logical_plan_effectively_empty(&alias.input),
LogicalPlan::Filter(filter) => {
let is_false_predicate = matches!(
filter.predicate,
Expr::Literal(ScalarValue::Boolean(Some(false)), _)
);
is_false_predicate || is_logical_plan_effectively_empty(&filter.input)
}
_ => false,
}
}
/*#[async_trait::async_trait]
pub trait S3ClientValidation: Send + Sync {
async fn get_aws_bucket_acl(
&self,
request: GetBucketAclRequest,
) -> ControlPlaneResult<GetBucketAclOutput>;
}
#[async_trait::async_trait]
impl S3ClientValidation for S3Client {
async fn get_aws_bucket_acl(
&self,
request: GetBucketAclRequest,
) -> ControlPlaneResult<GetBucketAclOutput> {
self.client
.get_bucket_acl(request)
.await
.map_err(ControlPlaneError::from)
}
}
pub struct S3Client {
client: ExternalS3Client,
}
impl S3Client {
pub fn new(profile: &StorageProfile) -> ControlPlaneResult<Self> {
if let Some(credentials) = profile.credentials.clone() {
match credentials {
Credentials::AccessKey(creds) => {
let profile_region = profile.region.clone().unwrap_or_default();
let credentials = StaticProvider::new_minimal(
creds.aws_access_key_id.clone(),
creds.aws_secret_access_key,
);
let region = Region::Custom {
name: profile_region.clone(),
endpoint: profile.endpoint.clone().unwrap_or_else(|| {
format!("https://s3.{profile_region}.amazonaws.com")
}),
};
let dispatcher =
HttpClient::new().context(crate::error::InvalidTLSConfigurationSnafu)?;
Ok(Self {
client: ExternalS3Client::new_with(dispatcher, credentials, region),
})
}
Credentials::Role(_) => Err(ControlPlaneError::UnsupportedAuthenticationMethod {
method: credentials.to_string(),
}),
}
} else {
Err(ControlPlaneError::InvalidCredentials)
}
}
}*/
#[must_use]
pub fn first_non_empty_type(union_array: &UnionArray) -> Option<(DataType, ArrayRef)> {
for i in 0..union_array.type_ids().len() {
let type_id = union_array.type_id(i);
let child = union_array.child(type_id);
if !child.is_empty() {
return Some((child.data_type().clone(), Arc::clone(child)));
}
}
None
}
#[allow(clippy::too_many_lines)]
pub fn convert_record_batches(
query_result: &QueryResult,
data_format: DataSerializationFormat,
) -> Result<Vec<RecordBatch>> {
let mut converted_batches = Vec::new();
let column_infos = query_result.column_info();
for batch in &query_result.records {
let mut columns = Vec::new();
let mut fields = Vec::new();
for (i, column) in batch.columns().iter().enumerate() {
let metadata = column_infos[i].to_metadata();
let field = batch.schema().field(i).clone();
let converted_column = match field.data_type() {
DataType::Union(..) => {
if let Some(union_array) = column.as_any().downcast_ref::<UnionArray>() {
if let Some((data_type, array)) = first_non_empty_type(union_array) {
fields.push(
Field::new(field.name(), data_type, field.is_nullable())
.with_metadata(metadata),
);
array
} else {
fields.push(field.with_metadata(metadata));
Arc::clone(column)
}
} else {
fields.push(field.with_metadata(metadata));
Arc::clone(column)
}
}
DataType::Timestamp(unit, tz) => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
Ok(convert_timestamp(col, *unit, tz.clone(), data_format))
})?
}
DataType::Date32 | DataType::Date64 => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
Ok(convert_date(col, data_format))
})?
}
DataType::Time32(unit) | DataType::Time64(unit) => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
Ok(convert_time(col, *unit, data_format))
})?
}
DataType::UInt64 | DataType::UInt32 | DataType::UInt16 | DataType::UInt8 => {
let column_info = &column_infos[i];
convert_uint_to_int_datatypes(
&mut fields,
&field,
column,
metadata,
data_format,
(
column_info.precision.unwrap_or(38),
column_info.scale.unwrap_or(0),
),
)
}
DataType::BinaryView | DataType::Utf8View => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
cast(col, &DataType::Utf8).context(ArrowSnafu)
})?
}
DataType::Decimal128(_, _) => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
if data_format == DataSerializationFormat::Json {
Ok(cast(&col, &DataType::Utf8).context(ArrowSnafu)?)
} else {
Ok(Arc::clone(column))
}
})?
}
DataType::Boolean => {
convert_and_push(column, &field, metadata, &mut fields, |col| {
if data_format == DataSerializationFormat::Json {
Ok(to_utf8_array(col, true)?)
} else {
Ok(Arc::clone(column))
}
})?
}
_ => {
fields.push(field.clone().with_metadata(metadata));
Arc::clone(column)
}
};
columns.push(converted_column);
}
let new_schema = Arc::new(Schema::new(fields));
let converted_batch = RecordBatch::try_new(new_schema, columns).context(ArrowSnafu)?;
converted_batches.push(converted_batch);
}
Ok(converted_batches)
}
fn convert_and_push(
column: &ArrayRef,
field: &Field,
metadata: HashMap<String, String>,
fields: &mut Vec<Field>,
convert_fn: impl Fn(&ArrayRef) -> Result<ArrayRef>,
) -> Result<ArrayRef> {
let converted = convert_fn(column)?;
fields.push(
Field::new(
field.name(),
converted.data_type().clone(),
field.is_nullable(),
)
.with_metadata(metadata),
);
Ok(Arc::clone(&converted))
}
macro_rules! downcast_and_iter {
($column:expr, $array_type:ty) => {
$column
.as_any()
.downcast_ref::<$array_type>()
.unwrap()
.into_iter()
};
}
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
fn convert_timestamp(
column: &ArrayRef,
unit: TimeUnit,
tz: Option<Arc<str>>,
data_format: DataSerializationFormat,
) -> ArrayRef {
match data_format {
DataSerializationFormat::Arrow => convert_timestamp_to_struct(column, unit),
DataSerializationFormat::Json => {
// When serializing to JSON, if a timezone is present we encode it as an offset in minutes
// relative to UTC. Chrono returns this as a signed number (e.g. -120 for UTC-2).
// To make the value non-negative (required by Snowflake's encoding), we normalize it by
// adding 1440 (the number of minutes in a day).
// On deserialization, the Snowflake Python connector’s _TIMESTAMP_TZ_to_python reverses
// this normalization by subtracting 1440, restoring the original signed offset.
let tz_encoded = encode_tz(tz);
let timestamps: Vec<_> = match unit {
TimeUnit::Second => downcast_and_iter!(column, TimestampSecondArray)
.map(|x| {
x.map(|ts| {
let ts = DateTime::from_timestamp(ts, 0).unwrap_or_default();
match tz_encoded {
Some(tz) => format!("{} {}", ts.timestamp(), tz),
None => format!("{}", ts.timestamp()),
}
})
})
.collect(),
TimeUnit::Millisecond => downcast_and_iter!(column, TimestampMillisecondArray)
.map(|x| {
x.map(|ts| {
let ts = DateTime::from_timestamp_millis(ts).unwrap_or_default();
match tz_encoded {
Some(tz) => format!(
"{}.{} {}",
ts.timestamp(),
ts.timestamp_subsec_millis(),
tz
),
None => {
format!("{}.{}", ts.timestamp(), ts.timestamp_subsec_millis())
}
}
})
})
.collect(),
TimeUnit::Microsecond => downcast_and_iter!(column, TimestampMicrosecondArray)
.map(|x| {
x.map(|ts| {
let ts = DateTime::from_timestamp_micros(ts).unwrap_or_default();
match tz_encoded {
Some(tz) => format!(
"{}.{} {}",
ts.timestamp(),
ts.timestamp_subsec_micros(),
tz
),
None => {
format!("{}.{}", ts.timestamp(), ts.timestamp_subsec_micros())
}
}
})
})
.collect(),
TimeUnit::Nanosecond => downcast_and_iter!(column, TimestampNanosecondArray)
.map(|x| {
x.map(|ts| {
let ts = DateTime::from_timestamp_nanos(ts);
match tz_encoded {
Some(tz) => format!(
"{}.{} {}",
ts.timestamp(),
ts.timestamp_subsec_nanos(),
tz
),
None => {
format!("{}.{}", ts.timestamp(), ts.timestamp_subsec_nanos())
}
}
})
})
.collect(),
};
Arc::new(StringArray::from(timestamps)) as ArrayRef
}
}
}
fn encode_tz(tz: Option<Arc<str>>) -> Option<i32> {
tz.and_then(|t| parse_timezone(&t))
.map(|off| off.local_minus_utc() / 60 + 1440)
}
#[allow(clippy::as_conversions)]
pub fn convert_struct_to_timestamp(records: &Vec<RecordBatch>) -> Result<Vec<RecordBatch>> {
let mut converted_batches = Vec::new();
for batch in records {
let mut columns = Vec::new();
let mut fields = Vec::new();
for (i, column) in batch.columns().iter().enumerate() {
let field = batch.schema().field(i).clone();
let (field, column) = if let DataType::Struct(fields_in_struct) = field.data_type() {
let has_epoch = fields_in_struct.iter().any(|f| f.name() == "epoch");
let has_fraction = fields_in_struct.iter().any(|f| f.name() == "fraction");
if has_epoch && has_fraction {
let struct_array = column
.as_any()
.downcast_ref::<StructArray>()
.context(CantCastToSnafu { v: "struct_array" })?;
let epoch_col = struct_array
.column_by_name("epoch")
.and_then(|c| c.as_any().downcast_ref::<Int64Array>())
.context(CantCastToSnafu { v: "int64_array" })?;
let fraction_col = struct_array
.column_by_name("fraction")
.and_then(|c| c.as_any().downcast_ref::<Int32Array>())
.context(CantCastToSnafu { v: "int32_array" })?;
let tz_col = struct_array
.column_by_name("timezone")
.and_then(|c| c.as_any().downcast_ref::<Int32Array>());
let ts_string_col = build_timestamp_strings(epoch_col, fraction_col, tz_col)?;
let ts_field = Field::new(field.name(), DataType::Utf8, true);
let column = Arc::new(ts_string_col) as ArrayRef;
(ts_field, column)
} else {
(field.clone(), Arc::clone(column))
}
} else {
(field.clone(), Arc::clone(column))
};
fields.push(field);
columns.push(column);
}
let new_schema = Arc::new(Schema::new(fields));
let converted_batch = RecordBatch::try_new(new_schema, columns).context(ArrowSnafu)?;
converted_batches.push(converted_batch);
}
Ok(converted_batches)
}
#[allow(clippy::as_conversions)]
fn build_timestamp_strings(
epochs: &Int64Array,
fractions: &Int32Array,
tz_col: Option<&Int32Array>,
) -> Result<StringArray> {
let mut builder = StringBuilder::new();
for i in 0..epochs.len() {
if epochs.is_null(i) || fractions.is_null(i) {
builder.append_null();
continue;
}
let epoch = epochs.value(i);
let fraction = i64::from(fractions.value(i));
let dt = DateTime::from_timestamp_nanos(epoch * 1_000_000_000 + fraction);
let dt_str = if let Some(tz) = tz_col {
let offset_minutes = tz.value(i);
let offset = FixedOffset::east_opt((offset_minutes - 1440) * 60)
.or_else(|| FixedOffset::east_opt(0)) // 0 fallback for invalid offsets
.context(CantCastToSnafu { v: "fixed_offset" })?;
dt.with_timezone(&offset).to_rfc3339()
} else {
dt.to_rfc3339()
};
builder.append_value(dt_str);
}
Ok(builder.finish())
}
#[allow(clippy::as_conversions, clippy::cast_sign_loss)]
fn convert_timestamp_to_struct(column: &ArrayRef, unit: TimeUnit) -> ArrayRef {
// For non-empty timezone we should return a struct with epoch, fraction and timezone.
// For empty timezone we should return int64 timestamp array in units.
let DataType::Timestamp(_, Some(tz)) = column.data_type() else {
let timestamps: Vec<_> = match unit {
TimeUnit::Second => downcast_and_iter!(column, TimestampSecondArray).collect(),
TimeUnit::Millisecond => {
downcast_and_iter!(column, TimestampMillisecondArray).collect()
}
TimeUnit::Microsecond => {
downcast_and_iter!(column, TimestampMicrosecondArray).collect()
}
TimeUnit::Nanosecond => downcast_and_iter!(column, TimestampNanosecondArray).collect(),
};
return Arc::new(Int64Array::from(timestamps)) as ArrayRef;
};
let ts_array = to_nanoseconds(column, unit);
let epochs: Int64Array = ts_array
.iter()
.map(|opt_nanos| opt_nanos.map(|nanos| nanos / 1_000_000_000))
.collect();
let fractions: Int32Array = ts_array
.iter()
.map(|opt_nanos| opt_nanos.map(|nanos| (nanos % 1_000_000_000) as i32))
.collect();
let tz_arr: Int32Array = ts_array
.iter()
.map(|opt_nanos| opt_nanos.map(|nanos| tz_to_i32(tz, nanos)))
.collect();
let struct_fields: Vec<(Arc<Field>, ArrayRef)> = vec![
(
Arc::new(Field::new("epoch", DataType::Int64, true)),
Arc::new(epochs) as ArrayRef,
),
(
Arc::new(Field::new("fraction", DataType::Int32, true)),
Arc::new(fractions) as ArrayRef,
),
(
Arc::new(Field::new("timezone", DataType::Int32, true)),
Arc::new(tz_arr) as ArrayRef,
),
];
let struct_array = StructArray::from(struct_fields);
Arc::new(struct_array)
}
fn tz_to_i32(tz_str: &str, nanos: i64) -> i32 {
if nanos == 0 {
return 1440;
}
let secs = nanos / 1_000_000_000;
let nanos = u32::try_from(nanos % 1_000_000_000).unwrap_or(0); // Handle overflow gracefully, default to 0
let Some(dt) = DateTime::from_timestamp(secs, nanos) else {
return 1440;
};
tz_str.parse::<Tz>().map_or_else(
|_| 1440,
|tz| {
tz.offset_from_utc_datetime(&dt.naive_utc())
.fix()
.local_minus_utc()
/ 60
+ 1440
},
)
}
fn to_nanoseconds(column: &ArrayRef, unit: TimeUnit) -> TimestampNanosecondArray {
match unit {
TimeUnit::Second => downcast_and_iter!(column, TimestampSecondArray)
.map(|opt| opt.map(|v| v * 1_000_000_000))
.collect(),
TimeUnit::Millisecond => downcast_and_iter!(column, TimestampMillisecondArray)
.map(|opt| opt.map(|v| v * 1_000_000))
.collect(),
TimeUnit::Microsecond => downcast_and_iter!(column, TimestampMicrosecondArray)
.map(|opt| opt.map(|v| v * 1_000))
.collect(),
TimeUnit::Nanosecond => downcast_and_iter!(column, TimestampNanosecondArray).collect(),
}
}
#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
fn convert_date(column: &ArrayRef, data_format: DataSerializationFormat) -> ArrayRef {
match data_format {
DataSerializationFormat::Json => {
let days: Vec<Option<i32>> = match column.data_type() {
DataType::Date32 => downcast_and_iter!(column, Date32Array).collect(),
DataType::Date64 => downcast_and_iter!(column, Date64Array)
.map(|ms| ms.map(|v| (v / 86_400_000) as i32))
.collect(),
_ => return column.clone(),
};
Arc::new(Int32Array::from(days)) as ArrayRef
}
DataSerializationFormat::Arrow => column.clone(),
}
}
#[allow(
clippy::cast_lossless,
clippy::unwrap_used,
clippy::as_conversions,
clippy::cast_possible_truncation,
clippy::cast_sign_loss
)]
fn convert_uint_to_int_datatypes(
fields: &mut Vec<Field>,
field: &Field,
column: &ArrayRef,
metadata: HashMap<String, String>,
data_format: DataSerializationFormat,
precision_scale: (i32, i32),
) -> ArrayRef {
match data_format {
DataSerializationFormat::Arrow => {
match field.data_type() {
DataType::UInt64 => {
fields.push(
Field::new(
field.name(),
DataType::Decimal128(precision_scale.0 as u8, precision_scale.1 as i8),
field.is_nullable(),
)
.with_metadata(metadata),
);
// converted_column
Arc::new(
Decimal128Array::from_unary(
column.as_any().downcast_ref::<UInt64Array>().unwrap(),
|x| x as i128,
)
.with_precision_and_scale(38, 0)
.unwrap(),
)
}
DataType::UInt32 => {
fields.push(
Field::new(field.name(), DataType::Int64, field.is_nullable())
.with_metadata(metadata),
);
// converted_column
Arc::new(Int64Array::from_unary(
column.as_any().downcast_ref::<UInt32Array>().unwrap(),
|x| x as i64,
))
}
DataType::UInt16 => {
fields.push(
Field::new(field.name(), DataType::Int32, field.is_nullable())
.with_metadata(metadata),
);
// converted_column
Arc::new(Int32Array::from_unary(
column.as_any().downcast_ref::<UInt16Array>().unwrap(),
|x| x as i32,
))
}
DataType::UInt8 => {
fields.push(
Field::new(field.name(), DataType::Int16, field.is_nullable())
.with_metadata(metadata),
);
// converted_column
Arc::new(Int16Array::from_unary(
column.as_any().downcast_ref::<UInt8Array>().unwrap(),
|x| x as i16,
))
}
_ => {
fields.push(field.clone().with_metadata(metadata));
Arc::clone(column)
}
}
}
DataSerializationFormat::Json => {
fields.push(field.clone().with_metadata(metadata));
Arc::clone(column)
}
}
}
#[allow(clippy::as_conversions)]
fn convert_time(
column: &ArrayRef,
unit: TimeUnit,
data_format: DataSerializationFormat,
) -> ArrayRef {
match data_format {
DataSerializationFormat::Json => {
let time: Vec<_> = match unit {
TimeUnit::Second => downcast_and_iter!(column, Time32SecondArray)
.map(|time| {
time.map(|ts| {
let ts = DateTime::from_timestamp(i64::from(ts), 0).unwrap_or_default();
//Snow sql expects value where `time = float(value[0 : -scale + 6])`
// `scale` for some reason by default is 9 (nanos)
// if we don't add this, time truncation is incorrect
// for any time function with seconds
format_time_string(ts.timestamp(), "000", 0)
})
})
.collect(),
TimeUnit::Millisecond => downcast_and_iter!(column, Time32MillisecondArray)
.map(|time| {
time.map(|ts| {
let ts =
DateTime::from_timestamp_millis(i64::from(ts)).unwrap_or_default();
//If millis == 0, 4 zeroes after the `.` instead of 3
format_time_string(ts.timestamp(), ts.timestamp_subsec_millis(), 3)
})
})
.collect(),
TimeUnit::Microsecond => downcast_and_iter!(column, Time64MicrosecondArray)
.map(|time| {
time.map(|ts| {
let ts = DateTime::from_timestamp_micros(ts).unwrap_or_default();
//If micros == 0, 7 zeroes after the `.` instead of 6
format_time_string(ts.timestamp(), ts.timestamp_subsec_micros(), 6)
})
})
.collect(),
TimeUnit::Nanosecond => downcast_and_iter!(column, Time64NanosecondArray)
.map(|time| {
time.map(|ts| {
let ts = DateTime::from_timestamp_nanos(ts);
//If nanos == 0, 10 zeroes after the `.` instead of 9
format_time_string(ts.timestamp(), ts.timestamp_subsec_nanos(), 9)
})
})
.collect(),
};
Arc::new(StringArray::from(time)) as ArrayRef
}
DataSerializationFormat::Arrow => {
let timestamps: Vec<_> = match unit {
TimeUnit::Second => downcast_and_iter!(column, Time32SecondArray)
.map(|ts| ts.map(i64::from))
.collect(),
TimeUnit::Millisecond => downcast_and_iter!(column, Time32MillisecondArray)
.map(|ts| ts.map(i64::from))
.collect(),
TimeUnit::Microsecond => {
downcast_and_iter!(column, Time64MicrosecondArray).collect()
}
TimeUnit::Nanosecond => downcast_and_iter!(column, Time64NanosecondArray).collect(),
};
Arc::new(Int64Array::from(timestamps)) as ArrayRef
}
}
}
fn to_utf8_array(array: &ArrayRef, upper_case: bool) -> Result<ArrayRef> {
let casted = cast(array, &DataType::Utf8).context(ArrowSnafu)?;
let utf8_array = casted
.as_any()
.downcast_ref::<StringArray>()
.ok_or_else(|| ArrowError::InvalidArgumentError("expected Utf8 array".into()))
.context(ArrowSnafu)?;
let mut builder = StringBuilder::new();
for i in 0..utf8_array.len() {
if utf8_array.is_null(i) {
builder.append_null();
} else {
let s = if upper_case {
utf8_array.value(i).to_ascii_uppercase()
} else {
utf8_array.value(i).to_string()
};
builder.append_value(&s);
}
}
Ok(Arc::new(builder.finish()))
}
/// Formats the timestamp and subsecond part into a string with the given scale.
/// `scale` is the number of digits to pad the subsecond value to.
fn format_time_string<T: std::fmt::Display>(timestamp: i64, subsecond: T, scale: usize) -> String {
let sub_str = subsecond.to_string();
let zeroes = scale.saturating_sub(sub_str.len());
format!("{timestamp}.{:0>zeroes$}{sub_str}", "")
}
#[derive(Debug, Clone)]
pub struct NormalizedIdent(pub Vec<Ident>);
impl NormalizedIdent {
#[must_use]
pub fn from_resolved(resolved: &ResolvedTableReference) -> Self {
Self(vec![
Ident::new(resolved.catalog.as_ref()),
Ident::new(resolved.schema.as_ref()),
Ident::new(resolved.table.as_ref()),
])
}
}
impl From<&NormalizedIdent> for String {
fn from(ident: &NormalizedIdent) -> Self {
ident
.0
.iter()
.map(|i| i.value.clone())
.collect::<Vec<_>>()
.join(".")
}
}
impl From<NormalizedIdent> for MetastoreTableIdent {
fn from(ident: NormalizedIdent) -> Self {
let ident = ident.0;
// TODO check len, return err. This code is just tmp
Self {
table: ident[2].value.clone(),
schema: ident[1].value.clone(),
database: ident[0].value.clone(),
}
}
}
impl From<NormalizedIdent> for MetastoreSchemaIdent {
fn from(ident: NormalizedIdent) -> Self {
let ident = ident.0;
Self {
schema: ident[1].value.clone(),
database: ident[0].value.clone(),
}
}
}
impl From<NormalizedIdent> for ObjectName {
fn from(ident: NormalizedIdent) -> Self {
Self::from(ident.0)
}
}
impl From<&NormalizedIdent> for TableReference {
fn from(ident: &NormalizedIdent) -> Self {
Self::parse_str(&String::from(ident))
}
}
impl std::fmt::Display for NormalizedIdent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from(self))
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::as_conversions, clippy::expect_used)]
mod tests {
use super::*;
use crate::models::ColumnInfo;
use datafusion::arrow::array::{
ArrayRef, BooleanArray, Float64Array, Int32Array, TimestampSecondArray, UInt64Array,
UnionArray,
};
use datafusion::arrow::array::{BinaryViewArray, StringViewArray};
use datafusion::arrow::buffer::ScalarBuffer;
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::arrow::record_batch::RecordBatch;
use functions::datetime::timestamp_from_parts::make_time;
use std::sync::Arc;
#[test]
fn test_first_non_empty_type() {
let int_array = Int32Array::from(vec![Some(1), None, Some(34)]);
let float_array = Float64Array::from(vec![None, Some(3.2), None]);
let type_ids = [0_i8, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
let union_fields = [
(0, Arc::new(Field::new("A", DataType::Int32, false))),
(1, Arc::new(Field::new("B", DataType::Float64, false))),
]
.into_iter()
.collect();
let children = vec![Arc::new(int_array) as ArrayRef, Arc::new(float_array)];
let union_array = UnionArray::try_new(union_fields, type_ids, None, children)
.expect("Failed to create UnionArray");
let result = first_non_empty_type(&union_array);
assert!(result.is_some());
let (data_type, array) = result.unwrap();
assert_eq!(data_type, DataType::Int32);
assert_eq!(array.len(), 3);
}
#[test]
fn test_convert_timestamp() {
let cases = [
(
TimeUnit::Second,
Some(1_627_846_261),
"1627846261",
None,
(1_627_846_261, 0, 1_627_846_261),
),
(
TimeUnit::Millisecond,
Some(1_627_846_261_233),
"1627846261.233",
None,
(1_627_846_261, 233_000_000, 1_627_846_261_233),
),
(
TimeUnit::Microsecond,
Some(1_627_846_261_233_222),
"1627846261.233222",
None,
(1_627_846_261, 233_222_000, 1_627_846_261_233_222),
),
(
TimeUnit::Nanosecond,
Some(1_627_846_261_233_222_111),
"1627846261.233222111 1440",
Some("UTC".to_string()),
(1_627_846_261, 233_222_111, 1_627_846_261_233_222_111),
),
];
for (unit, timestamp, expected_json, tz, (epoch, fraction, ar)) in &cases {
let values = vec![*timestamp, None];
let timestamp_array =
match unit {
TimeUnit::Second => {
Arc::new(TimestampSecondArray::from(values).with_timezone_opt(tz.clone()))
as ArrayRef
}
TimeUnit::Millisecond => Arc::new(
TimestampMillisecondArray::from(values).with_timezone_opt(tz.clone()),
) as ArrayRef,
TimeUnit::Microsecond => Arc::new(
TimestampMicrosecondArray::from(values).with_timezone_opt(tz.clone()),
) as ArrayRef,
TimeUnit::Nanosecond => Arc::new(
TimestampNanosecondArray::from(values).with_timezone_opt(tz.clone()),
) as ArrayRef,
};
let tz = tz.as_ref().map(|s| Arc::from(s.as_str()));
let result = convert_timestamp(
×tamp_array,
*unit,
tz.clone(),
DataSerializationFormat::Json,
);
let string_array = result.as_any().downcast_ref::<StringArray>().unwrap();
assert_eq!(string_array.len(), 2);
assert_eq!(string_array.value(0), *expected_json);
assert!(string_array.is_null(1));
let result = convert_timestamp(
×tamp_array,
*unit,
tz.clone(),
DataSerializationFormat::Arrow,
);
if tz.is_some() {
let struct_array = result.as_any().downcast_ref::<StructArray>().unwrap();
let epoch_array = struct_array
.column_by_name("epoch")
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()