spark_connect_rs/
catalog.rs

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
//! Spark Catalog representation through which the user may create, drop, alter or query underlying databases, tables, functions, etc.

use std::collections::HashMap;

use arrow::array::RecordBatch;

use crate::errors::SparkError;
use crate::plan::LogicalPlanBuilder;
use crate::session::SparkSession;
use crate::storage::StorageLevel;
use crate::types::StructType;
use crate::{spark, DataFrame};

/// User-facing catalog API, accessible through SparkSession.catalog.
#[derive(Debug, Clone)]
pub struct Catalog {
    spark_session: SparkSession,
}

impl Catalog {
    pub fn new(spark_session: SparkSession) -> Self {
        Self { spark_session }
    }

    fn arrow_to_bool(record: RecordBatch) -> Result<bool, SparkError> {
        let col = record.column(0);

        let data: &arrow::array::BooleanArray = match col.data_type() {
            arrow::datatypes::DataType::Boolean => col.as_any().downcast_ref().unwrap(),
            _ => unimplemented!("only Boolean data types are currently handled currently."),
        };

        Ok(data.value(0))
    }

    /// Returns the current default catalog in this session
    pub async fn current_catalog(self) -> Result<String, SparkError> {
        let cat_type = Some(spark::catalog::CatType::CurrentCatalog(
            spark::CurrentCatalog {},
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_first_value(plan).await
    }

    /// Sets the current default catalog in this session
    pub async fn set_current_catalog(self, catalog_name: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::SetCurrentCatalog(
            spark::SetCurrentCatalog {
                catalog_name: catalog_name.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Returns a list of catalogs in this session
    pub async fn list_catalogs(self, pattern: Option<&str>) -> Result<RecordBatch, SparkError> {
        let pattern = pattern.map(|val| val.to_owned());

        let cat_type = Some(spark::catalog::CatType::ListCatalogs(spark::ListCatalogs {
            pattern,
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Returns the current default database in this session
    pub async fn current_database(self) -> Result<String, SparkError> {
        let cat_type = Some(spark::catalog::CatType::CurrentDatabase(
            spark::CurrentDatabase {},
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_first_value(plan).await
    }

    /// Sets the current default database in this session
    pub async fn set_current_database(self, db_name: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::SetCurrentDatabase(
            spark::SetCurrentDatabase {
                db_name: db_name.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Returns a list of databases in this session
    pub async fn list_databases(self, pattern: Option<&str>) -> Result<RecordBatch, SparkError> {
        let pattern = pattern.map(|val| val.to_owned());

        let cat_type = Some(spark::catalog::CatType::ListDatabases(
            spark::ListDatabases { pattern },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Get the database with the specified name
    pub async fn get_database(self, db_name: &str) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::GetDatabase(spark::GetDatabase {
            db_name: db_name.to_string(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Check if the database with the specified name exists.
    pub async fn database_exists(self, db_name: &str) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::DatabaseExists(
            spark::DatabaseExists {
                db_name: db_name.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Returns a list of tables/views in the specific database
    pub async fn list_tables(
        self,
        pattern: Option<&str>,
        db_name: Option<&str>,
    ) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::ListTables(spark::ListTables {
            db_name: db_name.map(|db| db.to_owned()),
            pattern: pattern.map(|val| val.to_owned()),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Get the table or view with the specified name.
    pub async fn get_table(self, table_name: &str) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::GetTable(spark::GetTable {
            table_name: table_name.to_string(),
            db_name: None,
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Returns a list of functions registered in the specified database.
    pub async fn list_functions(
        self,
        db_name: Option<&str>,
        pattern: Option<&str>,
    ) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::ListFunctions(
            spark::ListFunctions {
                db_name: db_name.map(|val| val.to_owned()),
                pattern: pattern.map(|val| val.to_owned()),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Check if the function with the specified name exists.
    pub async fn function_exists(
        self,
        function_name: &str,
        db_name: Option<&str>,
    ) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::FunctionExists(
            spark::FunctionExists {
                function_name: function_name.to_string(),
                db_name: db_name.map(|val| val.to_owned()),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Get the function with the specified name.
    pub async fn get_function(self, function_name: &str) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::GetFunction(spark::GetFunction {
            function_name: function_name.to_string(),
            db_name: None,
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Returns a list of columns for the given tables/views in the specific database
    pub async fn list_columns(
        self,
        table_name: &str,
        db_name: Option<&str>,
    ) -> Result<RecordBatch, SparkError> {
        let cat_type = Some(spark::catalog::CatType::ListColumns(spark::ListColumns {
            table_name: table_name.to_owned(),
            db_name: db_name.map(|val| val.to_owned()),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().to_arrow(plan).await
    }

    /// Check if the table or view with the specified name exists.
    pub async fn table_exists(
        self,
        table_name: &str,
        db_name: Option<&str>,
    ) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::TableExists(spark::TableExists {
            table_name: table_name.to_string(),
            db_name: db_name.map(|val| val.to_owned()),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Drops the local temporary view with the given view name in the catalog.
    pub async fn drop_temp_view(self, view_name: &str) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::DropTempView(spark::DropTempView {
            view_name: view_name.to_string(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Drops the global temporary view with the given view name in the catalog.
    pub async fn drop_global_temp_view(self, view_name: &str) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::DropGlobalTempView(
            spark::DropGlobalTempView {
                view_name: view_name.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Returns true if the table is currently cached in-memory.
    pub async fn is_cached(self, table_name: &str) -> Result<bool, SparkError> {
        let cat_type = Some(spark::catalog::CatType::IsCached(spark::IsCached {
            table_name: table_name.to_string(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        let record = self.spark_session.client().to_arrow(plan).await?;

        Catalog::arrow_to_bool(record)
    }

    /// Creates a table based on the dataset in a data source.
    pub async fn create_table(
        &self,
        table_name: &str,
        path: Option<&str>,
        source: Option<&str>,
        description: Option<&str>,
        schema: Option<StructType>,
        options: Option<HashMap<String, String>>,
    ) -> Result<DataFrame, SparkError> {
        let cat_type = Some(spark::catalog::CatType::CreateTable(spark::CreateTable {
            table_name: table_name.to_string(),
            path: path.map(|p| p.to_string()),
            source: source.map(|s| s.to_string()),
            description: description.map(|d| d.to_string()),
            schema: schema.map(|s| s.into()),
            options: options.unwrap_or_default(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type);

        let df = DataFrame {
            spark_session: Box::new(self.spark_session.clone()),
            plan,
        };

        df.clone().count().await?;

        Ok(df)
    }

    /// Creates a table based on the dataset in a data source.
    pub async fn create_external_table(
        &self,
        table_name: &str,
        path: Option<&str>,
        source: Option<&str>,
        schema: Option<StructType>,
        options: Option<HashMap<String, String>>,
    ) -> Result<DataFrame, SparkError> {
        let cat_type = Some(spark::catalog::CatType::CreateExternalTable(
            spark::CreateExternalTable {
                table_name: table_name.to_string(),
                path: path.map(|p| p.to_string()),
                source: source.map(|s| s.to_string()),
                schema: schema.map(|s| s.into()),
                options: options.unwrap_or_default(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type);

        let df = DataFrame {
            spark_session: Box::new(self.spark_session.clone()),
            plan,
        };

        df.clone().count().await?;

        Ok(df)
    }

    /// Caches the specified table in-memory or with given storage level.
    pub async fn cache_table(
        self,
        table_name: &str,
        storage_level: Option<StorageLevel>,
    ) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::CacheTable(spark::CacheTable {
            table_name: table_name.to_string(),
            storage_level: storage_level.map(|val| val.to_owned().into()),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Removes the specified table from the in-memory cache.
    pub async fn uncache_table(self, table_name: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::UncacheTable(spark::UncacheTable {
            table_name: table_name.to_string(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Removes all cached tables from the in-memory cache.
    pub async fn clear_cache(self) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::ClearCache(spark::ClearCache {}));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Invalidates and refreshes all the cached data (and the associated metadata) for any DataFrame that contains the given data source path.
    pub async fn refresh_table(self, table_name: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::RefreshTable(spark::RefreshTable {
            table_name: table_name.to_string(),
        }));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Recovers all the partitions of the given table and updates the catalog.
    pub async fn recover_partitions(self, table_name: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::RecoverPartitions(
            spark::RecoverPartitions {
                table_name: table_name.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }

    /// Invalidates and refreshes all the cached data (and the associated metadata) for any DataFrame that contains the given data source path.
    pub async fn refresh_by_path(self, path: &str) -> Result<(), SparkError> {
        let cat_type = Some(spark::catalog::CatType::RefreshByPath(
            spark::RefreshByPath {
                path: path.to_string(),
            },
        ));

        let rel_type = spark::relation::RelType::Catalog(spark::Catalog { cat_type });

        let plan = LogicalPlanBuilder::from(rel_type).plan_root();

        self.spark_session.client().execute_command(plan).await
    }
}

#[cfg(test)]
mod tests {

    use crate::types::{DataType, StructField, StructType};
    use std::collections::HashMap;

    use super::*;

    use crate::errors::SparkError;
    use crate::SparkSessionBuilder;

    async fn setup() -> SparkSession {
        println!("SparkSession Setup");

        let connection = "sc://127.0.0.1:15002/;user_id=rust_catalog";

        SparkSessionBuilder::remote(connection)
            .build()
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn test_current_catalog() -> Result<(), SparkError> {
        let spark = setup().await;

        let value = spark.catalog().current_catalog().await?;

        assert_eq!(value, "spark_catalog".to_string());
        Ok(())
    }

    #[tokio::test]
    async fn test_set_current_catalog() -> Result<(), SparkError> {
        let spark = setup().await;

        spark.catalog().set_current_catalog("spark_catalog").await?;

        assert!(true);
        Ok(())
    }

    #[tokio::test]
    #[should_panic]
    async fn test_set_current_catalog_panic() -> () {
        let spark = setup().await;

        spark
            .catalog()
            .set_current_catalog("not_a_real_catalog")
            .await
            .unwrap();

        ()
    }

    #[tokio::test]
    async fn test_list_catalogs() -> Result<(), SparkError> {
        let spark = setup().await;

        let value = spark.catalog().list_catalogs(None).await?;

        assert_eq!(2, value.num_columns());
        assert_eq!(1, value.num_rows());

        Ok(())
    }

    #[tokio::test]
    async fn test_current_database() -> Result<(), SparkError> {
        let spark = setup().await;

        let value = spark.catalog().current_database().await?;

        assert_eq!(value, "default".to_string());
        Ok(())
    }

    #[tokio::test]
    async fn test_set_current_database() -> Result<(), SparkError> {
        let spark = setup().await;

        spark.sql("CREATE SCHEMA current_db").await?;

        spark.catalog().set_current_database("current_db").await?;

        assert!(true);

        spark.sql("DROP SCHEMA current_db").await?;

        Ok(())
    }

    #[tokio::test]
    #[should_panic]
    async fn test_set_current_database_panic() -> () {
        let spark = setup().await;

        spark
            .catalog()
            .set_current_catalog("not_a_real_db")
            .await
            .unwrap();

        ()
    }

    #[tokio::test]
    async fn test_get_database() -> Result<(), SparkError> {
        let spark = setup().await;

        spark.sql("CREATE SCHEMA get_db").await?;

        let res = spark.clone().catalog().get_database("get_db").await?;

        assert_eq!(res.num_rows(), 1);

        spark.sql("DROP SCHEMA get_db").await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_database_exists() -> Result<(), SparkError> {
        let spark = setup().await;

        let res = spark.catalog().database_exists("default").await?;

        assert!(res);

        let res = spark.catalog().database_exists("not_real").await?;

        assert!(!res);
        Ok(())
    }

    #[tokio::test]
    async fn test_function_exists() -> Result<(), SparkError> {
        let spark = setup().await;

        let res = spark.catalog().function_exists("len", None).await?;

        assert!(res);
        Ok(())
    }

    #[tokio::test]
    async fn test_list_columns() -> Result<(), SparkError> {
        let spark = setup().await;

        spark.sql("DROP TABLE IF EXISTS tmp_table").await?;

        spark
            .sql("CREATE TABLE tmp_table (name STRING, age INT) using parquet")
            .await?;

        let res = spark.catalog().list_columns("tmp_table", None).await?;

        assert_eq!(res.num_rows(), 2);

        spark.sql("DROP TABLE IF EXISTS tmp_table").await?;
        Ok(())
    }

    #[tokio::test]
    async fn test_drop_view() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .range(None, 2, 1, Some(1))
            .create_or_replace_global_temp_view("tmp_view")
            .await?;

        let res = spark.catalog().drop_global_temp_view("tmp_view").await?;

        assert!(res);

        spark
            .clone()
            .range(None, 2, 1, Some(1))
            .create_or_replace_temp_view("tmp_view")
            .await?;

        let res = spark.catalog().drop_temp_view("tmp_view").await?;

        assert!(res);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_table_with_schema() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .sql("DROP TABLE IF EXISTS tmp_table_with_schema")
            .await?;

        let schema = StructType::new(vec![
            StructField {
                name: "name",
                data_type: DataType::String,
                nullable: false,
                metadata: None,
            },
            StructField {
                name: "favorite_color",
                data_type: DataType::String,
                nullable: true,
                metadata: None,
            },
            StructField {
                name: "favorite_numbers",
                data_type: DataType::Array {
                    element_type: Box::new(DataType::Integer),
                    contains_null: true,
                },
                nullable: true,
                metadata: None,
            },
        ]);

        spark
            .catalog()
            .create_table(
                "tmp_table_with_schema",
                None,
                None,
                None,
                Some(schema.clone().into()),
                None,
            )
            .await?;

        let res = spark
            .catalog()
            .table_exists("tmp_table_with_schema", None)
            .await?;

        assert_eq!(res, true);

        let columns = spark
            .catalog()
            .list_columns("tmp_table_with_schema", None)
            .await?;

        assert_eq!(columns.num_rows(), 3);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_table_with_options() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .sql("DROP TABLE IF EXISTS tmp_table_with_options")
            .await?;

        let schema = StructType::new(vec![
            StructField {
                name: "name",
                data_type: DataType::String,
                nullable: false,
                metadata: None,
            },
            StructField {
                name: "favorite_color",
                data_type: DataType::String,
                nullable: true,
                metadata: None,
            },
            StructField {
                name: "favorite_numbers",
                data_type: DataType::Array {
                    element_type: Box::new(DataType::Integer),
                    contains_null: true,
                },
                nullable: true,
                metadata: None,
            },
        ]);

        let mut options = HashMap::new();
        options.insert("compression".to_string(), "gzip".to_string());

        spark
            .catalog()
            .create_table(
                "tmp_table_with_options",
                None,
                None,
                None,
                Some(schema.clone().into()),
                Some(options),
            )
            .await?;

        let res = spark
            .catalog()
            .table_exists("tmp_table_with_options", None)
            .await?;

        assert_eq!(res, true);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_table_with_desc() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .sql("DROP TABLE IF EXISTS tmp_table_with_desc")
            .await?;

        let schema = StructType::new(vec![
            StructField {
                name: "name",
                data_type: DataType::String,
                nullable: false,
                metadata: None,
            },
            StructField {
                name: "favorite_color",
                data_type: DataType::String,
                nullable: true,
                metadata: None,
            },
            StructField {
                name: "favorite_numbers",
                data_type: DataType::Array {
                    element_type: Box::new(DataType::Integer),
                    contains_null: true,
                },
                nullable: true,
                metadata: None,
            },
        ]);

        spark
            .catalog()
            .create_table(
                "tmp_table_with_desc",
                None,
                None,
                Some("A table with a description"),
                Some(schema.clone().into()),
                None,
            )
            .await?;

        let res = spark
            .catalog()
            .table_exists("tmp_table_with_desc", None)
            .await?;

        assert_eq!(res, true);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_table_with_path() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .sql("DROP TABLE IF EXISTS tmp_table_with_path")
            .await?;

        let schema = StructType::new(vec![
            StructField {
                name: "name",
                data_type: DataType::String,
                nullable: false,
                metadata: None,
            },
            StructField {
                name: "favorite_color",
                data_type: DataType::String,
                nullable: true,
                metadata: None,
            },
            StructField {
                name: "favorite_numbers",
                data_type: DataType::Array {
                    element_type: Box::new(DataType::Integer),
                    contains_null: true,
                },
                nullable: true,
                metadata: None,
            },
        ]);

        spark
            .catalog()
            .create_table(
                "tmp_table_with_path",
                Some("/opt/spark/work-dir/datasets/users.parquet"),
                Some("parquet"),
                None,
                Some(schema.clone().into()),
                None,
            )
            .await?;

        let res = spark
            .catalog()
            .table_exists("tmp_table_with_path", None)
            .await?;

        assert_eq!(res, true);

        Ok(())
    }

    #[tokio::test]
    async fn test_create_external_table() -> Result<(), SparkError> {
        let spark = setup().await;

        spark.sql("DROP TABLE IF EXISTS tmp_external_table").await?;

        let schema = StructType::new(vec![
            StructField {
                name: "name",
                data_type: DataType::String,
                nullable: false,
                metadata: None,
            },
            StructField {
                name: "favorite_color",
                data_type: DataType::String,
                nullable: true,
                metadata: None,
            },
            StructField {
                name: "favorite_numbers",
                data_type: DataType::Array {
                    element_type: Box::new(DataType::Integer),
                    contains_null: true,
                },
                nullable: true,
                metadata: None,
            },
        ]);

        spark
            .catalog()
            .create_external_table(
                "tmp_external_table",
                Some("/opt/spark/work-dir/datasets/users.parquet"),
                Some("parquet"),
                Some(schema.clone().into()),
                None,
            )
            .await?;

        let res = spark
            .catalog()
            .table_exists("tmp_external_table", None)
            .await?;

        assert_eq!(res, true);

        let data = spark.read().table("tmp_external_table", None)?;

        data.show(None, None, None).await?;

        Ok(())
    }

    #[tokio::test]
    async fn test_cache_table() -> Result<(), SparkError> {
        let spark = setup().await;

        spark
            .sql("CREATE TABLE cache_table (name STRING, age INT) using parquet")
            .await?;

        spark.catalog().cache_table("cache_table", None).await?;

        let res = spark.catalog().is_cached("cache_table").await?;

        assert!(res);

        spark.catalog().uncache_table("cache_table").await?;

        let res = spark.catalog().is_cached("cache_table").await?;

        assert!(!res);

        spark.sql("DROP TABLE cache_table").await?;
        Ok(())
    }
}