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
//! ShareReader implementation leveraging MySQL as backing store.

use async_trait::async_trait;
use sqlx::mysql::{MySqlPoolOptions, MySqlRow};
use sqlx::MySqlPool;
use sqlx::Row;

/// ShareReader using a MySQL database as backing store.
#[derive(Debug)]
pub struct MySqlShareReader {
    pool: MySqlPool,
}

use crate::protocol::securable::{Schema, SchemaBuilder, Share, ShareBuilder, Table, TableBuilder};

use super::{List, ListCursor, ShareIoError, ShareReader};

impl MySqlShareReader {
    /// Create a new instance of MySqlShareReader.
    pub async fn new(connection_url: &str) -> Self {
        let pool = MySqlPoolOptions::new()
            .max_connections(25)
            .connect(connection_url)
            .await
            .expect("failed to connect to mysql");

        Self { pool }
    }

    /// Create a new instance of MySqlShareReader from an existing pool.
    pub fn from_pool(pool: MySqlPool) -> Self {
        Self { pool }
    }

    /// Get a reference to the underlying pool.
    pub fn pool(&self) -> &MySqlPool {
        &self.pool
    }

    /// Insert a new share into the database.
    pub async fn insert_share(&self, share_name: &str) -> Result<Share, sqlx::Error> {
        let insert = sqlx::query("INSERT INTO share (name) VALUES (?);")
            .bind(share_name)
            .execute(&self.pool)
            .await?;
        let share_id = insert.last_insert_id().to_string();

        let share = ShareBuilder::new(share_name).id(share_id).build();
        Ok(share)
    }

    /// Retrieve a share by its name.
    async fn select_share_by_name(&self, share_name: &str) -> Result<Option<Share>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT 
                id AS share_id,
                name AS share_name
            FROM share
            WHERE name = ?;
            "#,
        )
        .bind(share_name)
        .fetch_optional(&self.pool)
        .await?
        .map(TryFrom::try_from)
        .transpose()
    }

    async fn select_shares(&self, cursor: &MySqlCursor) -> Result<Vec<Share>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT 
                id AS share_id,
                name AS share_name
            FROM share
            WHERE id > ?
            ORDER BY id
            LIMIT ?;
            "#,
        )
        .bind(cursor.last_seen_id())
        .bind(cursor.limit())
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(TryFrom::try_from)
        .collect()
    }

    /// Delete all shares from the database.
    pub async fn delete_shares(&self) -> Result<(), sqlx::Error> {
        sqlx::query("DELETE FROM share;")
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Insert a new schema into the database.
    pub async fn insert_schema(
        &self,
        share: &Share,
        schema_name: &str,
    ) -> Result<Schema, sqlx::Error> {
        let insert = sqlx::query(
            r#"
            INSERT INTO `schema` (name, share_id) 
            VALUES (?, ?);
            "#,
        )
        .bind(schema_name)
        .bind(share.id().unwrap())
        .execute(&self.pool)
        .await?;

        let schema_id = insert.last_insert_id().to_string();
        let schema = SchemaBuilder::new(share.clone(), schema_name)
            .id(schema_id)
            .build();

        Ok(schema)
    }

    async fn select_schema_by_name(
        &self,
        share_name: &str,
        schema_name: &str,
    ) -> Result<Option<Schema>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT 
                share.id AS share_id,
                share.name AS share_name,
                `schema`.id AS schema_id,
                `schema`.name AS schema_name
            FROM share
            LEFT JOIN `schema` ON `schema`.share_id = share.id
            WHERE share.name = ? AND `schema`.name = ?;
            "#,
        )
        .bind(share_name)
        .bind(schema_name)
        .fetch_optional(&self.pool)
        .await?
        .map(TryFrom::try_from)
        .transpose()
    }

    async fn select_schemas_by_share_name(
        &self,
        share_name: &str,
        cursor: &MySqlCursor,
    ) -> Result<Vec<Schema>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT 
                share.id AS share_id,
                share.name AS share_name,
                `schema`.id AS schema_id,
                `schema`.name AS schema_name
            FROM share
            LEFT JOIN `schema` ON `schema`.share_id = share.id
            WHERE share.name = ? AND `schema`.id > ?
            ORDER BY `schema`.id
            LIMIT ?;
            "#,
        )
        .bind(share_name)
        .bind(cursor.last_seen_id())
        .bind(cursor.limit())
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(TryFrom::try_from)
        .collect()
    }

    /// Delete all schemas from the database.
    pub async fn delete_schemas(&self) -> Result<(), sqlx::Error> {
        sqlx::query("DELETE FROM `schema`;")
            .execute(&self.pool)
            .await?;
        Ok(())
    }

    /// Insert a new table into the database.
    pub async fn insert_table(
        &self,
        schema: &Schema,
        table_name: &str,
        storage_path: &str,
        storage_format: Option<&String>,
    ) -> Result<Table, sqlx::Error> {
        let insert = sqlx::query(
            r#"
            INSERT INTO `table` (name, schema_id, storage_path, storage_format) 
            VALUES (?, ?, ?, ?);
            "#,
        )
        .bind(table_name)
        .bind(schema.id().unwrap())
        .bind(storage_path)
        .bind(storage_format)
        .execute(&self.pool)
        .await?;

        let table_id = insert.last_insert_id().to_string();
        let table = TableBuilder::new(schema.clone(), table_name, storage_path)
            .id(table_id)
            .set_format(storage_format)
            .build();

        Ok(table)
    }

    async fn select_tables_by_share(
        &self,
        share_name: &str,
        cursor: &MySqlCursor,
    ) -> Result<Vec<Table>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT
                share.id AS share_id,
                share.name AS share_name,
                `schema`.id AS schema_id,
                `schema`.name AS schema_name,
                `table`.id AS table_id,
                `table`.name AS table_name,
                `table`.storage_path AS storage_path,
                `table`.storage_format AS storage_format
            FROM share
            LEFT JOIN `schema` ON `schema`.share_id = share.id
            LEFT JOIN `table` ON `table`.schema_id = `schema`.id
            WHERE share.name = ? AND `table`.id > ?
            ORDER BY `table`.id
            LIMIT ?;
            "#,
        )
        .bind(share_name)
        .bind(cursor.last_seen_id())
        .bind(cursor.limit())
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(TryFrom::try_from)
        .collect()
    }

    async fn select_tables_by_schema(
        &self,
        share_name: &str,
        schema_name: &str,
        cursor: &MySqlCursor,
    ) -> Result<Vec<Table>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT
                share.id AS share_id,
                share.name AS share_name,
                `schema`.id AS schema_id,
                `schema`.name AS schema_name,
                `table`.id AS table_id,
                `table`.name AS table_name,
                `table`.storage_path AS storage_path,
                `table`.storage_format AS storage_format
            FROM share
            LEFT JOIN `schema` ON `schema`.share_id = share.id
            LEFT JOIN `table` ON `table`.schema_id = `schema`.id
            WHERE share.name = ? AND `schema`.name = ? AND `table`.id > ?
            ORDER BY `table`.id
            LIMIT ?;
            "#,
        )
        .bind(share_name)
        .bind(schema_name)
        .bind(cursor.last_seen_id())
        .bind(cursor.limit())
        .fetch_all(&self.pool)
        .await?
        .into_iter()
        .map(TryFrom::try_from)
        .collect()
    }

    async fn select_table_by_name(
        &self,
        share_name: &str,
        schema_name: &str,
        table_name: &str,
    ) -> Result<Option<Table>, sqlx::Error> {
        sqlx::query(
            r#"
            SELECT
                share.id AS share_id,
                share.name AS share_name,
                `schema`.id AS schema_id,
                `schema`.name AS schema_name,
                `table`.id AS table_id,
                `table`.name AS table_name,
                `table`.storage_path AS storage_path,
                `table`.storage_format AS storage_format
            FROM share
            LEFT JOIN `schema` ON `schema`.share_id = share.id
            LEFT JOIN `table` ON `table`.schema_id = `schema`.id
            WHERE share.name = ? AND `schema`.name = ? AND `table`.name = ?;
            "#,
        )
        .bind(share_name)
        .bind(schema_name)
        .bind(table_name)
        .fetch_optional(&self.pool)
        .await?
        .map(TryFrom::try_from)
        .transpose()
    }

    /// Delete all tables from the database.
    pub async fn delete_tables(&self) -> Result<(), sqlx::Error> {
        sqlx::query("DELETE FROM `table`;")
            .execute(&self.pool)
            .await?;
        Ok(())
    }
}

#[derive(Debug)]
struct MySqlCursor {
    last_seen_id: Option<u64>,
    limit: Option<u32>,
}

impl MySqlCursor {
    pub fn new(last_seen_id: Option<u64>, limit: Option<u32>) -> Self {
        Self {
            last_seen_id,
            limit,
        }
    }

    pub fn last_seen_id(&self) -> u64 {
        self.last_seen_id.unwrap_or(0)
    }

    pub fn limit(&self) -> i32 {
        match self.limit {
            Some(lim) => lim as i32,
            None => 100,
        }
    }
}

use core::str::FromStr;

impl TryFrom<ListCursor> for MySqlCursor {
    type Error = &'static str;
    fn try_from(cursor: ListCursor) -> Result<Self, Self::Error> {
        let last_seen_id = cursor
            .page_token()
            .map(|token| u64::from_str(token).map_err(|_| "invalid page token"))
            .transpose()?;
        let pg_cursor = MySqlCursor::new(last_seen_id, cursor.max_results());
        Ok(pg_cursor)
    }
}

impl TryFrom<MySqlRow> for Share {
    type Error = sqlx::Error;

    fn try_from(row: MySqlRow) -> Result<Self, Self::Error> {
        let name: String = row.try_get("share_name")?;
        let id: i32 = row.try_get("share_id")?;
        let share = ShareBuilder::new(name).id(id.to_string()).build();
        Ok(share)
    }
}

impl TryFrom<MySqlRow> for Schema {
    type Error = sqlx::Error;

    fn try_from(row: MySqlRow) -> Result<Self, Self::Error> {
        let share_id: i32 = row.try_get("share_id")?;
        let share_name: String = row.try_get("share_name")?;
        let schema_id: i32 = row.try_get("schema_id")?;
        let schema_name: String = row.try_get("schema_name")?;

        let share = ShareBuilder::new(share_name)
            .id(share_id.to_string())
            .build();
        let schema = SchemaBuilder::new(share, schema_name)
            .id(schema_id.to_string())
            .build();

        Ok(schema)
    }
}

impl TryFrom<MySqlRow> for Table {
    type Error = sqlx::Error;

    fn try_from(row: MySqlRow) -> Result<Self, Self::Error> {
        let share_id: i32 = row.try_get("share_id")?;
        let share_name: String = row.try_get("share_name")?;
        let schema_id: i32 = row.try_get("schema_id")?;
        let schema_name: String = row.try_get("schema_name")?;
        let table_id: i32 = row.try_get("table_id")?;
        let table_name: String = row.try_get("table_name")?;
        let storage_path: String = row.try_get("storage_path")?;
        let storage_format: Option<String> = row.try_get("storage_format")?;

        let share = ShareBuilder::new(share_name)
            .id(share_id.to_string())
            .build();
        let schema = SchemaBuilder::new(share, schema_name)
            .id(schema_id.to_string())
            .build();
        let table = TableBuilder::new(schema, table_name, storage_path)
            .id(table_id.to_string())
            .set_format(storage_format)
            .build();

        Ok(table)
    }
}

#[async_trait]
impl ShareReader for MySqlShareReader {
    async fn list_shares(&self, cursor: &ListCursor) -> Result<List<Share>, ShareIoError> {
        let pg_cursor = MySqlCursor::try_from(cursor.clone())
            .map_err(|_| ShareIoError::MalformedContinuationToken)?;
        let shares = self.select_shares(&pg_cursor).await?;

        let next_page_token = if shares.len() == pg_cursor.limit() as usize {
            shares
                .iter()
                .last()
                .and_then(|s| s.id())
                .map(|id| id.to_string())
        } else {
            None
        };

        Ok(List::new(shares, next_page_token))
    }

    async fn get_share(&self, share_name: &str) -> Result<Share, ShareIoError> {
        self.select_share_by_name(share_name)
            .await?
            .ok_or(ShareIoError::ShareNotFound {
                share_name: share_name.to_string(),
            })
    }

    async fn list_schemas(
        &self,
        share_name: &str,
        cursor: &ListCursor,
    ) -> Result<List<Schema>, ShareIoError> {
        let pg_cursor = MySqlCursor::try_from(cursor.clone())
            .map_err(|_| ShareIoError::MalformedContinuationToken)?;
        let schemas = self
            .select_schemas_by_share_name(share_name, &pg_cursor)
            .await?;

        let next_page_token = if schemas.len() == pg_cursor.limit() as usize {
            schemas
                .iter()
                .last()
                .and_then(|s| s.id())
                .map(|id| id.to_string())
        } else {
            None
        };

        Ok(List::new(schemas, next_page_token))
    }

    async fn list_tables_in_share(
        &self,
        share_name: &str,
        cursor: &ListCursor,
    ) -> Result<List<Table>, ShareIoError> {
        let pg_cursor = MySqlCursor::try_from(cursor.clone())
            .map_err(|_| ShareIoError::MalformedContinuationToken)?;
        let tables = self.select_tables_by_share(share_name, &pg_cursor).await?;

        let next_page_token = if tables.len() == pg_cursor.limit() as usize {
            tables
                .iter()
                .last()
                .and_then(|s| s.id())
                .map(|id| id.to_string())
        } else {
            None
        };

        Ok(List::new(tables, next_page_token))
    }

    async fn list_tables_in_schema(
        &self,
        share_name: &str,
        schema_name: &str,
        cursor: &ListCursor,
    ) -> Result<List<Table>, ShareIoError> {
        let pg_cursor = MySqlCursor::try_from(cursor.clone())
            .map_err(|_| ShareIoError::MalformedContinuationToken)?;
        let tables = self
            .select_tables_by_schema(share_name, schema_name, &pg_cursor)
            .await?;

        let next_page_token = if tables.len() == pg_cursor.limit() as usize {
            tables
                .iter()
                .last()
                .and_then(|s| s.id())
                .map(|id| id.to_string())
        } else {
            None
        };

        Ok(List::new(tables, next_page_token))
    }

    async fn get_table(
        &self,
        share_name: &str,
        schema_name: &str,
        table_name: &str,
    ) -> Result<Table, ShareIoError> {
        match self
            .select_table_by_name(share_name, schema_name, table_name)
            .await
        {
            Ok(Some(table)) => Ok(table),
            Ok(None) => {
                let share = self.select_share_by_name(share_name).await?;
                let schema = self.select_schema_by_name(share_name, schema_name).await?;
                match (share, schema) {
                    (None, _) => Err(ShareIoError::ShareNotFound {
                        share_name: share_name.to_owned(),
                    }),
                    (Some(_), None) => Err(ShareIoError::SchemaNotFound {
                        share_name: share_name.to_owned(),
                        schema_name: schema_name.to_owned(),
                    }),
                    (Some(_), Some(_)) => Err(ShareIoError::TableNotFound {
                        share_name: share_name.to_owned(),
                        schema_name: schema_name.to_owned(),
                        table_name: table_name.to_owned(),
                    }),
                }
            }
            Err(err) => Err(err.into()),
        }
    }
}