1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
use crate::component::table::Row;
use crate::component::table::Table;
use crate::storage::bytescoder::BytesCoder;
use crate::storage::diskinterface::{
    DbInfo, DbsJson, DiskError, DiskInterface, TableMeta, TablesJson, UsernameInfo, UsernamesJson,
};
use std::fs;
use std::io::{BufRead, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::Path;

#[derive(Debug, Clone)]
pub struct File {
    /* definition */
// Ideally, File is a stateless struct
}

// TODO: add table-level folders to storage hierarchy
#[allow(dead_code)]
impl File {
    pub fn create_file_base(base_path: &str) -> Result<(), DiskError> {
        // create base data folder if not exists
        if !Path::new(base_path).exists() {
            fs::create_dir_all(base_path)?;
        } else {
            return Err(DiskError::BaseDirExists);
        }

        // create and save an initialized `usernames.json`
        let usernames_json = UsernamesJson { usernames: Vec::new() };
        let usernames_json_path = format!("{}/{}", base_path, "usernames.json");
        let mut usernames_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(usernames_json_path)?;
        usernames_file.write_all(serde_json::to_string_pretty(&usernames_json)?.as_bytes())?;

        Ok(())
    }

    pub fn create_username(username: &str, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward base level
        DiskInterface::storage_hierarchy_check(base_path, None, None, None).map_err(|e| e)?;

        // load current usernames from `usernames.json`
        let usernames_json_path = format!("{}/{}", base_path, "usernames.json");
        let usernames_file = fs::File::open(&usernames_json_path)?;
        let mut usernames_json: UsernamesJson = serde_json::from_reader(usernames_file)?;

        // check if the username exists
        for username_info in &usernames_json.usernames {
            if username_info.name == username {
                return Err(DiskError::UsernameExists);
            }
        }

        // create new username json instance
        let new_username_info = UsernameInfo {
            name: username.to_string(),
            path: username.to_string(),
        };

        // insert the new username record into `usernames.json`
        usernames_json.usernames.push(new_username_info);

        // save `usernames.json`
        let mut usernames_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(usernames_json_path)?;
        usernames_file.write_all(serde_json::to_string_pretty(&usernames_json)?.as_bytes())?;

        // create corresponding directory for the new username
        let username_path = format!("{}/{}", base_path, username);
        fs::create_dir_all(&username_path)?;

        // create corresponding `dbs.json` for the new username
        let dbs_json_path = format!("{}/{}", username_path, "dbs.json");
        let mut dbs_file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(dbs_json_path)?;
        let dbs_json = DbsJson { dbs: Vec::new() };
        dbs_file.write_all(serde_json::to_string_pretty(&dbs_json)?.as_bytes())?;

        Ok(())
    }

    pub fn get_usernames(base_path: &str) -> Result<Vec<String>, DiskError> {
        // perform storage check toward base level
        DiskInterface::storage_hierarchy_check(base_path, None, None, None).map_err(|e| e)?;

        // read and parse `usernames.json`
        let usernames_json_path = format!("{}/{}", base_path, "usernames.json");
        let usernames_file = fs::File::open(&usernames_json_path)?;
        let usernames_json: UsernamesJson = serde_json::from_reader(usernames_file)?;

        // create a vector of usernames
        let usernames = usernames_json
            .usernames
            .iter()
            .map(|username_info| username_info.name.clone())
            .collect::<Vec<String>>();
        Ok(usernames)
    }

    pub fn remove_username(username: &str, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward base level
        DiskInterface::storage_hierarchy_check(base_path, None, None, None).map_err(|e| e)?;

        // read and parse `usernames.json`
        let usernames_json_path = format!("{}/{}", base_path, "usernames.json");
        let usernames_file = fs::File::open(&usernames_json_path)?;
        let mut usernames_json: UsernamesJson = serde_json::from_reader(usernames_file)?;

        // remove if the username exists; otherwise raise error
        let idx_to_remove = usernames_json
            .usernames
            .iter()
            .position(|username_info| &username_info.name == username);
        match idx_to_remove {
            Some(idx) => usernames_json.usernames.remove(idx),
            None => return Err(DiskError::UsernameNotExists),
        };

        // remove corresponding username directory
        let username_path = format!("{}/{}", base_path, username);
        if Path::new(&username_path).exists() {
            fs::remove_dir_all(&username_path)?;
        }

        // overwrite `usernames.json`
        let mut usernames_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(usernames_json_path)?;
        usernames_file.write_all(serde_json::to_string_pretty(&usernames_json)?.as_bytes())?;

        Ok(())
    }

    pub fn create_db(username: &str, db_name: &str, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward username level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), None, None).map_err(|e| e)?;

        // load current dbs from `dbs.json`
        let dbs_json_path = format!("{}/{}/{}", base_path, username, "dbs.json");
        let dbs_file = fs::File::open(&dbs_json_path)?;
        let mut dbs_json: DbsJson = serde_json::from_reader(dbs_file)?;

        // check if the db exists
        for db_info in &dbs_json.dbs {
            if db_info.name == db_name {
                return Err(DiskError::DbExists);
            }
        }

        // create new db json instance
        let new_db_info = DbInfo {
            name: db_name.to_string(),
            path: db_name.to_string(),
        };

        // insert the new db record into `dbs.json`
        dbs_json.dbs.push(new_db_info);

        // save `dbs.json`
        let mut dbs_file = fs::OpenOptions::new().write(true).truncate(true).open(dbs_json_path)?;
        dbs_file.write_all(serde_json::to_string_pretty(&dbs_json)?.as_bytes())?;

        // create corresponding directory for the db
        let db_path = format!("{}/{}/{}", base_path, username, db_name);
        fs::create_dir_all(&db_path)?;

        // create corresponding `tables.json` for the new db
        let tables_json_path = format!("{}/{}", db_path, "tables.json");
        let mut tables_file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(tables_json_path)?;
        let tables_json = TablesJson { tables: Vec::new() };
        tables_file.write_all(serde_json::to_string_pretty(&tables_json)?.as_bytes())?;

        Ok(())
    }

    pub fn get_dbs(username: &str, base_path: &str) -> Result<Vec<String>, DiskError> {
        // perform storage check toward username level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), None, None).map_err(|e| e)?;

        // read and parse `dbs.json`
        let dbs_json_path = format!("{}/{}/{}", base_path, username, "dbs.json");
        let dbs_file = fs::File::open(&dbs_json_path)?;
        let dbs_json: DbsJson = serde_json::from_reader(dbs_file)?;

        // create a vector of dbs
        let dbs = dbs_json
            .dbs
            .iter()
            .map(|db_info| db_info.name.clone())
            .collect::<Vec<String>>();
        Ok(dbs)
    }

    pub fn remove_db(username: &str, db_name: &str, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward username level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), None, None).map_err(|e| e)?;

        // load current dbs from `dbs.json`
        let dbs_json_path = format!("{}/{}/{}", base_path, username, "dbs.json");
        let dbs_file = fs::File::open(&dbs_json_path)?;
        let mut dbs_json: DbsJson = serde_json::from_reader(dbs_file)?;

        // remove if the db exists; otherwise raise error
        let idx_to_remove = dbs_json.dbs.iter().position(|db_info| &db_info.name == db_name);
        match idx_to_remove {
            Some(idx) => dbs_json.dbs.remove(idx),
            None => return Err(DiskError::DbNotExists),
        };

        // remove corresponding db directory
        let db_path = format!("{}/{}/{}", base_path, username, db_name);
        if Path::new(&db_path).exists() {
            fs::remove_dir_all(&db_path)?;
        }

        // overwrite `dbs.json`
        let mut dbs_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(dbs_json_path)?;
        dbs_file.write_all(serde_json::to_string_pretty(&dbs_json)?.as_bytes())?;

        Ok(())
    }

    pub fn create_table(username: &str, db_name: &str, table: &Table, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward db level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), None).map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let mut tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // check if the table exists
        for table_meta in &tables_json.tables {
            if table_meta.name == table.name {
                return Err(DiskError::TableExists);
            }
        }

        // create new table json instance
        let mut new_table_meta = TableMeta {
            name: table.name.to_string(),
            username: username.to_string(),
            db_name: db_name.to_string(),
            path_tsv: format!("{}.tsv", table.name),
            path_bin: format!("{}.bin", table.name),
            primary_key: table.primary_key.clone(),
            foreign_key: table.foreign_key.clone(),
            reference_table: table.reference_table.clone(),
            reference_attr: table.reference_attr.clone(),
            row_length: 0,
            attrs_order: vec![],
            attrs: table.fields.clone(),
            attr_offset_ranges: vec![],
        };

        // determine storing order of attrs in .tsv and .bin
        // `__valid__` and primary key attrs are always at first
        new_table_meta.attrs_order = vec!["__valid__".to_string()];
        new_table_meta
            .attrs_order
            .extend_from_slice(&new_table_meta.primary_key);
        let mut other_attrs: Vec<String> = vec![];
        for (k, _v) in table.fields.iter() {
            if !new_table_meta.primary_key.contains(&k) {
                other_attrs.push(k.clone());
            }
        }
        other_attrs.sort();
        new_table_meta.attrs_order.extend_from_slice(&other_attrs);

        // determine the starting offset of each attribute in a row of bin file
        new_table_meta.attr_offset_ranges = vec![vec![0, 1]];
        let attr_sizes: Vec<u32> = new_table_meta.attrs_order[1..]
            .iter()
            .map(|attr_name| DiskInterface::get_datatype_size(&new_table_meta.attrs[attr_name].datatype))
            .collect();

        // `__valid__` attr occupies 1 byte
        let mut curr_offset = 1;
        for attr_size in attr_sizes {
            new_table_meta
                .attr_offset_ranges
                .push(vec![curr_offset, curr_offset + attr_size]);
            curr_offset += attr_size;
        }
        new_table_meta.row_length = curr_offset;

        // create corresponding bin for the table, which is empty
        let table_bin_path = format!("{}/{}/{}/{}", base_path, username, db_name, new_table_meta.path_bin);
        let mut table_bin_file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(table_bin_path)?;
        table_bin_file.write_all("".as_bytes())?;

        // perform equivalent operation on table tsv
        if dotenv!("ENABLE_TSV") == "true" {
            // create corresponding tsv for the table, with the title line
            let table_tsv_path = format!("{}/{}/{}/{}", base_path, username, db_name, new_table_meta.path_tsv);
            let mut table_tsv_file = fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(table_tsv_path)?;
            table_tsv_file.write_all(new_table_meta.attrs_order.join("\t").as_bytes())?;
        }

        // insert the new table record into `tables.json`
        tables_json.tables.push(new_table_meta);

        // save `tables.json`
        let mut tables_file = fs::OpenOptions::new()
            .write(true)
            .truncate(true)
            .open(tables_json_path)?;
        tables_file.write_all(serde_json::to_string_pretty(&tables_json)?.as_bytes())?;

        Ok(())
    }

    /// get the list of tables in a database
    /// for `show tables`
    pub fn get_tables(username: &str, db_name: &str, base_path: &str) -> Result<Vec<String>, DiskError> {
        // perform storage check toward db level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), None).map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;
        let tables = tables_json
            .tables
            .iter()
            .map(|table| table.name.clone())
            .collect::<Vec<String>>();

        // return the vector of table name
        Ok(tables)
    }

    /// load metadata of all tables from the database
    pub fn load_tables_meta(username: &str, db_name: &str, base_path: &str) -> Result<Vec<TableMeta>, DiskError> {
        // perform storage check toward db level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), None).map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // return the vector of table meta
        Ok(tables_json.tables)
    }

    /// load a particular table meta data
    pub fn load_table_meta(
        username: &str,
        db_name: &str,
        table_name: &str,
        base_path: &str,
    ) -> Result<TableMeta, DiskError> {
        // perform storage check toward db level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), None).map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // return the vector of table meta
        for table in tables_json.tables {
            if &table.name == table_name {
                return Ok(table);
            }
        }
        Err(DiskError::TableNotExists)
    }

    pub fn drop_table(username: &str, db_name: &str, table_name: &str, base_path: &str) -> Result<(), DiskError> {
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let mut tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // remove if the table exists; otherwise raise error
        let idx_to_remove = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);
        match idx_to_remove {
            Some(idx) => tables_json.tables.remove(idx),
            None => return Err(DiskError::TableNotExists),
        };

        // remove corresponding bin file
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        if Path::new(&table_bin_path).exists() {
            fs::remove_file(&table_bin_path)?;
        }

        // perform equivalent operation on table tsv
        if dotenv!("ENABLE_TSV") == "true" {
            // remove corresponding tsv file
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            if Path::new(&table_tsv_path).exists() {
                fs::remove_file(&table_tsv_path)?;
            }
        }

        // overwrite `tables.json`
        let mut tables_file = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(tables_json_path)?;
        tables_file.write_all(serde_json::to_string_pretty(&tables_json)?.as_bytes())?;

        Ok(())
    }

    pub fn append_rows(
        username: &str,
        db_name: &str,
        table_name: &str,
        rows: &Vec<Row>,
        base_path: &str,
    ) -> Result<(), DiskError> {
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // locate meta of target table
        let idx_target = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);

        let table_meta_target: &TableMeta = match idx_target {
            Some(idx) => &tables_json.tables[idx],
            None => return Err(DiskError::TableNotExists),
        };

        // create chunk of bytes to be inserted
        let mut chunk_bytes = vec![];
        for row in rows {
            chunk_bytes.extend_from_slice(&BytesCoder::row_to_bytes(&table_meta_target, row)?);
        }

        // append chunk of bytes to table bin
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let mut table_bin_file = fs::OpenOptions::new().append(true).open(table_bin_path)?;
        table_bin_file.write_all(&chunk_bytes)?;

        // perform equivalent operation on table tsv
        if dotenv!("ENABLE_TSV") == "true" {
            // create chunk of rows to be inserted
            let mut chunk = String::new();
            for row in rows {
                // set `__valid__` to 1
                let mut raw_row = vec!["1".to_string()];
                for attr in table_meta_target.attrs_order[1..].iter() {
                    raw_row.push(row.data.get(attr).ok_or_else(|| DiskError::AttrNotExists)?.clone());
                }
                chunk += &("\n".to_string() + &raw_row.join("\t"));
            }

            // append chunk to table tsv
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            let mut table_tsv_file = fs::OpenOptions::new().append(true).open(table_tsv_path)?;
            table_tsv_file.write_all(chunk.as_bytes())?;
        }

        Ok(())
    }

    pub fn fetch_rows(
        username: &str,
        db_name: &str,
        table_name: &str,
        row_range: &Vec<u32>,
        base_path: &str,
    ) -> Result<Vec<Row>, DiskError> {
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // locate meta of target table
        let idx_target = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);

        let table_meta_target: &TableMeta = match idx_target {
            Some(idx) => &tables_json.tables[idx],
            None => return Err(DiskError::TableNotExists),
        };

        // load corresponding chunk of bytes from table bin
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file = fs::File::open(&table_bin_path)?;
        let mut buffered = BufReader::new(table_bin_file);

        let mut chunk_bytes = vec![];
        buffered.seek(SeekFrom::Start((row_range[0] * table_meta_target.row_length) as u64))?;
        let mut raw = buffered.take(((row_range[1] - row_range[0]) * table_meta_target.row_length) as u64);
        raw.read_to_end(&mut chunk_bytes)?;

        if chunk_bytes.len() != ((row_range[1] - row_range[0]) * table_meta_target.row_length) as usize {
            return Err(DiskError::RangeExceedLatestRecord);
        }

        // parse chunk of bytes to vector of rows
        let mut rows: Vec<Row> = vec![];
        for row_bytes in chunk_bytes.chunks(table_meta_target.row_length as usize) {
            if row_bytes[0] == 0 as u8 {
                return Err(DiskError::RangeContainsDeletedRecord);
            }
            rows.push(BytesCoder::bytes_to_row(&table_meta_target, &row_bytes.to_vec())?);
        }

        // DEPRECATED: load rows from table tsv (functionally same with loading from bin)
        // let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
        // let table_tsv_file = fs::File::open(&table_tsv_path)?;
        // let buffered = BufReader::new(table_tsv_file);

        // let mut rows: Vec<Row> = vec![];
        // let mut curr_idx = row_range[0];
        // for line in buffered.lines().skip((row_range[0] + 1) as usize) {
        //     let raw_line: Vec<String> = line?.replace('\n', "").split('\t').map(|e| e.to_string()).collect();
        //     if raw_line[0] == "0".to_string() {
        //         return Err(DiskError::RangeContainsDeletedRecord);
        //     }
        //     let mut new_row = Row::new();
        //     for i in 1..raw_line.len() {
        //         new_row
        //             .data
        //             .insert(table_meta_target.attrs_order[i].clone(), raw_line[i].clone());
        //     }
        //     rows.push(new_row);
        //     curr_idx += 1;
        //     if curr_idx == row_range[1] {
        //         break;
        //     }
        // }
        // if rows.len() < ((row_range[1] - row_range[0]) as usize) {
        //     return Err(DiskError::RangeExceedLatestRecord);
        // }

        Ok(rows)
    }

    pub fn delete_rows(
        username: &str,
        db_name: &str,
        table_name: &str,
        row_range: &Vec<u32>,
        base_path: &str,
    ) -> Result<(), DiskError> {
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // locate meta of target table
        let idx_target = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);

        let table_meta_target: &TableMeta = match idx_target {
            Some(idx) => &tables_json.tables[idx],
            None => return Err(DiskError::TableNotExists),
        };

        // open table bin for read
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file = fs::OpenOptions::new().read(true).open(table_bin_path)?;
        let mut buffered = BufReader::new(table_bin_file);

        // check if row range contains deleted record
        for row_id in row_range[0]..row_range[1] {
            buffered.seek(SeekFrom::Start((row_id * table_meta_target.row_length) as u64))?;
            let mut valid_byte = [0; 1];
            match buffered.read_exact(&mut valid_byte) {
                Ok(_) => (),
                Err(_) => return Err(DiskError::RangeExceedLatestRecord),
            };
            if valid_byte[0] == 0 as u8 {
                return Err(DiskError::RangeContainsDeletedRecord);
            }
        }

        // open table bin for write
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file = fs::OpenOptions::new().write(true).open(table_bin_path)?;
        let mut buffered = BufWriter::new(table_bin_file);

        // locate the `__valid__` byte for each row and overwrite them to 0
        for row_id in row_range[0]..row_range[1] {
            buffered.seek(SeekFrom::Start((row_id * table_meta_target.row_length) as u64))?;
            let mut del_valid_byte = [0; 1];
            buffered.write_all(&mut del_valid_byte)?;
        }

        // perform equivalent operation on table tsv
        if dotenv!("ENABLE_TSV") == "true" {
            // open table tsv
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            let table_tsv_file = fs::File::open(&table_tsv_path)?;
            let buffered = BufReader::new(table_tsv_file);

            let mut new_content: Vec<String> = vec![];

            // overwrite the `__valid__` attr of rows to delete
            let mut rows_deleted = 0;
            for (idx, line) in buffered.lines().enumerate() {
                if idx < (row_range[0] + 1) as usize || idx > row_range[1] as usize {
                    new_content.push(line?);
                } else {
                    let l = line?;
                    if (&l).starts_with("0") {
                        return Err(DiskError::RangeContainsDeletedRecord);
                    }
                    new_content.push(format!("0{}", &l[1..]));
                    rows_deleted += 1;
                }
            }
            if rows_deleted < row_range[1] - row_range[0] {
                return Err(DiskError::RangeExceedLatestRecord);
            }

            // overwrite table tsv file
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            let mut table_tsv_file = fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(table_tsv_path)?;
            table_tsv_file.write_all(new_content.join("\n").as_bytes())?;
        }

        Ok(())
    }

    pub fn modify_rows(
        username: &str,
        db_name: &str,
        table_name: &str,
        row_range: &Vec<u32>,
        new_rows: &Vec<Row>,
        base_path: &str,
    ) -> Result<(), DiskError> {
        if row_range[1] - row_range[0] != new_rows.len() as u32 {
            return Err(DiskError::RangeAndNumRowsMismatch);
        }
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // locate meta of target table
        let idx_target = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);

        let table_meta_target: &TableMeta = match idx_target {
            Some(idx) => &tables_json.tables[idx],
            None => return Err(DiskError::TableNotExists),
        };

        // open table bin for read
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file = fs::OpenOptions::new().read(true).open(table_bin_path)?;
        let mut buffered = BufReader::new(table_bin_file);

        // check if row range contains deleted record
        for row_id in row_range[0]..row_range[1] {
            buffered.seek(SeekFrom::Start((row_id * table_meta_target.row_length) as u64))?;
            let mut valid_byte = [0; 1];
            match buffered.read_exact(&mut valid_byte) {
                Ok(_) => (),
                Err(_) => return Err(DiskError::RangeExceedLatestRecord),
            };
            if valid_byte[0] == 0 as u8 {
                return Err(DiskError::RangeContainsDeletedRecord);
            }
        }

        // open table bin for write
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file = fs::OpenOptions::new().write(true).open(table_bin_path)?;
        let mut buffered = BufWriter::new(table_bin_file);

        // create modified chunk of bytes
        let mut modified_chunk_bytes: Vec<u8> = vec![];
        for row in new_rows {
            modified_chunk_bytes.extend_from_slice(&BytesCoder::row_to_bytes(&table_meta_target, row)?);
        }

        // overwrite modified chunk of bytes
        buffered.seek(SeekFrom::Start((row_range[0] * table_meta_target.row_length) as u64))?;
        buffered.write_all(&mut modified_chunk_bytes)?;

        // perform equivalent operation on table tsv
        if dotenv!("ENABLE_TSV") == "true" {
            // create modified rows
            let mut modified_content: Vec<String> = vec![];
            for row in new_rows {
                // set `__valid__` to 1
                let mut raw_row = vec!["1".to_string()];
                for attr in table_meta_target.attrs_order[1..].iter() {
                    raw_row.push(row.data.get(attr).ok_or_else(|| DiskError::AttrNotExists)?.clone());
                }
                modified_content.push(raw_row.join("\t"));
            }

            // open table tsv
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            let table_tsv_file = fs::File::open(&table_tsv_path)?;
            let buffered = BufReader::new(table_tsv_file);

            // overwrite the rows to be modified
            let mut new_content: Vec<String> = vec![];
            let mut rows_modified = 0;
            for (idx, line) in buffered.lines().enumerate() {
                if idx < (row_range[0] + 1) as usize || idx > row_range[1] as usize {
                    new_content.push(line?);
                } else {
                    let l = line?;
                    if (&l).starts_with("0") {
                        return Err(DiskError::RangeContainsDeletedRecord);
                    }
                    new_content.push(modified_content[idx - (row_range[0] + 1) as usize].clone());
                    rows_modified += 1;
                }
            }
            if rows_modified < row_range[1] - row_range[0] {
                return Err(DiskError::RangeExceedLatestRecord);
            }

            // overwrite table tsv file
            let table_tsv_path = format!("{}/{}/{}/{}.tsv", base_path, username, db_name, table_name);
            let mut table_tsv_file = fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(table_tsv_path)?;
            table_tsv_file.write_all(new_content.join("\n").as_bytes())?;
        }

        Ok(())
    }

    pub fn get_num_rows(username: &str, db_name: &str, table_name: &str, base_path: &str) -> Result<u32, DiskError> {
        // perform storage check toward table level
        DiskInterface::storage_hierarchy_check(base_path, Some(username), Some(db_name), Some(table_name))
            .map_err(|e| e)?;

        // load current tables from `tables.json`
        let tables_json_path = format!("{}/{}/{}/{}", base_path, username, db_name, "tables.json");
        let tables_file = fs::File::open(&tables_json_path)?;
        let tables_json: TablesJson = serde_json::from_reader(tables_file)?;

        // locate meta of target table
        let idx_target = tables_json
            .tables
            .iter()
            .position(|table_meta| &table_meta.name == table_name);

        let table_meta_target: &TableMeta = match idx_target {
            Some(idx) => &tables_json.tables[idx],
            None => return Err(DiskError::TableNotExists),
        };

        // load corresponding chunk of bytes from table bin
        let table_bin_path = format!("{}/{}/{}/{}.bin", base_path, username, db_name, table_name);
        let table_bin_file_meta = fs::metadata(&table_bin_path)?;

        Ok((table_bin_file_meta.len() / table_meta_target.row_length as u64) as u32)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::component::datatype::DataType;
    use crate::component::field;
    use crate::component::field::Field;
    use std::collections::HashMap;

    #[test]
    pub fn test_create_file_base() {
        let file_base_path = "data0";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();

        assert!(Path::new(file_base_path).exists());

        let usernames_json_path = format!("{}/{}", file_base_path, "usernames.json");
        assert!(Path::new(&usernames_json_path).exists());

        assert_eq!(
            DiskInterface::create_file_base(Some(file_base_path)).unwrap_err(),
            DiskError::BaseDirExists
        );
    }

    #[test]
    pub fn test_create_username() {
        let file_base_path = "data1";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_username("happyguy", Some(file_base_path)).unwrap();

        let usernames_json_path = format!("{}/{}", file_base_path, "usernames.json");
        let usernames_json = fs::read_to_string(usernames_json_path).unwrap();
        let usernames_json: UsernamesJson = serde_json::from_str(&usernames_json).unwrap();

        let ideal_usernames_json = UsernamesJson {
            usernames: vec![
                UsernameInfo {
                    name: "crazyguy".to_string(),
                    path: "crazyguy".to_string(),
                },
                UsernameInfo {
                    name: "happyguy".to_string(),
                    path: "happyguy".to_string(),
                },
            ],
        };

        assert_eq!(usernames_json.usernames[0].name, ideal_usernames_json.usernames[0].name);
        assert_eq!(usernames_json.usernames[1].name, ideal_usernames_json.usernames[1].name);
        assert_eq!(usernames_json.usernames[0].path, ideal_usernames_json.usernames[0].path);
        assert_eq!(usernames_json.usernames[1].path, ideal_usernames_json.usernames[1].path);

        assert!(Path::new(&format!("{}/{}", file_base_path, "crazyguy")).exists());
        assert!(Path::new(&format!("{}/{}", file_base_path, "happyguy")).exists());

        assert!(Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "dbs.json")).exists());
        assert!(Path::new(&format!("{}/{}/{}", file_base_path, "happyguy", "dbs.json")).exists());

        let dbs_json = fs::read_to_string(format!("{}/{}/{}", file_base_path, "crazyguy", "dbs.json")).unwrap();
        let dbs_json: DbsJson = serde_json::from_str(&dbs_json).unwrap();

        assert_eq!(dbs_json.dbs.len(), 0);

        assert_eq!(
            DiskInterface::create_username("happyguy", Some(file_base_path)).unwrap_err(),
            DiskError::UsernameExists
        );
    }

    #[test]
    pub fn test_get_usernames() {
        let file_base_path = "data2";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_username("happyguy", Some(file_base_path)).unwrap();

        let usernames: Vec<String> = DiskInterface::get_usernames(Some(file_base_path)).unwrap();
        assert_eq!(usernames, vec!["crazyguy", "happyguy"]);
    }

    #[test]
    pub fn test_remove_username() {
        let file_base_path = "data3";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_username("happyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_username("sadguy", Some(file_base_path)).unwrap();

        let usernames: Vec<String> = DiskInterface::get_usernames(Some(file_base_path)).unwrap();
        assert_eq!(usernames, vec!["crazyguy", "happyguy", "sadguy"]);

        DiskInterface::remove_username("happyguy", Some(file_base_path)).unwrap();

        let usernames: Vec<String> = DiskInterface::get_usernames(Some(file_base_path)).unwrap();
        assert_eq!(usernames, vec!["crazyguy", "sadguy"]);

        assert_eq!(
            DiskInterface::remove_username("happyguy", Some(file_base_path)).unwrap_err(),
            DiskError::UsernameNotExists
        );

        DiskInterface::remove_username("sadguy", Some(file_base_path)).unwrap();

        let usernames: Vec<String> = DiskInterface::get_usernames(Some(file_base_path)).unwrap();
        assert_eq!(usernames, vec!["crazyguy"]);

        DiskInterface::remove_username("crazyguy", Some(file_base_path)).unwrap();

        let usernames: Vec<String> = DiskInterface::get_usernames(Some(file_base_path)).unwrap();
        assert_eq!(usernames.len(), 0);
    }

    #[test]
    pub fn test_create_db() {
        let file_base_path = "data4";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "MovieDB", Some(file_base_path)).unwrap();

        let dbs_json_path = format!("{}/{}/{}", file_base_path, "crazyguy", "dbs.json");
        assert!(Path::new(&dbs_json_path).exists());

        let dbs_json = fs::read_to_string(dbs_json_path).unwrap();
        let dbs_json: DbsJson = serde_json::from_str(&dbs_json).unwrap();

        let ideal_dbs_json = DbsJson {
            dbs: vec![
                DbInfo {
                    name: "BookerDB".to_string(),
                    path: "BookerDB".to_string(),
                },
                DbInfo {
                    name: "MovieDB".to_string(),
                    path: "MovieDB".to_string(),
                },
            ],
        };

        assert_eq!(dbs_json.dbs[0].name, ideal_dbs_json.dbs[0].name);
        assert_eq!(dbs_json.dbs[1].name, ideal_dbs_json.dbs[1].name);
        assert_eq!(dbs_json.dbs[0].path, ideal_dbs_json.dbs[0].path);
        assert_eq!(dbs_json.dbs[1].path, ideal_dbs_json.dbs[1].path);

        assert!(Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "BookerDB")).exists());
        assert!(Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "MovieDB")).exists());

        assert!(Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "tables.json"
        ))
        .exists());
        assert!(Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "MovieDB", "tables.json"
        ))
        .exists());

        let tables_json = fs::read_to_string(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "tables.json"
        ))
        .unwrap();
        let tables_json: TablesJson = serde_json::from_str(&tables_json).unwrap();

        assert_eq!(tables_json.tables.len(), 0);

        assert_eq!(
            DiskInterface::create_db("happyguy", "BookerDB", Some(file_base_path)).unwrap_err(),
            DiskError::UsernameNotExists
        );
        assert_eq!(
            DiskInterface::create_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap_err(),
            DiskError::DbExists
        );
    }

    #[test]
    pub fn test_get_dbs() {
        let file_base_path = "data5";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("happyguy", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("happyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs.len(), 0);

        DiskInterface::create_db("happyguy", "BookerDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("happyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs, vec!["BookerDB"]);

        DiskInterface::create_db("happyguy", "MovieDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("happyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs, vec!["BookerDB", "MovieDB"]);

        assert_eq!(
            DiskInterface::get_dbs("sadguy", Some(file_base_path)).unwrap_err(),
            DiskError::UsernameNotExists
        );
    }

    #[test]
    pub fn test_remove_db() {
        let file_base_path = "data6";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "MovieDB", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "PhotoDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("crazyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs, vec!["BookerDB", "MovieDB", "PhotoDB"]);

        DiskInterface::remove_db("crazyguy", "MovieDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("crazyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs, vec!["BookerDB", "PhotoDB"]);

        assert_eq!(
            DiskInterface::remove_db("happyguy", "BookerDB", Some(file_base_path)).unwrap_err(),
            DiskError::UsernameNotExists
        );

        DiskInterface::remove_db("crazyguy", "PhotoDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("crazyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs, vec!["BookerDB"]);

        assert_eq!(
            DiskInterface::remove_db("crazyguy", "PhotoDB", Some(file_base_path)).unwrap_err(),
            DiskError::DbNotExists
        );

        DiskInterface::remove_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        let dbs: Vec<String> = DiskInterface::get_dbs("crazyguy", Some(file_base_path)).unwrap();
        assert_eq!(dbs.len(), 0);

        assert!(!Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "BookerDB")).exists());
        assert!(!Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "MovieDB")).exists());
        assert!(!Path::new(&format!("{}/{}/{}", file_base_path, "crazyguy", "PhotoDB")).exists());
    }

    #[test]
    pub fn test_create_get_load_drop_table() {
        let file_base_path = "data7";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        let mut aff_table = Table::new("Affiliates");
        aff_table.fields.insert(
            "AffID".to_string(),
            Field::new_all("AffID", DataType::Int, true, None, field::Checker::None, false),
        );
        aff_table.fields.insert(
            "AffName".to_string(),
            Field::new_all(
                "AffName",
                DataType::Varchar(40),
                true,
                None,
                field::Checker::None,
                false,
            ),
        );
        aff_table.fields.insert(
            "AffEmail".to_string(),
            Field::new_all(
                "AffEmail",
                DataType::Varchar(50),
                true,
                None,
                field::Checker::None,
                false,
            ),
        );
        aff_table.fields.insert(
            "AffPhoneNum".to_string(),
            Field::new_all(
                "AffPhoneNum",
                DataType::Varchar(20),
                false,
                Some("+886900000000".to_string()),
                field::Checker::None,
                false,
            ),
        );
        aff_table.primary_key.push("AffID".to_string());

        DiskInterface::create_table("crazyguy", "BookerDB", &aff_table, Some(file_base_path)).unwrap();

        let mut htl_table = Table::new("Hotels");
        htl_table.fields.insert(
            "HotelID".to_string(),
            Field::new_all("HotelID", DataType::Int, true, None, field::Checker::None, false),
        );
        htl_table.fields.insert(
            "HotelName".to_string(),
            Field::new_all(
                "HotelName",
                DataType::Varchar(40),
                true,
                None,
                field::Checker::None,
                false,
            ),
        );
        htl_table.fields.insert(
            "HotelType".to_string(),
            Field::new_all(
                "HotelType",
                DataType::Varchar(20),
                false,
                Some("Homestay".to_string()),
                field::Checker::None,
                false,
            ),
        );
        htl_table.fields.insert(
            "HotelAddr".to_string(),
            Field::new_all(
                "HotelAddr",
                DataType::Varchar(50),
                false,
                Some("".to_string()),
                field::Checker::None,
                false,
            ),
        );
        htl_table.primary_key.push("HotelID".to_string());

        DiskInterface::create_table("crazyguy", "BookerDB", &htl_table, Some(file_base_path)).unwrap();

        let ideal_tables = vec![
            TableMeta {
                name: "Affiliates".to_string(),
                username: "crazyguy".to_string(),
                db_name: "BookerDB".to_string(),
                path_tsv: "Affiliates.tsv".to_string(),
                path_bin: "Affiliates.bin".to_string(),
                primary_key: vec!["AffID".to_string()],
                foreign_key: vec![],
                reference_table: None,
                reference_attr: None,
                attr_offset_ranges: vec![vec![0, 1], vec![1, 5], vec![5, 55], vec![55, 95], vec![95, 115]],
                row_length: 115,
                // ignore attrs checking
                attrs_order: vec![],
                attrs: HashMap::new(),
            },
            TableMeta {
                name: "Hotels".to_string(),
                username: "crazyguy".to_string(),
                db_name: "BookerDB".to_string(),
                path_tsv: "Hotels.tsv".to_string(),
                path_bin: "Hotels.bin".to_string(),
                primary_key: vec!["HotelID".to_string()],
                foreign_key: vec![],
                reference_table: None,
                reference_attr: None,
                attr_offset_ranges: vec![vec![0, 1], vec![1, 5], vec![5, 55], vec![55, 95], vec![95, 115]],
                row_length: 115,
                // ignore attrs checking
                attrs_order: vec![],
                attrs: HashMap::new(),
            },
        ];

        let table_names = DiskInterface::get_tables("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        for i in 0..ideal_tables.len() {
            assert_eq!(table_names[i], ideal_tables[i].name);
        }

        // load_table_meta
        assert!(DiskInterface::load_table_meta("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).is_ok());
        assert!(DiskInterface::load_table_meta("crazyguy", "BookerDB", "none_table", Some(file_base_path)).is_err());

        let tables = DiskInterface::load_tables_meta("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        assert_eq!(tables.len(), 2);

        for i in 0..tables.len() {
            assert_eq!(tables[i].name, ideal_tables[i].name);
            assert_eq!(tables[i].username, ideal_tables[i].username);
            assert_eq!(tables[i].db_name, ideal_tables[i].db_name);
            assert_eq!(tables[i].path_tsv, ideal_tables[i].path_tsv);
            assert_eq!(tables[i].path_bin, ideal_tables[i].path_bin);
            assert_eq!(tables[i].primary_key, ideal_tables[i].primary_key);
            assert_eq!(tables[i].foreign_key, ideal_tables[i].foreign_key);
            assert_eq!(tables[i].reference_table, ideal_tables[i].reference_table);
            assert_eq!(tables[i].reference_attr, ideal_tables[i].reference_attr);
            assert_eq!(tables[i].row_length, ideal_tables[i].row_length);
            assert_eq!(tables[i].attr_offset_ranges, ideal_tables[i].attr_offset_ranges);
        }

        assert!(Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "Affiliates.bin"
        ))
        .exists());
        assert!(Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "Hotels.bin"
        ))
        .exists());

        if dotenv!("ENABLE_TSV") == "true" {
            assert!(Path::new(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .exists());
            assert!(Path::new(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Hotels.tsv"
            ))
            .exists());

            let aff_tsv_content: Vec<String> = fs::read_to_string(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .unwrap()
            .split('\t')
            .map(|s| s.to_string())
            .collect();

            assert_eq!(aff_tsv_content[0], "__valid__".to_string());
            assert_eq!(aff_tsv_content[1], "AffID".to_string());
            assert_eq!(aff_tsv_content.len(), 5);
        }

        assert_eq!(
            DiskInterface::create_table("happyguy", "BookerDB", &htl_table, Some(file_base_path)).unwrap_err(),
            DiskError::UsernameNotExists
        );
        assert_eq!(
            DiskInterface::create_table("crazyguy", "MusicDB", &htl_table, Some(file_base_path)).unwrap_err(),
            DiskError::DbNotExists
        );
        assert_eq!(
            DiskInterface::create_table("crazyguy", "BookerDB", &htl_table, Some(file_base_path)).unwrap_err(),
            DiskError::TableExists
        );

        DiskInterface::drop_table("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).unwrap();

        assert!(!Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "Affiliates.bin"
        ))
        .exists());

        if dotenv!("ENABLE_TSV") == "true" {
            assert!(!Path::new(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .exists());
        }

        let tables = DiskInterface::load_tables_meta("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        assert_eq!(tables.len(), 1);

        assert_eq!(
            DiskInterface::drop_table("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).unwrap_err(),
            DiskError::TableNotExists
        );

        DiskInterface::drop_table("crazyguy", "BookerDB", "Hotels", Some(file_base_path)).unwrap();

        assert!(!Path::new(&format!(
            "{}/{}/{}/{}",
            file_base_path, "crazyguy", "BookerDB", "Hotels.bin"
        ))
        .exists());

        if dotenv!("ENABLE_TSV") == "true" {
            assert!(!Path::new(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Hotels.tsv"
            ))
            .exists());
        }

        let tables = DiskInterface::load_tables_meta("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        assert_eq!(tables.len(), 0);
    }

    #[test]
    pub fn test_append_fetch_delete_modify_rows() {
        let file_base_path = "data8";
        if Path::new(file_base_path).exists() {
            fs::remove_dir_all(file_base_path).unwrap();
        }

        DiskInterface::create_file_base(Some(file_base_path)).unwrap();
        DiskInterface::create_username("crazyguy", Some(file_base_path)).unwrap();
        DiskInterface::create_db("crazyguy", "BookerDB", Some(file_base_path)).unwrap();

        let mut aff_table = Table::new("Affiliates");
        aff_table.fields.insert(
            "AffID".to_string(),
            Field::new_all("AffID", DataType::Int, true, None, field::Checker::None, false),
        );
        aff_table.fields.insert(
            "AffName".to_string(),
            Field::new_all(
                "AffName",
                DataType::Varchar(40),
                true,
                None,
                field::Checker::None,
                false,
            ),
        );
        aff_table.fields.insert(
            "AffEmail".to_string(),
            Field::new_all(
                "AffEmail",
                DataType::Varchar(50),
                true,
                None,
                field::Checker::None,
                false,
            ),
        );
        aff_table.fields.insert(
            "AffPhoneNum".to_string(),
            Field::new_all(
                "AffPhoneNum",
                DataType::Varchar(20),
                false,
                Some("+886900000000".to_string()),
                field::Checker::None,
                false,
            ),
        );
        aff_table.primary_key.push("AffID".to_string());

        DiskInterface::create_table("crazyguy", "BookerDB", &aff_table, Some(file_base_path)).unwrap();

        let data = vec![
            ("AffID", "1"),
            ("AffName", "Tom"),
            ("AffEmail", "tom@foo.com"),
            ("AffPhoneNum", "+886900000001"),
        ];
        aff_table.insert_row(data).unwrap();

        DiskInterface::append_rows(
            "crazyguy",
            "BookerDB",
            "Affiliates",
            &aff_table.rows,
            Some(file_base_path),
        )
        .unwrap();

        if dotenv!("ENABLE_TSV") == "true" {
            let aff_tsv_content: Vec<String> = fs::read_to_string(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .unwrap()
            .split('\n')
            .map(|s| s.to_string())
            .collect();

            assert_eq!(aff_tsv_content.len(), 2);
            assert_eq!(aff_tsv_content[1], "1\t1\ttom@foo.com\tTom\t+886900000001".to_string());
        }

        let data = vec![
            ("AffID", "2"),
            ("AffName", "Ben"),
            ("AffEmail", "ben@foo.com"),
            ("AffPhoneNum", "+886900000002"),
        ];
        aff_table.insert_row(data).unwrap();
        let data = vec![
            ("AffID", "3"),
            ("AffName", "Leo"),
            ("AffEmail", "leo@dee.com"),
            ("AffPhoneNum", "+886900000003"),
        ];
        aff_table.insert_row(data).unwrap();

        DiskInterface::append_rows(
            "crazyguy",
            "BookerDB",
            "Affiliates",
            &aff_table.rows[1..].iter().cloned().collect(),
            Some(file_base_path),
        )
        .unwrap();

        if dotenv!("ENABLE_TSV") == "true" {
            let aff_tsv_content: Vec<String> = fs::read_to_string(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .unwrap()
            .split('\n')
            .map(|s| s.to_string())
            .collect();

            assert_eq!(aff_tsv_content.len(), 4);
            assert_eq!(aff_tsv_content[1], "1\t1\ttom@foo.com\tTom\t+886900000001".to_string());
            assert_eq!(aff_tsv_content[2], "1\t2\tben@foo.com\tBen\t+886900000002".to_string());
            assert_eq!(aff_tsv_content[3], "1\t3\tleo@dee.com\tLeo\t+886900000003".to_string());
        }

        assert_eq!(
            DiskInterface::get_num_rows("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).unwrap(),
            3
        );

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![0, 1], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 1);

        for (attr, val) in aff_table.rows[0].data.iter() {
            assert_eq!(val.clone(), rows[0].data[attr]);
        }

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![0, 3], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 3);

        for i in 0..3 {
            for (attr, val) in aff_table.rows[i].data.iter() {
                assert_eq!(val.clone(), rows[i].data[attr]);
            }
        }

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![1, 3], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 2);

        for i in 0..2 {
            for (attr, val) in aff_table.rows[i + 1].data.iter() {
                assert_eq!(val.clone(), rows[i].data[attr]);
            }
        }

        assert_eq!(
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![2, 4], Some(file_base_path))
                .unwrap_err(),
            DiskError::RangeExceedLatestRecord
        );

        DiskInterface::delete_rows("crazyguy", "BookerDB", "Affiliates", &vec![1, 2], Some(file_base_path)).unwrap();

        assert_eq!(
            DiskInterface::delete_rows("crazyguy", "BookerDB", "Affiliates", &vec![1, 2], Some(file_base_path))
                .unwrap_err(),
            DiskError::RangeContainsDeletedRecord,
        );

        assert_eq!(
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![0, 2], Some(file_base_path))
                .unwrap_err(),
            DiskError::RangeContainsDeletedRecord,
        );

        DiskInterface::delete_rows("crazyguy", "BookerDB", "Affiliates", &vec![0, 1], Some(file_base_path)).unwrap();

        if dotenv!("ENABLE_TSV") == "true" {
            let aff_tsv_content: Vec<String> = fs::read_to_string(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .unwrap()
            .split('\n')
            .map(|s| s.to_string())
            .collect();

            assert_eq!(aff_tsv_content.len(), 4);
            assert_eq!(aff_tsv_content[1], "0\t1\ttom@foo.com\tTom\t+886900000001".to_string());
            assert_eq!(aff_tsv_content[2], "0\t2\tben@foo.com\tBen\t+886900000002".to_string());
            assert_eq!(aff_tsv_content[3], "1\t3\tleo@dee.com\tLeo\t+886900000003".to_string());
        }

        let data = vec![
            ("AffID", "4"),
            ("AffName", "John"),
            ("AffEmail", "john@dee.com"),
            ("AffPhoneNum", "+886900000004"),
        ];
        aff_table.insert_row(data).unwrap();

        let data = vec![
            ("AffID", "5"),
            ("AffName", "Ray"),
            ("AffEmail", "ray@dee.com"),
            ("AffPhoneNum", "+886900000005"),
        ];
        aff_table.insert_row(data).unwrap();

        let data = vec![
            ("AffID", "6"),
            ("AffName", "Bryn"),
            ("AffEmail", "bryn@dee.com"),
            ("AffPhoneNum", "+886900000006"),
        ];
        aff_table.insert_row(data).unwrap();

        DiskInterface::append_rows(
            "crazyguy",
            "BookerDB",
            "Affiliates",
            &aff_table.rows[3..].iter().cloned().collect(),
            Some(file_base_path),
        )
        .unwrap();

        if dotenv!("ENABLE_TSV") == "true" {
            let aff_tsv_content: Vec<String> = fs::read_to_string(&format!(
                "{}/{}/{}/{}",
                file_base_path, "crazyguy", "BookerDB", "Affiliates.tsv"
            ))
            .unwrap()
            .split('\n')
            .map(|s| s.to_string())
            .collect();

            assert_eq!(aff_tsv_content.len(), 7);
        }

        assert_eq!(
            DiskInterface::delete_rows("crazyguy", "BookerDB", "Affiliates", &vec![5, 7], Some(file_base_path))
                .unwrap_err(),
            DiskError::RangeExceedLatestRecord
        );

        DiskInterface::delete_rows("crazyguy", "BookerDB", "Affiliates", &vec![5, 6], Some(file_base_path)).unwrap();

        assert_eq!(
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![5, 6], Some(file_base_path))
                .unwrap_err(),
            DiskError::RangeContainsDeletedRecord,
        );

        assert_eq!(
            DiskInterface::get_num_rows("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).unwrap(),
            6
        );

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![2, 5], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 3);

        for i in 0..3 {
            for (attr, val) in aff_table.rows[i + 2].data.iter() {
                assert_eq!(val.clone(), rows[i].data[attr]);
            }
        }

        *aff_table.rows[2].data.get_mut("AffName").unwrap() = "Leow".to_string();
        *aff_table.rows[4].data.get_mut("AffEmail").unwrap() = "raymond@dee.com".to_string();
        *aff_table.rows[4].data.get_mut("AffPhoneNum").unwrap() = "+886900000015".to_string();
        DiskInterface::modify_rows(
            "crazyguy",
            "BookerDB",
            "Affiliates",
            &vec![2, 5],
            &aff_table.rows[2..5].iter().cloned().collect(),
            Some(file_base_path),
        )
        .unwrap();

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![2, 5], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 3);

        for i in 0..3 {
            for (attr, val) in aff_table.rows[i + 2].data.iter() {
                assert_eq!(val.clone(), rows[i].data[attr]);
            }
        }

        assert_eq!(
            DiskInterface::modify_rows(
                "crazyguy",
                "BookerDB",
                "Affiliates",
                &vec![1, 4],
                &aff_table.rows[1..4].iter().cloned().collect(),
                Some(file_base_path)
            )
            .unwrap_err(),
            DiskError::RangeContainsDeletedRecord
        );

        let data = vec![
            ("AffID", "7"),
            ("AffName", "Eric"),
            ("AffEmail", "eric@doo.com"),
            ("AffPhoneNum", "+886900000007"),
        ];
        aff_table.insert_row(data).unwrap();

        let data = vec![
            ("AffID", "8"),
            ("AffName", "Vinc"),
            ("AffEmail", "vinc@doo.com"),
            ("AffPhoneNum", "+886900000008"),
        ];
        aff_table.insert_row(data).unwrap();

        DiskInterface::append_rows(
            "crazyguy",
            "BookerDB",
            "Affiliates",
            &aff_table.rows[6..].iter().cloned().collect(),
            Some(file_base_path),
        )
        .unwrap();

        assert_eq!(
            DiskInterface::modify_rows(
                "crazyguy",
                "BookerDB",
                "Affiliates",
                &vec![6, 10],
                &aff_table.rows[1..4].iter().cloned().collect(),
                Some(file_base_path)
            )
            .unwrap_err(),
            DiskError::RangeAndNumRowsMismatch
        );

        assert_eq!(
            DiskInterface::modify_rows(
                "crazyguy",
                "BookerDB",
                "Affiliates",
                &vec![6, 9],
                &aff_table.rows[1..4].iter().cloned().collect(),
                Some(file_base_path)
            )
            .unwrap_err(),
            DiskError::RangeExceedLatestRecord
        );

        assert_eq!(
            DiskInterface::get_num_rows("crazyguy", "BookerDB", "Affiliates", Some(file_base_path)).unwrap(),
            8
        );

        let rows: Vec<Row> =
            DiskInterface::fetch_rows("crazyguy", "BookerDB", "Affiliates", &vec![6, 8], Some(file_base_path)).unwrap();

        assert_eq!(rows.len(), 2);

        for i in 0..2 {
            for (attr, val) in aff_table.rows[i + 6].data.iter() {
                assert_eq!(val.clone(), rows[i].data[attr]);
            }
        }
    }
}