akd_mysql 0.8.8

A MySQL storage layer implementation for an auditable key directory (AKD)
Documentation
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
// Copyright (c) Meta Platforms, Inc. and affiliates.
//
// This source code is licensed under both the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree and the Apache
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
// of this source tree.

//! This module implements record handling for a simple asynchronized mysql database

use std::convert::TryInto;

use akd::storage::types::{DbRecord, StorageType};
use akd::storage::Storable;
use akd::tree_node::{NodeKey, TreeNodeWithPreviousValue};
use akd::NodeLabel;
use mysql_async::prelude::*;
use mysql_async::*;

type MySqlError = mysql_async::Error;

pub(crate) const TABLE_AZKS: &str = "azks";
pub(crate) const TABLE_HISTORY_TREE_NODES: &str = "history";
pub(crate) const TABLE_USER: &str = "users";
pub(crate) const TEMP_IDS_TABLE: &str = "temp_ids_table";

const SELECT_AZKS_DATA: &str = "`epoch`, `num_nodes`";
const SELECT_HISTORY_TREE_NODE_DATA: &str =
    "`label_len`, `label_val`, `last_epoch`, `least_descendant_ep`, `parent_label_len`, `parent_label_val`, `node_type`, `left_child_len`, `left_child_label_val`, `right_child_len`, `right_child_label_val`, `hash`, `p_last_epoch`, `p_least_descendant_ep`, `p_parent_label_len`, `p_parent_label_val`, `p_node_type`, `p_left_child_len`, `p_left_child_label_val`, `p_right_child_len`, `p_right_child_label_val`, `p_hash`";
const SELECT_USER_DATA: &str =
    "`username`, `epoch`, `version`, `node_label_val`, `node_label_len`, `data`";

pub(crate) trait MySqlStorable {
    fn set_statement(&self) -> String;

    fn set_params(&self) -> Option<mysql_async::Params>;

    fn set_batch_statement<St: Storable>(items: usize) -> String;

    fn set_batch_params(items: &[DbRecord]) -> Result<mysql_async::Params>;

    fn get_statement<St: Storable>() -> String;

    fn get_batch_create_temp_table<St: Storable>() -> Option<String>;

    fn get_batch_fill_temp_table<St: Storable>(num_items: Option<usize>) -> String;

    fn get_batch_statement<St: Storable>() -> String;

    fn get_specific_statement<St: Storable>() -> String;

    fn get_specific_params<St: Storable>(key: &St::StorageKey) -> Option<mysql_async::Params>;

    fn get_multi_row_specific_params<St: Storable>(
        keys: &[St::StorageKey],
    ) -> Option<mysql_async::Params>;

    fn from_row<St: Storable>(row: &mut mysql_async::Row) -> core::result::Result<Self, MySqlError>
    where
        Self: std::marker::Sized;
}

impl MySqlStorable for DbRecord {
    fn set_statement(&self) -> String {
        match &self {
            DbRecord::Azks(_) => format!("INSERT INTO `{TABLE_AZKS}` (`key`, {SELECT_AZKS_DATA})
            VALUES (:key, :epoch, :num_nodes)
            ON DUPLICATE KEY UPDATE
                `epoch` = :epoch
                , `num_nodes` = :num_nodes"),
            DbRecord::TreeNode(_) => format!("INSERT INTO `{TABLE_HISTORY_TREE_NODES}` ({SELECT_HISTORY_TREE_NODE_DATA})
            VALUES (:label_len
                , :label_val
                , :last_epoch
                , :least_descendant_ep
                , :parent_label_len
                , :parent_label_val
                , :node_type
                , :left_child_len
                , :left_child_label_val
                , :right_child_len
                , :right_child_label_val
                , :hash
                , :p_last_epoch
                , :p_least_descendant_ep
                , :p_parent_label_len
                , :p_parent_label_val
                , :p_node_type
                , :p_left_child_len
                , :p_left_child_label_val
                , :p_right_child_len
                , :p_right_child_label_val
                , :p_hash)
            ON DUPLICATE KEY UPDATE
                `label_len` = :label_len
                , `label_val` = :label_val
                , `last_epoch` = :last_epoch
                , `least_descendant_ep` = :least_descendant_ep
                , `parent_label_len` = :parent_label_len
                , `parent_label_val` = :parent_label_val
                , `node_type` = :node_type
                , `left_child_len` = :left_child_len
                , `left_child_label_val` = :left_child_label_val
                , `right_child_len` = :right_child_len
                , `right_child_label_val` = :right_child_label_val
                , `hash` = :hash
                , `p_last_epoch` = :p_last_epoch
                , `p_least_descendant_ep` = :p_least_descendant_ep
                , `p_parent_label_len` = :p_parent_label_len
                , `p_parent_label_val` = :p_parent_label_val
                , `p_node_type` = :p_node_type
                , `p_left_child_len` = :p_left_child_len
                , `p_left_child_label_val` = :p_left_child_label_val
                , `p_right_child_len` = :p_right_child_len
                , `p_right_child_label_val` = :p_right_child_label_val
                , `p_hash` = :p_hash"),
            DbRecord::ValueState(_) => format!("INSERT INTO `{TABLE_USER}` ({SELECT_USER_DATA}) VALUES (:username, :epoch, :version, :node_label_val, :node_label_len, :data)"),
        }
    }

    fn set_params(&self) -> Option<mysql_async::Params> {
        match &self {
            DbRecord::Azks(azks) => Some(
                params! { "key" => 1u8, "epoch" => azks.latest_epoch, "num_nodes" => azks.num_nodes },
            ),
            DbRecord::TreeNode(node) => Some(params! {
                "label_len" => node.label.label_len,
                "label_val" => node.label.label_val,
                // "Latest" node values
                "last_epoch" => node.latest_node.last_epoch,
                "least_descendant_ep" => node.latest_node.min_descendant_epoch,
                "parent_label_len" => node.latest_node.parent.label_len,
                "parent_label_val" => node.latest_node.parent.label_val,
                "node_type" => node.latest_node.node_type as u8,
                "left_child_len" => node.latest_node.left_child.map(|lc| lc.label_len),
                "left_child_label_val" => node.latest_node.left_child.map(|lc| lc.label_val),
                "right_child_len" => node.latest_node.right_child.map(|rc| rc.label_len),
                "right_child_label_val" => node.latest_node.right_child.map(|rc| rc.label_val),
                "hash" => node.latest_node.hash.0,
                // "Previous" node values
                "p_last_epoch" => node.previous_node.clone().map(|a| a.last_epoch),
                "p_least_descendant_ep" => node.previous_node.clone().map(|a| a.min_descendant_epoch),
                "p_parent_label_len" => node.previous_node.clone().map(|a| a.parent.label_len),
                "p_parent_label_val" => node.previous_node.clone().map(|a| a.parent.label_val),
                "p_node_type" => node.previous_node.clone().map(|a| a.node_type as u8),
                "p_left_child_len" => node.previous_node.clone().and_then(|a| a.left_child.map(|lc| lc.label_len)),
                "p_left_child_label_val" => node.previous_node.clone().and_then(|a| a.left_child.map(|lc| lc.label_val)),
                "p_right_child_len" => node.previous_node.clone().and_then(|a| a.right_child.map(|rc| rc.label_len)),
                "p_right_child_label_val" => node.previous_node.clone().and_then(|a| a.right_child.map(|rc| rc.label_val)),
                "p_hash" => node.previous_node.clone().map(|a| a.hash.0),
            }),
            DbRecord::ValueState(state) => Some(
                params! { "username" => state.get_id().0, "epoch" => state.epoch, "version" => state.version, "node_label_len" => state.label.label_len, "node_label_val" => state.label.label_val, "data" => state.value.0.clone() },
            ),
        }
    }

    fn set_batch_statement<St: Storable>(items: usize) -> String {
        let mut parts = "".to_string();
        for i in 0..items {
            match St::data_type() {
                StorageType::TreeNode => {
                    parts = format!(
                        "{parts}(:label_len{i}
                            , :label_val{i}
                            , :last_epoch{i}
                            , :least_descendant_ep{i}
                            , :parent_label_len{i}
                            , :parent_label_val{i}
                            , :node_type{i}
                            , :left_child_len{i}
                            , :left_child_label_val{i}
                            , :right_child_len{i}
                            , :right_child_label_val{i}
                            , :hash{i}
                            , :p_last_epoch{i}
                            , :p_least_descendant_ep{i}
                            , :p_parent_label_len{i}
                            , :p_parent_label_val{i}
                            , :p_node_type{i}
                            , :p_left_child_len{i}
                            , :p_left_child_label_val{i}
                            , :p_right_child_len{i}
                            , :p_right_child_label_val{i}
                            , :p_hash{i})"
                    );
                }
                StorageType::ValueState => {
                    parts = format!(
                        "{parts}(:username{i}, :epoch{i}, :version{i}, :node_label_val{i}, :node_label_len{i}, :data{i})"
                    );
                }
                _ => {
                    // azks
                }
            }

            if i < items - 1 {
                parts += ", ";
            }
        }

        match St::data_type() {
            StorageType::Azks => format!(
                "INSERT INTO `{TABLE_AZKS}` (`key`, {SELECT_AZKS_DATA})
            VALUES (:key, :epoch, :num_nodes) as new
            ON DUPLICATE KEY UPDATE `epoch` = new.epoch, `num_nodes` = new.num_nodes"
            ),
            StorageType::TreeNode => format!(
                "INSERT INTO `{TABLE_HISTORY_TREE_NODES}` ({SELECT_HISTORY_TREE_NODE_DATA})
            VALUES {parts} as new
            ON DUPLICATE KEY UPDATE
                `label_len` = new.label_len
                , `label_val` = new.label_val
                , `least_descendant_ep` = new.least_descendant_ep
                , `last_epoch` = new.last_epoch
                , `parent_label_len` = new.parent_label_len
                , `parent_label_val` = new.parent_label_val
                , `node_type` = new.node_type
                , `left_child_len` = new.left_child_len
                , `left_child_label_val` = new.left_child_label_val
                , `right_child_len` = new.right_child_len
                , `right_child_label_val` = new.right_child_label_val
                , `hash` = new.hash
                , `p_last_epoch` = new.p_last_epoch
                , `p_least_descendant_ep` = new.p_least_descendant_ep
                , `p_parent_label_len` = new.p_parent_label_len
                , `p_parent_label_val` = new.p_parent_label_val
                , `p_node_type` = new.p_node_type
                , `p_left_child_len` = new.p_left_child_len
                , `p_left_child_label_val` = new.p_left_child_label_val
                , `p_right_child_len` = new.p_right_child_len
                , `p_right_child_label_val` = new.p_right_child_label_val
                , `p_hash` = new.p_hash"
            ),
            StorageType::ValueState => format!(
                "INSERT INTO `{TABLE_USER}` ({SELECT_USER_DATA})
            VALUES {parts} as new
            ON DUPLICATE KEY UPDATE
                `data` = new.data
                , `node_label_val` = new.node_label_val
                , `node_label_len` = new.node_label_len
                , `version` = new.version"
            ),
        }
    }

    fn set_batch_params(items: &[DbRecord]) -> Result<mysql_async::Params> {
        let param_batch = items
            .iter()
            .enumerate()
            .map(|(idx, item)| match &item {
                DbRecord::Azks(azks) => Ok(vec![
                    ("key".to_string(), Value::from(1u8)),
                    ("epoch".to_string(), Value::from(azks.latest_epoch)),
                    ("num_nodes".to_string(), Value::from(azks.num_nodes)),
                ]),
                DbRecord::TreeNode(node) => {
                    let pnode = &node.previous_node;
                    Ok(vec![
                        (format!("label_len{idx}"), Value::from(node.label.label_len)),
                        (format!("label_val{idx}"), Value::from(node.label.label_val)),
                        (
                            format!("last_epoch{idx}"),
                            Value::from(node.latest_node.last_epoch),
                        ),
                        (
                            format!("least_descendant_ep{idx}"),
                            Value::from(node.latest_node.min_descendant_epoch),
                        ),
                        (
                            format!("parent_label_len{idx}"),
                            Value::from(node.latest_node.parent.label_len),
                        ),
                        (
                            format!("parent_label_val{idx}"),
                            Value::from(node.latest_node.parent.label_val),
                        ),
                        (
                            format!("node_type{idx}"),
                            Value::from(node.latest_node.node_type as u8),
                        ),
                        (
                            format!("left_child_len{idx}"),
                            Value::from(node.latest_node.left_child.map(|lc| lc.label_len)),
                        ),
                        (
                            format!("left_child_label_val{idx}"),
                            Value::from(node.latest_node.left_child.map(|lc| lc.label_val)),
                        ),
                        (
                            format!("right_child_len{idx}"),
                            Value::from(node.latest_node.right_child.map(|rc| rc.label_len)),
                        ),
                        (
                            format!("right_child_label_val{idx}"),
                            Value::from(node.latest_node.right_child.map(|rc| rc.label_val)),
                        ),
                        (format!("hash{idx}"), Value::from(node.latest_node.hash.0)),
                        (
                            format!("p_last_epoch{idx}"),
                            Value::from(pnode.clone().map(|a| a.last_epoch)),
                        ),
                        (
                            format!("p_least_descendant_ep{idx}"),
                            Value::from(pnode.clone().map(|a| a.min_descendant_epoch)),
                        ),
                        (
                            format!("p_parent_label_len{idx}"),
                            Value::from(pnode.clone().map(|a| a.parent.label_len)),
                        ),
                        (
                            format!("p_parent_label_val{idx}"),
                            Value::from(pnode.clone().map(|a| a.parent.label_val)),
                        ),
                        (
                            format!("p_node_type{idx}"),
                            Value::from(pnode.clone().map(|a| a.node_type as u8)),
                        ),
                        (
                            format!("p_left_child_len{idx}"),
                            Value::from(
                                pnode
                                    .clone()
                                    .and_then(|a| a.left_child.map(|lc| lc.label_len)),
                            ),
                        ),
                        (
                            format!("p_left_child_label_val{idx}"),
                            Value::from(
                                pnode
                                    .clone()
                                    .and_then(|a| a.left_child.map(|lc| lc.label_val)),
                            ),
                        ),
                        (
                            format!("p_right_child_len{idx}"),
                            Value::from(
                                pnode
                                    .clone()
                                    .and_then(|a| a.right_child.map(|rc| rc.label_len)),
                            ),
                        ),
                        (
                            format!("p_right_child_label_val{idx}"),
                            Value::from(
                                pnode
                                    .clone()
                                    .and_then(|a| a.right_child.map(|rc| rc.label_val)),
                            ),
                        ),
                        (
                            format!("p_hash{idx}"),
                            Value::from(pnode.clone().map(|a| a.hash.0)),
                        ),
                    ])
                }
                DbRecord::ValueState(state) => Ok(vec![
                    (format!("username{idx}"), Value::from(state.get_id().0)),
                    (format!("epoch{idx}"), Value::from(state.epoch)),
                    (format!("version{idx}"), Value::from(state.version)),
                    (
                        format!("node_label_len{idx}"),
                        Value::from(state.label.label_len),
                    ),
                    (
                        format!("node_label_val{idx}"),
                        Value::from(state.label.label_val),
                    ),
                    (format!("data{idx}"), Value::from(state.value.0.clone())),
                ]),
            })
            .into_iter()
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .flatten()
            .collect::<Vec<_>>();
        Ok(mysql_async::Params::from(param_batch))
    }

    fn get_statement<St: Storable>() -> String {
        match St::data_type() {
            StorageType::Azks => format!("SELECT {SELECT_AZKS_DATA} FROM `{TABLE_AZKS}`"),
            StorageType::TreeNode => {
                format!("SELECT {SELECT_HISTORY_TREE_NODE_DATA} FROM `{TABLE_HISTORY_TREE_NODES}`")
            }
            StorageType::ValueState => format!("SELECT {SELECT_USER_DATA} FROM `{TABLE_USER}`"),
        }
    }

    fn get_batch_create_temp_table<St: Storable>() -> Option<String> {
        match St::data_type() {
            StorageType::Azks => None,
            StorageType::TreeNode => {
                Some(
                    format!(
                        "CREATE TEMPORARY TABLE `{TEMP_IDS_TABLE}`(`label_len` INT UNSIGNED NOT NULL, `label_val` VARBINARY(32) NOT NULL, PRIMARY KEY(`label_len`, `label_val`))"
                    )
                )
            },
            StorageType::ValueState => {
                Some(
                    format!(
                        "CREATE TEMPORARY TABLE `{TEMP_IDS_TABLE}`(`username` VARCHAR(256) NOT NULL, `epoch` BIGINT UNSIGNED NOT NULL, PRIMARY KEY(`username`, `epoch`))"
                    )
                )
            },
        }
    }

    fn get_batch_fill_temp_table<St: Storable>(num_items: Option<usize>) -> String {
        let mut statement = match St::data_type() {
            StorageType::Azks => "".to_string(),
            StorageType::TreeNode => {
                format!("INSERT INTO `{TEMP_IDS_TABLE}` (`label_len`, `label_val`) VALUES ")
            }
            StorageType::ValueState => {
                format!("INSERT INTO `{TEMP_IDS_TABLE}` (`username`, `epoch`) VALUES ")
            }
        };
        if let Some(item_count) = num_items {
            for i in 0..item_count {
                let append = match St::data_type() {
                    StorageType::Azks => String::from(""),
                    StorageType::TreeNode => {
                        format!("(:label_len{i}, :label_val{i})")
                    }
                    StorageType::ValueState => {
                        format!("(:username{i}, :epoch{i})")
                    }
                };
                statement = format!("{statement}{append}");

                if i < item_count - 1 {
                    // inner-item, append a comma
                    statement += ", ";
                }
            }
        } else {
            statement += match St::data_type() {
                StorageType::Azks => "",
                StorageType::TreeNode => "(:label_len, :label_val)",
                StorageType::ValueState => "(:username, :epoch)",
            };
        }
        statement
    }

    fn get_batch_statement<St: Storable>() -> String {
        match St::data_type() {
            StorageType::Azks => {
                format!("SELECT {SELECT_AZKS_DATA} FROM `{TABLE_AZKS}` LIMIT 1")
            }
            StorageType::TreeNode => {
                format!(
                    "SELECT
                        a.`label_len`
                        , a.`label_val`
                        , a.`last_epoch`
                        , a.`least_descendant_ep`
                        , a.`parent_label_len`
                        , a.`parent_label_val`
                        , a.`node_type`
                        , a.`left_child_len`
                        , a.`left_child_label_val`
                        , a.`right_child_len`
                        , a.`right_child_label_val`
                        , a.`hash`, a.`p_last_epoch`
                        , a.`p_least_descendant_ep`
                        , a.`p_parent_label_len`
                        , a.`p_parent_label_val`
                        , a.`p_node_type`
                        , a.`p_left_child_len`
                        , a.`p_left_child_label_val`
                        , a.`p_right_child_len`
                        , a.`p_right_child_label_val`
                        , a.`p_hash`
                    FROM `{TABLE_HISTORY_TREE_NODES}` a
                    INNER JOIN {TEMP_IDS_TABLE} ids
                        ON ids.`label_len` = a.`label_len`
                        AND ids.`label_val` = a.`label_val`"
                )
            }
            StorageType::ValueState => {
                format!(
                    "SELECT
                        a.`username`
                        , a.`epoch`
                        , a.`version`
                        , a.`node_label_val`
                        , a.`node_label_len`
                        , a.`data`
                    FROM `{TABLE_USER}` a
                    INNER JOIN {TEMP_IDS_TABLE} ids
                        ON ids.`username` = a.`username`
                        AND ids.`epoch` = a.`epoch`"
                )
            }
        }
    }

    fn get_specific_statement<St: Storable>() -> String {
        match St::data_type() {
            StorageType::Azks => {
                format!("SELECT {SELECT_AZKS_DATA} FROM `{TABLE_AZKS}` LIMIT 1")
            }
            StorageType::TreeNode => format!(
                "SELECT {SELECT_HISTORY_TREE_NODE_DATA} FROM `{TABLE_HISTORY_TREE_NODES}` WHERE `label_len` = :label_len AND `label_val` = :label_val"
            ),
            StorageType::ValueState => format!(
                "SELECT {SELECT_USER_DATA} FROM `{TABLE_USER}` WHERE `username` = :username AND `epoch` = :epoch"
            ),
        }
    }

    fn get_specific_params<St: Storable>(key: &St::StorageKey) -> Option<mysql_async::Params> {
        match St::data_type() {
            StorageType::Azks => None,
            StorageType::TreeNode => {
                let bin = St::get_full_binary_key_id(key);
                if let Ok(back) = TreeNodeWithPreviousValue::key_from_full_binary(&bin) {
                    Some(params! {
                        "label_len" => back.0.label_len,
                        "label_val" => back.0.label_val,
                    })
                } else {
                    None
                }
            }
            StorageType::ValueState => {
                let bin = St::get_full_binary_key_id(key);
                if let Ok(back) = akd::storage::types::ValueState::key_from_full_binary(&bin) {
                    Some(params! {
                        "username" => back.0,
                        "epoch" => back.1
                    })
                } else {
                    None
                }
            }
        }
    }

    fn get_multi_row_specific_params<St: Storable>(
        keys: &[St::StorageKey],
    ) -> Option<mysql_async::Params> {
        match St::data_type() {
            StorageType::Azks => None,
            StorageType::TreeNode => {
                let pvec = keys
                    .iter()
                    .enumerate()
                    .map(|(idx, key)| {
                        let bin = St::get_full_binary_key_id(key);
                        // Since these are constructed from a safe key, they should never fail
                        // so we'll leave the unwrap to simplify
                        let back: NodeKey =
                            TreeNodeWithPreviousValue::key_from_full_binary(&bin).unwrap();
                        vec![
                            (format!("label_len{idx}"), Value::from(back.0.label_len)),
                            (format!("label_val{idx}"), Value::from(back.0.label_val)),
                        ]
                    })
                    .into_iter()
                    .flatten()
                    .collect::<Vec<_>>();
                Some(mysql_async::Params::from(pvec))
            }
            StorageType::ValueState => {
                let pvec = keys
                    .iter()
                    .enumerate()
                    .map(|(idx, key)| {
                        let bin = St::get_full_binary_key_id(key);
                        // Since these are constructed from a safe key, they should never fail
                        // so we'll leave the unwrap to simplify
                        let back: akd::storage::types::ValueStateKey =
                            akd::storage::types::ValueState::key_from_full_binary(&bin).unwrap();
                        vec![
                            (format!("username{idx}"), Value::from(back.0.clone())),
                            (format!("epoch{idx}"), Value::from(back.1)),
                        ]
                    })
                    .into_iter()
                    .flatten()
                    .collect::<Vec<_>>();
                Some(mysql_async::Params::from(pvec))
            }
        }
    }

    fn from_row<St: Storable>(row: &mut mysql_async::Row) -> core::result::Result<Self, MySqlError>
    where
        Self: std::marker::Sized,
    {
        fn cast_err() -> MySqlError {
            MySqlError::from(mysql_async::ServerError {
                state: "".to_string(),
                code: 0,
                message: "Failed to cast label:val into [u8; 32]".to_string(),
            })
        }

        fn optional_child_label(
            child_val: Option<Value>,
            child_len: Option<Value>,
        ) -> core::result::Result<Option<NodeLabel>, MySqlError> {
            match (child_val, child_len) {
                (Some(Value::NULL), _) => Ok(None),
                (_, Some(Value::NULL)) => Ok(None),
                (None, _) => Ok(None),
                (_, None) => Ok(None),
                (Some(possible_bytes), Some(possible_u32)) => {
                    match (
                        from_value_opt::<u32>(possible_u32),
                        from_value_opt::<Vec<u8>>(possible_bytes),
                    ) {
                        (Ok(len), Ok(val)) => Ok(Some(NodeLabel::new(
                            val.try_into().map_err(|_| cast_err())?,
                            len,
                        ))),
                        (Err(_len_err), _) => Err(Error::from(mysql_async::ServerError {
                            state: "".to_string(),
                            code: 0,
                            message: "Error decoding length".to_string(),
                        })),
                        (_, Err(_val_err)) => Err(Error::from(mysql_async::ServerError {
                            state: "".to_string(),
                            code: 0,
                            message: "Error decoding value".to_string(),
                        })),
                    }
                }
            }
        }

        match St::data_type() {
            StorageType::Azks => {
                // epoch, num_nodes
                if let (Some(Ok(epoch)), Some(Ok(num_nodes))) = (row.take_opt(0), row.take_opt(1)) {
                    let azks = DbRecord::build_azks(epoch, num_nodes);
                    return Ok(DbRecord::Azks(azks));
                }
            }
            StorageType::TreeNode => {
                // A NOTE ABOUT THE SYNTAX HERE: The outer-most Some(**) of the row.take(..) indicates the COLUMN EXISTS, not that it actually has a value.
                // Therefore the signature of these fields you want is Some(Option<value>) for a nullable column. The inner option type is not necessary
                // for types which have NOT NULL in the SQL definition
                if let (
                    Some(Ok(label_len)),
                    Some(Ok(label_val)),
                    Some(Ok(last_epoch)),
                    Some(Ok(least_descendant_ep)),
                    Some(Ok(parent_label_len)),
                    Some(Ok(parent_label_val)),
                    Some(Ok(node_type)),
                    left_child_len_res,
                    left_child_val_res,
                    right_child_len_res,
                    right_child_val_res,
                    Some(Ok(hash)),
                    Some(p_last_epoch),
                    Some(p_least_descendant_ep),
                    Some(p_parent_label_len),
                    Some(p_parent_label_val),
                    Some(p_node_type),
                    p_left_child_len,
                    p_left_child_label_val,
                    p_right_child_len,
                    p_right_child_label_val,
                    Some(p_hash),
                ) = (
                    row.take_opt(0),
                    row.take_opt(1),
                    row.take_opt(2),
                    row.take_opt(3),
                    row.take_opt(4),
                    row.take_opt(5),
                    row.take_opt(6),
                    row.take(7),
                    row.take(8),
                    row.take(9),
                    row.take(10),
                    row.take_opt(11),
                    row.take(12),
                    row.take(13),
                    row.take(14),
                    row.take(15),
                    row.take(16),
                    row.take(17),
                    row.take(18),
                    row.take(19),
                    row.take(20),
                    row.take(21),
                ) {
                    let left_child = optional_child_label(left_child_val_res, left_child_len_res)?;
                    let right_child =
                        optional_child_label(right_child_val_res, right_child_len_res)?;
                    let p_left_child =
                        optional_child_label(p_left_child_label_val, p_left_child_len)?;
                    let p_right_child =
                        optional_child_label(p_right_child_label_val, p_right_child_len)?;

                    let label_val_vec: Vec<u8> = label_val;

                    let parent_label_val_vec: Vec<u8> = parent_label_val;
                    let prev_parent_label_val_vec: Option<Vec<u8>> = p_parent_label_val;
                    let hash_vec: Vec<u8> = hash;
                    let prev_hash_vec: Option<Vec<u8>> = p_hash;

                    let massaged_prev_parent_label_val: Option<[u8; 32]> =
                        match prev_parent_label_val_vec {
                            Some(v) => Some(v.try_into().map_err(|_| cast_err())?),
                            None => None,
                        };
                    let massaged_hash_vec: akd::Digest =
                        akd::hash::try_parse_digest(&hash_vec).map_err(|_| cast_err())?;
                    let massaged_prev_hash_vec: Option<akd::Digest> = match prev_hash_vec {
                        Some(v) => match akd::hash::try_parse_digest(&v).map_err(|_| cast_err()) {
                            Ok(r) => Some(r),
                            Err(err) => return Err(err),
                        },
                        None => None,
                    };

                    let node = DbRecord::build_tree_node_with_previous_value(
                        label_val_vec.try_into().map_err(|_| cast_err())?,
                        label_len,
                        last_epoch,
                        least_descendant_ep,
                        parent_label_val_vec.try_into().map_err(|_| cast_err())?,
                        parent_label_len,
                        node_type,
                        left_child,
                        right_child,
                        massaged_hash_vec,
                        p_last_epoch,
                        p_least_descendant_ep,
                        massaged_prev_parent_label_val,
                        p_parent_label_len,
                        p_node_type,
                        p_left_child,
                        p_right_child,
                        massaged_prev_hash_vec,
                    );
                    return Ok(DbRecord::TreeNode(node));
                }
            }
            StorageType::ValueState => {
                // `username`, `epoch`, `version`, `node_label_val`, `node_label_len`, `data`
                if let (
                    Some(Ok(username)),
                    Some(Ok(epoch)),
                    Some(Ok(version)),
                    Some(Ok(node_label_val)),
                    Some(Ok(node_label_len)),
                    Some(Ok(data)),
                ) = (
                    row.take_opt(0),
                    row.take_opt(1),
                    row.take_opt(2),
                    row.take_opt(3),
                    row.take_opt(4),
                    row.take_opt(5),
                ) {
                    let node_label_val_vec: Vec<u8> = node_label_val;
                    let state = DbRecord::build_user_state(
                        username,
                        data,
                        version,
                        node_label_len,
                        node_label_val_vec.try_into().map_err(|_| cast_err())?,
                        epoch,
                    );
                    return Ok(DbRecord::ValueState(state));
                }
            }
        }
        // fallback
        let err = MySqlError::Driver(mysql_async::DriverError::FromRow { row: row.clone() });
        Err(err)
    }
}