polars_io/catalog/unity/
client.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
use polars_core::prelude::PlHashMap;
use polars_core::schema::Schema;
use polars_error::{polars_bail, to_compute_err, PolarsResult};

use super::models::{CatalogInfo, NamespaceInfo, TableCredentials, TableInfo};
use super::schema::schema_to_column_info_list;
use super::utils::{do_request, PageWalker};
use crate::catalog::unity::models::{ColumnInfo, DataSourceFormat, TableType};
use crate::impl_page_walk;
use crate::utils::decode_json_response;

/// Unity catalog client.
pub struct CatalogClient {
    workspace_url: String,
    http_client: reqwest::Client,
}

impl CatalogClient {
    pub async fn list_catalogs(&self) -> PolarsResult<Vec<CatalogInfo>> {
        ListCatalogs(PageWalker::new(self.http_client.get(format!(
            "{}{}",
            &self.workspace_url, "/api/2.1/unity-catalog/catalogs"
        ))))
        .read_all_pages()
        .await
    }

    pub async fn list_namespaces(&self, catalog_name: &str) -> PolarsResult<Vec<NamespaceInfo>> {
        ListSchemas(PageWalker::new(
            self.http_client
                .get(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/schemas"
                ))
                .query(&[("catalog_name", catalog_name)]),
        ))
        .read_all_pages()
        .await
    }

    pub async fn list_tables(
        &self,
        catalog_name: &str,
        namespace: &str,
    ) -> PolarsResult<Vec<TableInfo>> {
        ListTables(PageWalker::new(
            self.http_client
                .get(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/tables"
                ))
                .query(&[("catalog_name", catalog_name), ("schema_name", namespace)]),
        ))
        .read_all_pages()
        .await
    }

    pub async fn get_table_info(
        &self,
        catalog_name: &str,
        namespace: &str,
        table_name: &str,
    ) -> PolarsResult<TableInfo> {
        let full_table_name = format!(
            "{}.{}.{}",
            catalog_name.replace('/', "%2F"),
            namespace.replace('/', "%2F"),
            table_name.replace('/', "%2F")
        );

        let bytes = do_request(
            self.http_client
                .get(format!(
                    "{}{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/tables/", full_table_name
                ))
                .query(&[("full_name", full_table_name)]),
        )
        .await?;

        let out: TableInfo = decode_json_response(&bytes)?;

        Ok(out)
    }

    pub async fn get_table_credentials(
        &self,
        table_id: &str,
        write: bool,
    ) -> PolarsResult<TableCredentials> {
        let bytes = do_request(
            self.http_client
                .post(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/temporary-table-credentials"
                ))
                .query(&[
                    ("table_id", table_id),
                    ("operation", if write { "READ_WRITE" } else { "READ" }),
                ]),
        )
        .await?;

        let out: TableCredentials = decode_json_response(&bytes)?;

        Ok(out)
    }

    pub async fn create_catalog(
        &self,
        catalog_name: &str,
        comment: Option<&str>,
        storage_root: Option<&str>,
    ) -> PolarsResult<CatalogInfo> {
        let resp = do_request(
            self.http_client
                .post(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/catalogs"
                ))
                .json(&Body {
                    name: catalog_name,
                    comment,
                    storage_root,
                }),
        )
        .await?;

        return decode_json_response(&resp);

        #[derive(serde::Serialize)]
        struct Body<'a> {
            name: &'a str,
            comment: Option<&'a str>,
            storage_root: Option<&'a str>,
        }
    }

    pub async fn delete_catalog(&self, catalog_name: &str, force: bool) -> PolarsResult<()> {
        let catalog_name = catalog_name.replace('/', "%2F");

        do_request(
            self.http_client
                .delete(format!(
                    "{}{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/catalogs/", catalog_name
                ))
                .query(&[("force", force)]),
        )
        .await?;

        Ok(())
    }

    pub async fn create_namespace(
        &self,
        catalog_name: &str,
        namespace: &str,
        comment: Option<&str>,
        storage_root: Option<&str>,
    ) -> PolarsResult<NamespaceInfo> {
        let resp = do_request(
            self.http_client
                .post(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/schemas"
                ))
                .json(&Body {
                    name: namespace,
                    catalog_name,
                    comment,
                    storage_root,
                }),
        )
        .await?;

        return decode_json_response(&resp);

        #[derive(serde::Serialize)]
        struct Body<'a> {
            name: &'a str,
            catalog_name: &'a str,
            comment: Option<&'a str>,
            storage_root: Option<&'a str>,
        }
    }

    pub async fn delete_namespace(
        &self,
        catalog_name: &str,
        namespace: &str,
        force: bool,
    ) -> PolarsResult<()> {
        let full_name = format!(
            "{}.{}",
            catalog_name.replace('/', "%2F"),
            namespace.replace('/', "%2F"),
        );

        do_request(
            self.http_client
                .delete(format!(
                    "{}{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/schemas/", full_name
                ))
                .query(&[("force", force)]),
        )
        .await?;

        Ok(())
    }

    /// Note, `data_source_format` can be None for some `table_type`s.
    #[allow(clippy::too_many_arguments)]
    pub async fn create_table(
        &self,
        catalog_name: &str,
        namespace: &str,
        table_name: &str,
        schema: Option<&Schema>,
        table_type: &TableType,
        data_source_format: Option<&DataSourceFormat>,
        comment: Option<&str>,
        storage_location: Option<&str>,
        properties: &mut (dyn Iterator<Item = (&str, &str)> + Send + Sync),
    ) -> PolarsResult<TableInfo> {
        let columns = schema.map(schema_to_column_info_list).transpose()?;
        let columns = columns.as_deref();

        let resp = do_request(
            self.http_client
                .post(format!(
                    "{}{}",
                    &self.workspace_url, "/api/2.1/unity-catalog/tables"
                ))
                .json(&Body {
                    name: table_name,
                    catalog_name,
                    schema_name: namespace,
                    table_type,
                    data_source_format,
                    comment,
                    columns,
                    storage_location,
                    properties: properties.collect(),
                }),
        )
        .await?;

        return decode_json_response(&resp);

        #[derive(serde::Serialize)]
        struct Body<'a> {
            name: &'a str,
            catalog_name: &'a str,
            schema_name: &'a str,
            comment: Option<&'a str>,
            table_type: &'a TableType,
            #[serde(skip_serializing_if = "Option::is_none")]
            data_source_format: Option<&'a DataSourceFormat>,
            columns: Option<&'a [ColumnInfo]>,
            storage_location: Option<&'a str>,
            properties: PlHashMap<&'a str, &'a str>,
        }
    }

    pub async fn delete_table(
        &self,
        catalog_name: &str,
        namespace: &str,
        table_name: &str,
    ) -> PolarsResult<()> {
        let full_name = format!(
            "{}.{}.{}",
            catalog_name.replace('/', "%2F"),
            namespace.replace('/', "%2F"),
            table_name.replace('/', "%2F"),
        );

        do_request(self.http_client.delete(format!(
            "{}{}{}",
            &self.workspace_url, "/api/2.1/unity-catalog/tables/", full_name
        )))
        .await?;

        Ok(())
    }
}

pub struct CatalogClientBuilder {
    workspace_url: Option<String>,
    bearer_token: Option<String>,
}

#[allow(clippy::derivable_impls)]
impl Default for CatalogClientBuilder {
    fn default() -> Self {
        Self {
            workspace_url: None,
            bearer_token: None,
        }
    }
}

impl CatalogClientBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_workspace_url(mut self, workspace_url: impl Into<String>) -> Self {
        self.workspace_url = Some(workspace_url.into());
        self
    }

    pub fn with_bearer_token(mut self, bearer_token: impl Into<String>) -> Self {
        self.bearer_token = Some(bearer_token.into());
        self
    }

    pub fn build(self) -> PolarsResult<CatalogClient> {
        let Some(workspace_url) = self.workspace_url else {
            polars_bail!(ComputeError: "expected Some(_) for workspace_url")
        };

        Ok(CatalogClient {
            workspace_url,
            http_client: {
                let builder = reqwest::ClientBuilder::new().user_agent("polars");

                let builder = if let Some(bearer_token) = self.bearer_token {
                    use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT};

                    let mut headers = HeaderMap::new();

                    let mut auth_value =
                        HeaderValue::from_str(format!("Bearer {}", bearer_token).as_str()).unwrap();
                    auth_value.set_sensitive(true);

                    headers.insert(AUTHORIZATION, auth_value);
                    headers.insert(USER_AGENT, "polars".try_into().unwrap());

                    builder.default_headers(headers)
                } else {
                    builder
                };

                builder.build().map_err(to_compute_err)?
            },
        })
    }
}

pub struct ListCatalogs(pub(crate) PageWalker);
impl_page_walk!(ListCatalogs, CatalogInfo, key_name = catalogs);

pub struct ListSchemas(pub(crate) PageWalker);
impl_page_walk!(ListSchemas, NamespaceInfo, key_name = schemas);

pub struct ListTables(pub(crate) PageWalker);
impl_page_walk!(ListTables, TableInfo, key_name = tables);