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
//! MySQL implementation.

#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::{
    archiver::YotsubaArchiver,
    enums::{YotsubaBoard, YotsubaEndpoint, YotsubaHash, YotsubaIdentifier},
    sql::*
};
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use enum_iterator::IntoEnumIterator;
use mysql_async::{prelude::*, Pool, Row};
use std::{
    boxed::Box,
    collections::{BTreeSet, HashSet},
    convert::TryFrom,
    sync::{Arc, Mutex}
};

pub type Statement = mysql_async::Stmt<mysql_async::Conn>;

// Exif field in Asagi schema
// pub struct Exif {
//     uniqueIps: String,
//     archivedOn: u64,
//     since4pass: String,
//     trollCountry: String
// }
#[cold]
#[allow(dead_code)]
pub mod asagi {

    #[cold]
    #[allow(dead_code)]
    pub struct Post {
        pub poster_ip:            i32,
        pub num:                  i32,
        pub subnum:               i32,
        pub thread_num:           i32,
        pub unique_ips:           i32,
        pub since4pass:           i32,
        pub op:                   bool,
        pub date:                 i64,
        pub preview_orig:         String,
        pub preview_w:            i32,
        pub preview_h:            i32,
        pub media_id:             i32,
        pub media_orig:           String,
        pub media_w:              i32,
        pub media_h:              i32,
        pub media_size:           i32,
        pub media_hash:           String,
        pub media_filename:       String,
        pub spoiler:              bool,
        pub deleted:              bool,
        pub capcode:              String,
        pub email:                String,
        pub name:                 String,
        pub trip:                 String,
        pub title:                String,
        pub comment:              String,
        pub delpass:              String,
        pub sticky:               bool,
        pub closed:               bool,
        pub archived:             bool,
        pub poster_hash:          String,
        pub poster_country:       String,
        pub poster_troll_country: String,
        pub exif:                 String,
        pub link:                 String,
        pub r#type:               String,
        pub omitted:              bool
    }
}

#[async_trait]
impl Archiver for YotsubaArchiver<Statement, mysql_async::Row, Pool, reqwest::Client> {
    async fn run_inner(&self) -> Result<()> {
        Ok(self.run().await?)
    }
}

impl QueryRaw for Pool {
    fn inquiry(&self, statement: YotsubaStatement, id: QueryIdentifier) -> String {
        match statement {
            YotsubaStatement::InitSchema => format!(
                r#"
            SET SESSION transaction_isolation='READ-COMMITTED';
            begin;
            -- SET GLOBAL binlog_format = 'ROW';
            
            CREATE TABLE IF NOT EXISTS `index_counters` (
                `id` varchar(50) NOT NULL,
                `val` int(10) NOT NULL,
                PRIMARY KEY (`id`)
              ) ENGINE={engine} DEFAULT CHARSET={charset};
              
              
              DROP FUNCTION IF EXISTS doCleanFull;
              CREATE FUNCTION doCleanFull (com TEXT)
              RETURNS TEXT DETERMINISTIC
              RETURN	
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(	
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(
                  REGEXP_REPLACE(com, '&#039;', '\'')
                  , '&gt;', '>')
                  , '&lt;', '<')
                  , '&quot;', '"')
                  , '&amp;', '&')
                  , '\\s*$', '')
                  , '^\\s*$', '')
                  , '<span class=\"capcodeReplies\"><span style=\"font-size: smaller;\"><span style=\"font-weight: bold;\">(?:Administrator|Moderator|Developer) Repl(?:y|ies):</span>.*?</span><br></span>', '')
                  , '\\[(/?(banned|moot|spoiler|code))]', '[$1:lit]')
                  , '<span class=\"abbr\">.*?</span>', '')
                  , '<table class=\"exif\"[^>]*>.*?</table>', '')
                  , '<br><br><small><b>Oekaki Post</b>.*?</small>', '')
                  , '<(?:b|strong) style=\"color:\\s*red;\">(.*?)</(?:b|strong)>', '[banned]$1[/banned]')
                  , '<div style=\"padding: 5px;margin-left: \\.5em;border-color: #faa;border: 2px dashed rgba\\(255,0,0,\\.1\\);border-radius: 2px\">(.*?)</div>', '[moot]$1[/moot]')
                  , '<span class=\"fortune\" style=\"color:(.*?)\"><br><br><b>(.*?)</b></span>', '\n\n[fortune color=\"$1\"]$2[/fortune]')
                  , '<(?:b|strong)>(.*?)</(?:b|strong)>', '[b]$1[/b]')
                  , '<pre[^>]*>', '[code]')
                  , '</pre>', '[/code]')
                  , '<span class=\"math\">(.*?)</span>', '[math]$1[/math]')
                  , '<div class=\"math\">(.*?)</div>', '[eqn]$1[/eqn]')
                  , '<font class=\"unkfunc\">(.*?)</font>', '$1')
                  , '<span class=\"quote\">(.*?)</span>', '$1')
                  , '<span class=\"(?:[^\"]*)?deadlink\">(.*?)</span>', '$1')
                  , '<a[^>]*>(.*?)</a>', '$1')
                  , '<span class=\"spoiler\"[^>]*>(.*?)</span>', '[spoiler]$1[/spoiler]')
                  , '<span class=\"sjis\">(.*?)</span>', '[shiftjis]$1[/shiftjis]')
                  , '<s>', '[spoiler]')
                  , '</s>', '[/spoiler]')
                  , '<wbr>', '')
                  , '<br\\s*/?>', '\n');
              "#,
                engine = id.engine.mysql_engine(),
                charset = id.charset.unwrap()
            ),
            YotsubaStatement::InitType => "select 1".into(),
            YotsubaStatement::InitMetadata => format!(
                "
                CREATE TABLE IF NOT EXISTS `metadata` (
                    `board` varchar(10) NOT NULL PRIMARY key unique ,
                    `threads` json,
                    `archive` json,
                    INDEX metadata_board_idx (`board`)
                ) ENGINE={engine} CHARSET={charset} COLLATE={charset}_general_ci;
                ",
                engine = id.engine.mysql_engine(),
                charset = id.charset.unwrap()
            ),
            YotsubaStatement::InitBoard => {
                let s = id.schema.unwrap_or("".into());
                let base = format!(
                    r#"CREATE TABLE IF NOT EXISTS `{board}` (
                    `doc_id` int unsigned NOT NULL auto_increment,
                    `media_id` int unsigned NOT NULL DEFAULT '0',
                    `poster_ip` decimal(39,0) unsigned NOT NULL DEFAULT '0',
                    `num` int unsigned NOT NULL,
                    `subnum` int unsigned NOT NULL,
                    `thread_num` int unsigned NOT NULL DEFAULT '0',
                    `op` bool NOT NULL DEFAULT '0',
                    `timestamp` int unsigned NOT NULL,
                    `timestamp_expired` int unsigned NOT NULL,
                    `preview_orig` varchar(20),
                    `preview_w` smallint unsigned NOT NULL DEFAULT '0',
                    `preview_h` smallint unsigned NOT NULL DEFAULT '0',
                    `media_filename` text,
                    `media_w` smallint unsigned NOT NULL DEFAULT '0',
                    `media_h` smallint unsigned NOT NULL DEFAULT '0',
                    `media_size` int unsigned NOT NULL DEFAULT '0',
                    `media_hash` varchar(25),
                    `media_orig` varchar(20),
                    `spoiler` bool NOT NULL DEFAULT '0',
                    `deleted` bool NOT NULL DEFAULT '0',
                    `capcode` varchar(1) NOT NULL DEFAULT 'N',
                    `email` varchar(100),
                    `name` varchar(100),
                    `trip` varchar(25),
                    `title` varchar(100),
                    `comment` text,
                    `delpass` tinytext,
                    `sticky` bool NOT NULL DEFAULT '0',
                    `locked` bool NOT NULL DEFAULT '0',
                    `poster_hash` varchar(8),
                    `poster_country` varchar(2),
                    `exif` text,
                  
                    PRIMARY KEY (`doc_id`),
                    UNIQUE num_subnum_index (`num`, `subnum`),
                    INDEX thread_num_subnum_index (`thread_num`, `num`, `subnum`),
                    INDEX subnum_index (`subnum`),
                    INDEX op_index (`op`),
                    INDEX media_id_index (`media_id`),
                    INDEX media_hash_index (`media_hash`),
                    INDEX media_orig_index (`media_orig`),
                    INDEX name_trip_index (`name`, `trip`),
                    INDEX trip_index (`trip`),
                    INDEX email_index (`email`),
                    INDEX poster_ip_index (`poster_ip`),
                    INDEX timestamp_index (`timestamp`)
                  ) engine={engine} CHARSET={charset} COLLATE={charset}_general_ci;
                  
                  CREATE TABLE IF NOT EXISTS `{board}_deleted` LIKE `{board}`;
        
        
                  CREATE TABLE IF NOT EXISTS `{board}_threads` (
                    `thread_num` int unsigned NOT NULL,
                    `time_op` int unsigned NOT NULL,
                    `time_last` int unsigned NOT NULL,
                    `time_bump` int unsigned NOT NULL,
                    `time_ghost` int unsigned DEFAULT NULL,
                    `time_ghost_bump` int unsigned DEFAULT NULL,
                    `time_last_modified` int unsigned NOT NULL,
                    `nreplies` int unsigned NOT NULL DEFAULT '0',
                    `nimages` int unsigned NOT NULL DEFAULT '0',
                    `sticky` bool NOT NULL DEFAULT '0',
                    `locked` bool NOT NULL DEFAULT '0',
                  
                    PRIMARY KEY (`thread_num`),
                    INDEX time_op_index (`time_op`),
                    INDEX time_bump_index (`time_bump`),
                    INDEX time_ghost_bump_index (`time_ghost_bump`),
                    INDEX time_last_modified_index (`time_last_modified`),
                    INDEX sticky_index (`sticky`),
                    INDEX locked_index (`locked`)
                  ) ENGINE={engine} CHARSET={charset} COLLATE={charset}_general_ci;
                  
                  
                  CREATE TABLE IF NOT EXISTS `{board}_users` (
                    `user_id` int unsigned NOT NULL auto_increment,
                    `name` varchar(100) NOT NULL DEFAULT '',
                    `trip` varchar(25) NOT NULL DEFAULT '',
                    `firstseen` int(11) NOT NULL,
                    `postcount` int(11) NOT NULL,
                  
                    PRIMARY KEY (`user_id`),
                    UNIQUE name_trip_index (`name`, `trip`),
                    INDEX firstseen_index (`firstseen`),
                    INDEX postcount_index (`postcount`)
                  ) ENGINE={engine} DEFAULT CHARSET={charset} COLLATE={charset}_general_ci;
                  
                  
                  CREATE TABLE IF NOT EXISTS `{board}_images` (
                    `media_id` int unsigned NOT NULL auto_increment,
                    `media_hash` varchar(25) NOT NULL,
                    `media` varchar(20),
                    `preview_op` varchar(20),
                    `preview_reply` varchar(20),
                    `total` int(10) unsigned NOT NULL DEFAULT '0',
                    `banned` smallint unsigned NOT NULL DEFAULT '0',
                  
                    PRIMARY KEY (`media_id`),
                    UNIQUE media_hash_index (`media_hash`),
                    INDEX total_index (`total`),
                    INDEX banned_index (`banned`)
                  ) ENGINE={engine} DEFAULT CHARSET={charset} COLLATE={charset}_general_ci;
                  
                  
                  CREATE TABLE IF NOT EXISTS `{board}_daily` (
                    `day` int(10) unsigned NOT NULL,
                    `posts` int(10) unsigned NOT NULL,
                    `images` int(10) unsigned NOT NULL,
                    `sage` int(10) unsigned NOT NULL,
                    `anons` int(10) unsigned NOT NULL,
                    `trips` int(10) unsigned NOT NULL,
                    `names` int(10) unsigned NOT NULL,
                  
                    PRIMARY KEY (`day`)
                  ) ENGINE={engine} DEFAULT CHARSET={charset} COLLATE={charset}_general_ci;
                  
                  "#,
                    board = id.board,
                    engine = id.engine.mysql_engine(),
                    charset = id.charset.unwrap()
                );
                match s.as_str() {
                "" => base.as_str(),
                "update_thread" => {
                    r#"
                    CREATE PROCEDURE `update_thread_{board}` (tnum INT, ghost_num INT, p_timestamp INT,
                        p_media_hash VARCHAR(25), p_email VARCHAR(100))
                      BEGIN
                        DECLARE d_time_last INT;
                        DECLARE d_time_bump INT;
                        DECLARE d_time_ghost INT;
                        DECLARE d_time_ghost_bump INT;
                        DECLARE d_time_last_modified INT;
                        DECLARE d_image INT;
                      
                        SET d_time_last = 0;
                        SET d_time_bump = 0;
                        SET d_time_ghost = 0;
                        SET d_time_ghost_bump = 0;
                        SET d_image = p_media_hash IS NOT NULL;
                      
                        IF (ghost_num = 0) THEN
                          SET d_time_last_modified = p_timestamp;
                          SET d_time_last = p_timestamp;
                          IF (p_email <> 'sage' OR p_email IS NULL) THEN
                            SET d_time_bump = p_timestamp;
                          END IF;
                        ELSE
                          SET d_time_last_modified = p_timestamp;
                          SET d_time_ghost = p_timestamp;
                          IF (p_email <> 'sage' OR p_email IS NULL) THEN
                            SET d_time_ghost_bump = p_timestamp;
                          END IF;
                        END IF;
                      
                        UPDATE
                          `{board}_threads` op
                        SET
                          op.time_last = (
                            COALESCE(
                              GREATEST(op.time_op, d_time_last),
                              op.time_op
                            )
                          ),
                          op.time_bump = (
                            COALESCE(
                              GREATEST(op.time_bump, d_time_bump),
                              op.time_op
                            )
                          ),
                          op.time_ghost = (
                            IF (
                              GREATEST(
                                IFNULL(op.time_ghost, 0),
                                d_time_ghost
                              ) <> 0,
                              GREATEST(
                                IFNULL(op.time_ghost, 0),
                                d_time_ghost
                              ),
                              NULL
                            )
                          ),
                          op.time_ghost_bump = (
                            IF(
                              GREATEST(
                                IFNULL(op.time_ghost_bump, 0),
                                d_time_ghost_bump
                              ) <> 0,
                              GREATEST(
                                IFNULL(op.time_ghost_bump, 0),
                                d_time_ghost_bump
                              ),
                              NULL
                            )
                          ),
                          op.time_last_modified = (
                            COALESCE(
                              GREATEST(op.time_last_modified, d_time_last_modified),
                              op.time_op
                            )
                          ),
                          op.nreplies = (
                            op.nreplies + 1
                          ),
                          op.nimages = (
                            op.nimages + d_image
                          )
                          WHERE op.thread_num = tnum;
                      END;
                    "#
                },
                "update_thread_timestamp" => {
                r#"
      
                CREATE PROCEDURE `update_thread_timestamp_{board}` (tnum INT, timestamp INT)
                BEGIN
                  UPDATE
                    `{board}_threads` op
                  SET
                    op.time_last_modified = (
                      GREATEST(op.time_last_modified, timestamp)
                    )
                  WHERE op.thread_num = tnum;
                END;
                
                "#
                },
                "create_thread" => {
                    r#"
      
                    CREATE PROCEDURE `create_thread_{board}` (num INT, timestamp INT)
                    BEGIN
                      INSERT IGNORE INTO `{board}_threads` VALUES (num, timestamp, timestamp,
                        timestamp, NULL, NULL, timestamp, 0, 0, 0, 0);
                    END;
                    
                    "#
                    },
                "delete_thread" => {
                    r#"
      
                    CREATE PROCEDURE `delete_thread_{board}` (tnum INT)
                    BEGIN
                      DELETE FROM `{board}_threads` WHERE thread_num = tnum;
                    END;
                    
                    "#
                    },
                    "insert_image" => {
                    r#"
      
                    CREATE PROCEDURE `insert_image_{board}` (n_media_hash VARCHAR(25),
                    n_media VARCHAR(20), n_preview VARCHAR(20), n_op INT)
                   BEGIN
                     IF n_op = 1 THEN
                       INSERT INTO `{board}_images` (media_hash, media, preview_op, total)
                       VALUES (n_media_hash, n_media, n_preview, 1)
                       ON DUPLICATE KEY UPDATE
                         media_id = LAST_INSERT_ID(media_id),
                         total = (total + 1),
                         preview_op = COALESCE(preview_op, VALUES(preview_op)),
                         media = COALESCE(media, VALUES(media));
                     ELSE
                       INSERT INTO `{board}_images` (media_hash, media, preview_reply, total)
                       VALUES (n_media_hash, n_media, n_preview, 1)
                       ON DUPLICATE KEY UPDATE
                         media_id = LAST_INSERT_ID(media_id),
                         total = (total + 1),
                         preview_reply = COALESCE(preview_reply, VALUES(preview_reply)),
                         media = COALESCE(media, VALUES(media));
                     END IF;
                   END;
                   
                    "#
                    },
                    "delete_image" => {
                    r#"
      
                    CREATE PROCEDURE `delete_image_{board}` (n_media_id INT)
                    BEGIN
                      UPDATE `{board}_images` SET total = (total - 1) WHERE media_id = n_media_id;
                    END;
                    
                    "#
                    },
                    "before_ins" => {
                    r#"
      
                    CREATE TRIGGER `before_ins_{board}` BEFORE INSERT ON `{board}`
                    FOR EACH ROW
                    BEGIN
                      IF NEW.media_hash IS NOT NULL THEN
                        CALL insert_image_{board}(NEW.media_hash, NEW.media_orig, NEW.preview_orig, NEW.op);
                        SET NEW.media_id = LAST_INSERT_ID();
                      END IF;
                    END;
                    
                    "#
                    },
                "after_ins" => {
                    r#"
      
                    CREATE TRIGGER `after_ins_{board}` AFTER INSERT ON `{board}`
                    FOR EACH ROW
                    BEGIN
                      IF NEW.op = 1 THEN
                        CALL create_thread_{board}(NEW.num, NEW.timestamp);
                      END IF;
                      CALL update_thread_{board}(NEW.thread_num, NEW.subnum, NEW.timestamp, NEW.media_hash, NEW.email);
                    END;
                    
                    "#
                    },
                "after_del" => {
                    r#"
      
                    CREATE TRIGGER `after_del_{board}` AFTER DELETE ON `{board}`
                    FOR EACH ROW
                    BEGIN
                      CALL update_thread_{board}(OLD.thread_num, OLD.subnum, OLD.timestamp, OLD.media_hash, OLD.email);
                      IF OLD.op = 1 THEN
                        CALL delete_thread_{board}(OLD.num);
                      END IF;
                      IF OLD.media_hash IS NOT NULL THEN
                        CALL delete_image_{board}(OLD.media_id);
                      END IF;
                    END;
                    
                    "#
                    },
                "after_upd" => {
                    r#"
                    CREATE TRIGGER `after_upd_{board}` AFTER UPDATE ON `{board}`
                    FOR EACH ROW
                    BEGIN
                      IF NEW.timestamp_expired <> 0 THEN
                        CALL update_thread_timestamp_{board}(NEW.thread_num, NEW.timestamp_expired);
                      END IF;
                    END;
                    
                    "#
                    },
                _ => { "select 1;" },
            }.into()
            }
            YotsubaStatement::InitViews => "select 1".into(),
            YotsubaStatement::UpdateMetadata => format!(
                r#"
                INSERT INTO `metadata`(`board`, `{endpoint}`)       
                SELECT :bb, :jj
                ON DUPLICATE KEY update
                   `{endpoint}` = :jj;"#,
                endpoint = id.endpoint
            ),
            YotsubaStatement::UpdateThread => format!(
                r#"
            INSERT INTO `{board}`(`num`,`subnum`,`thread_num`,`op`,`timestamp`,`timestamp_expired`,`preview_orig`,`preview_w`,`preview_h`,`media_filename`,`media_w`,`media_h`,`media_size`,`media_hash`,`media_orig`,`spoiler`,`deleted`,`capcode`,`email`,`name`,`trip`,`title`,`comment`,`delpass`,`sticky`,`locked`,`poster_hash`,`poster_country`,`exif`)
            SELECT *
            FROM (SELECT
                    -- _id																'media_id',
                    -- null																'poster_ip',	-- Unused in Asagi. Used in FF.
                    no																'num',
                    0																'subnum',		-- Unused in Asagi. Used in FF for ghost posts.
                    IF(resto=0, no, resto)											'thread_num',
                    IF(resto=0, TRUE, FALSE)										'op',
                    `time`															'timestamp',
                    0																'timestamp_expired',
                    IF(tim IS NULL, NULL, CONCAT(tim, 's.jpg'))						'preview_orig',
                    IF(tn_w IS NULL, 0, tn_w)										'preview_w',
                    IF(tn_h IS NULL, 0, tn_h)										'preview_h',
                    IF(filename IS NULL, NULL, CONCAT(filename, ext))				'media_filename',
                    IF(w IS NULL, 0, w)												'media_w',
                    IF(h IS NULL, 0, h)												'media_h',
                    IF(fsize IS NULL, 0, h)											'media_size',
                    md5																'media_hash',
                    IF(tim IS NOT NULL and ext IS NOT NULL, CONCAT(tim, ext), NULL)	'media_orig',
                    IF(spoiler IS NULL, FALSE, spoiler)								'spoiler',
                    0																'deleted',
                    IF(capcode='manager' or capcode='Manager', 'G', coalesce(upper(left(capcode, 1)),'N'))  'capcode',
                    NULL															'email',
                    doCleanFull(name)												'name',
                    trip															'trip',
                    doCleanFull(sub)												'title',
                    doCleanFull(com)												'comment',
                    NULL															'delpass',		-- Unused in Asagi. Used in FF.
                    IFNULL(sticky, FALSE)								            'sticky',
                    IF((closed IS not NULL or closed=1) and (archived is null or archived = 0), closed, false)     'locked',
                    IF(id='Developer', 'Dev', id)									'poster_hash',	-- Not the same as media_hash
                    IF(country is not null and (country='XX' or country='A1'), null, country)   'poster_country',
                    -- country_name													'poster_country_name',
                    NULLIF(cast(JSON_REMOVE(
                        JSON_OBJECT(
                        IF(unique_ips is null, 'null__', 'uniqueIps'), cast(unique_ips as char),
                        IF(archived_on is null, 'null__', 'archivedOn'), archived_on,
                        IF(since4pass is null, 'null__', 'since4pass'), cast(since4pass as char),
                        IF(country or troll_country in('AC','AN','BL','CF','CM','CT','DM','EU','FC','GN','GY','JH','KN','MF','NB','NZ','PC','PR','RE','TM','TR','UN','WP'), 'trollCountry', 'null__' ), IFNULL(country, troll_country)), '$.null__') as char), '{{}}')    'exif' -- JSON in text format of uniqueIps, since4pass, and trollCountry. Has some deprecated fields but still used by Asagi and FF.
            FROM ( {schema_4chan_query} ) AS `4chan`) AS q
                ON DUPLICATE KEY UPDATE
                    -- `poster_ip`		= values(`poster_ip`),
                    `num`				= values(`num`),
                    `subnum`			= values(`subnum`),
                    `thread_num`		= values(`thread_num`),
                    `op`				= values(`op`),
                    `timestamp`			= values(`timestamp`),
                    `timestamp_expired`	= values(`timestamp_expired`),
                    `preview_orig`		= values(`preview_orig`),
                    `preview_w`			= values(`preview_w`),
                    `preview_h`			= values(`preview_h`),
                    `media_filename`	= values(`media_filename`),
                    `media_w`			= values(`media_w`),
                    `media_h`			= values(`media_h`),
                    `media_size`		= values(`media_size`),
                    `media_hash`		= values(`media_hash`),
                    `media_orig`		= values(`media_orig`),
                    `spoiler`			= values(`spoiler`),
                    `deleted`			= values(`deleted`),
                    `capcode`			= values(`capcode`),
                    `email`				= values(`email`),
                    `name`				= values(`name`),
                    `trip`				= values(`trip`),
                    `title`				= values(`title`),
                    `comment`			= values(`comment`),
                    `delpass`			= values(`delpass`),
                    `sticky`			= values(`sticky`),
                    `locked`			= values(`locked`),
                    `poster_hash`		= values(`poster_hash`),
                    `poster_country`	= values(`poster_country`),
                    `exif`				= values(`exif`);
            "#,
                board = id.board,
                schema_4chan_query = query_4chan_schema()
            ),
            YotsubaStatement::Delete => format!(
                "UPDATE `{}` SET deleted = 1, timestamp_expired = unix_timestamp() WHERE num = ? AND subnum = 0",
                id.board
            ),

            // This is not used as MySQL takes too long processing this.
            // So it is done locally with a HashSet
            YotsubaStatement::UpdateDeleteds => format!(
                r#"
                    UPDATE `{board}`, (
                        SELECT x.* FROM
                            (SELECT num, `timestamp`, thread_num FROM `{board}` where num=:no or thread_num=:no order by num) x
                        LEFT OUTER JOIN
                            ( {schema_4chan_query} ) z
                          ON x.num = z.no
                          UNION
                          
                        SELECT x.* FROM
                            (SELECT num, `timestamp`, thread_num FROM `{board}` where num=:no or thread_num=:no order by num) x
                        RIGHT OUTER JOIN
                            ( {schema_4chan_query} ) z
                          ON x.num = z.no
                        WHERE z.no is null
                    ) as `src`
                    SET `{board}`.deleted = 1;"#,
                board = id.board,
                schema_4chan_query = query_4chan_schema()
            ),
            YotsubaStatement::UpdateHashMedia => "select 1".into(),
            YotsubaStatement::UpdateHashThumbs => "select 1".into(),
            YotsubaStatement::Medias => format!(
                "SELECT * FROM `{board}`
                    WHERE (media_hash is not null) AND (num=:no or thread_num=:no)
                    ORDER BY num desc LOCK IN SHARE MODE;",
                board = id.board
            ),
            YotsubaStatement::Threads => r#"
            SELECT JSON_ARRAYAGG(no)
            FROM
            ( SELECT * FROM JSON_TABLE(:jj, "$[*].threads[*]" COLUMNS(
            `no`				bigint		PATH "$.no")
            ) w )z
            WHERE no is not null LOCK IN SHARE MODE;
            "#
            .to_string(),

            // This is not used as MySQL takes too long processing this.
            // So it is done locally with a HashSet
            YotsubaStatement::ThreadsModified => {
                let threads = r#"
            select JSON_ARRAYAGG(c) from (
                select prev->'$.no' as c from (
                SELECT prev from metadata m2 ,
                    JSON_TABLE(threads, '$[*].threads[*]'
                    COLUMNS(prev json path '$')) q 
                LEFT OUTER JOIN
                (SELECT newv from 
                    JSON_TABLE(:jj, '$[*].threads[*]'
                    COLUMNS(newv json path '$')) w) e
                on prev->'$.no' = newv->'$.no'
                where board = :bb and newv is null or prev is null or prev->'$.last_modified' != newv->'$.last_modified'
                
                UNION
                
                SELECT prev from metadata m3 ,
                    JSON_TABLE( threads, '$[*].threads[*]'
                    COLUMNS(prev json path '$')) r
                RIGHT OUTER JOIN
                (SELECT newv FROM
                    JSON_TABLE(:jj, '$[*].threads[*]'
                    COLUMNS(newv json path '$')) a) s
                on prev->'$.no' = newv->'$.no'
                where board = :bb and newv is null or prev is null or prev->'$.last_modified' != newv->'$.last_modified'
            ) z )i where c is not null;
        "#.to_string();
                let archive = r#"
            SELECT JSON_ARRAYAGG(c) from (
                select prev as c (
                SELECT prev from metadata m2 ,
                    JSON_TABLE( archive, '$[*]'
                    COLUMNS(prev json path '$')) q 
                LEFT OUTER JOIN
                (SELECT newv from 
                    JSON_TABLE(:jj, '$[*]'
                    COLUMNS(newv json path '$')) w) e
                on prev = newv
                where board = :bb
                
                UNION
                
                SELECT prev from metadata m3 ,
                    JSON_TABLE( archive, '$[*]'
                    COLUMNS(prev json path '$')) r
                RIGHT OUTER JOIN
                (SELECT newv FROM
                    JSON_TABLE(:jj, '$[*]'
                    COLUMNS(newv json path '$')) a) s
                on prev = newv
                where board = :bb
            ) z
            where newv is null or prev is null
            )xx where c is not null;
            "#
                .to_string();
                match id.endpoint {
                    YotsubaEndpoint::Threads => threads,
                    _ => archive
                }
            }

            // This is not used as MySQL takes too long processing this.
            // So it is done locally with a HashSet
            YotsubaStatement::ThreadsCombined => {
                let thread = format!(
                    r#"
                select JSON_ARRAYAGG(c) from (
                    select c from (
                    SELECT prev->'$.no' as c from (
                        SELECT prev from metadata m2 ,
                            JSON_TABLE(threads, '$[*].threads[*]'
                            COLUMNS(prev json path '$')) q 
                        LEFT OUTER JOIN
                        (SELECT newv from 
                            JSON_TABLE(:jj, '$[*].threads[*]'
                            COLUMNS(newv json path '$')) w) e
                        on prev->'$.no' = newv->'$.no'
                        where board = :bb
                        
                        UNION
                        
                        SELECT prev from metadata m3 ,
                            JSON_TABLE( threads, '$[*].threads[*]'
                            COLUMNS(prev json path '$')) r
                        RIGHT OUTER JOIN
                        (SELECT newv FROM
                            JSON_TABLE(:jj, '$[*].threads[*]'
                            COLUMNS(newv json path '$')) a) s
                        on prev->'$.no' = newv->'$.no'
                        where board = :bb
                    ) z ) i
                    left join
                      (select num as nno from `{board}` where op=1 and (timestamp_expired is not null or deleted is not null))u
                      ON c = nno
                    where nno is null LOCK IN SHARE MODE
                    )xx where c is not null;
                "#,
                    board = id.board
                );

                let archive = format!(
                    r#"
                select JSON_ARRAYAGG(c) from (
                    select c from (
                    SELECT coalesce (newv, prev) as c from (
                        SELECT prev from metadata m2 ,
                            JSON_TABLE(archive, '$[*]'
                            COLUMNS(prev json path '$')) q 
                        LEFT OUTER JOIN
                        (SELECT newv from 
                            JSON_TABLE(:jj, '$[*]'
                            COLUMNS(newv json path '$')) w) e
                        on prev = newv
                        where board = :bb
                        
                        UNION
                        
                        SELECT prev from metadata m3 ,
                            JSON_TABLE(archive, '$[*]'
                            COLUMNS(prev json path '$')) r
                        RIGHT OUTER JOIN
                        (SELECT newv FROM
                            JSON_TABLE(:jj, '$[*]'
                            COLUMNS(newv json path '$')) a) s
                        on prev = newv
                        where board = :bb
                    ) z ) i
                    left join
                      (select num as nno from `{board}` where op=1 and (timestamp_expired is not null or deleted is not null))u
                      ON c = nno
                    where  nno is null LOCK IN SHARE MODE
                    )xx where c is not null;
                "#,
                    board = id.board
                );
                match id.endpoint {
                    YotsubaEndpoint::Archive => archive,
                    _ => thread
                }
            }
            YotsubaStatement::Metadata => format!(
                r#"
                SELECT (CASE WHEN (
                    SELECT JSON_ARRAYAGG(`no`) from
                        (SELECT * FROM metadata,JSON_TABLE(`{endpoint}`, "{path1}" COLUMNS(
                        `no`				bigint		PATH "{path2}")
                        ) w where board = :bb)z 
                    WHERE `no` IS NOT NULL
                    ) IS NOT NULL AND `{endpoint}` IS NOT NULL
                    THEN true ELSE false END) as `check`
                FROM `metadata` WHERE board = :bb LOCK IN SHARE MODE;
                "#,
                endpoint = id.endpoint,
                path1 = if matches!(id.endpoint, YotsubaEndpoint::Threads) {
                    "$[*].threads[*]"
                } else {
                    "$[*]"
                },
                path2 = if matches!(id.endpoint, YotsubaEndpoint::Threads) { "$.no" } else { "$" }
            )
        }
    }
}

#[async_trait]
impl Query<Statement, Row> for Pool {
    async fn first(
        &self, statement: YotsubaStatement, id: &QueryIdentifier,
        statements: &StatementStore<Statement>, item: Option<&[u8]>, no: Option<u64>
    ) -> Result<u64>
    {
        if matches!(statement, YotsubaStatement::InitBoard) {
            log::info!("|Query| Running: {} /{}/", statement, id.board);
        } else {
            log::debug!("|Query| Running: {} /{}/", statement, id.board);
        }
        let endpoint = id.endpoint;
        let board = id.board;
        let conn = self.get_conn().await?;

        let item = item.ok_or_else(|| anyhow!("|Query::{}| Empty `json` item received", statement));
        let no = no.ok_or_else(|| anyhow!("|Query::{}| Empty `no` received", statement));
        match statement {
            YotsubaStatement::InitSchema | YotsubaStatement::InitMetadata => {
                conn.drop_query(&self.inquiry(statement, id.clone())).await?;
                Ok(1)
            }
            YotsubaStatement::InitBoard => {
                // Usually we'd just query the entire board + procedures + triggers creation
                // But MySQL is taking too long because it drops and recreates the procedures +
                // triggers on each restart of this program so we have to handle it
                // manually by checking if exists, if it does skip it, else create
                // them.

                // MySQL doesn't use a schema so this can be None.
                // Also the `None` identifier notfies the method to return the board creation string
                let inner_id = QueryIdentifier { schema: None, ..id.clone() };
                let conn = conn.drop_query(&self.inquiry(statement, inner_id)).await?;

                let base: BTreeSet<_> = [
                    "update_thread",
                    "update_thread_timestamp",
                    "create_thread",
                    "delete_thread",
                    "insert_image",
                    "delete_image",
                    "before_ins",
                    "after_ins",
                    "after_del",
                    "after_upd"
                ]
                .iter()
                .map(ToString::to_string)
                .collect();

                let (conn, r): (mysql_async::Conn, Option<Row>) = conn
                    .first(format!(
                        r#"
                select * from (select JSON_ARRAYAGG(trigger_name) as triggers
                from information_schema.triggers
                where trigger_schema = '{schema}'
                and event_object_table = '{board}') x, 
                (select JSON_ARRAYAGG(routine_name) as procs
                from information_schema.routines
                where routine_type = 'PROCEDURE'
                AND routine_schema = '{schema}'
                and routine_name like '%\_{board}')c;
                "#,
                        schema = id.schema.clone().unwrap(),
                        board = id.board
                    ))
                    .await?;

                let a: Option<(
                    Option<Option<serde_json::Value>>,
                    Option<Option<serde_json::Value>>
                )> = r.map(|q| (q.get("triggers"), q.get("procs")));

                let mut procsb: BTreeSet<String> = BTreeSet::new();
                if let Some((tr, pr)) = a {
                    let procedures = pr.flatten().unwrap_or(serde_json::json!([]));
                    let triggers = tr.flatten().unwrap_or(serde_json::json!([]));
                    procsb = serde_json::from_value(procedures)?;
                    let mut triggersb: BTreeSet<String> = serde_json::from_value(triggers)?;
                    procsb.append(&mut triggersb);

                    procsb = procsb
                        .into_iter()
                        .map(|s| {
                            s.trim_end_matches(&["_", &id.board.to_string()].concat()).to_string()
                        })
                        .collect::<BTreeSet<_>>();
                }
                // log::warn!("base: {:?}\nprocsb:{:?}", base, procsb);
                let diff = base.difference(&procsb).collect::<BTreeSet<_>>();
                // log::warn!("diff: {:?}", diff);

                // Generate a new ID to call InitBoard with the specific trigger or procedure
                // I'm using `schema` here ad the variable to pass it even though it isn't a schema,
                // it's just to store the data.
                for a in diff {
                    let inner_id = QueryIdentifier { schema: Some(a.clone()), ..id.clone() };
                    // log::info!("{}_{}", a, id.board);
                    self.get_conn()
                        .await?
                        .drop_query(
                            &self
                                .inquiry(statement, inner_id)
                                .replace("{board}", &id.board.to_string())
                        )
                        .await?;
                }

                Ok(1)
            }
            YotsubaStatement::Metadata => Ok(conn
                .prep_exec(
                    self.inquiry(statement, id.clone()),
                    params! {"bb" => id.board.to_string()}
                )
                .await
                .map(|x| x.collect_and_drop())?
                .await?
                .1
                .pop()
                .unwrap_or(0)),
            YotsubaStatement::UpdateMetadata => {
                let json = serde_json::from_slice::<serde_json::Value>(item?)?;
                // conn = conn
                //     .drop_exec(
                //         "SELECT *,1 from `metadata` WHERE board = ? for update;",
                //         (&board.to_string(),)
                //     )
                //     .await?;
                Ok(conn
                    .first_exec(
                        self.inquiry(statement, id.clone()),
                        params! { "bb" => board.to_string(), "jj" => json }
                    )
                    .await
                    .map(|(c, val)| val)?
                    .unwrap_or(1))
            }
            YotsubaStatement::UpdateThread => {
                // The result of this query will be empty since it's not SELECTing anything
                let json = serde_json::from_slice::<serde_json::Value>(item?)?;
                // conn = conn
                //     .drop_query(format!("SELECT *,1 from `{}` limit 1 for update;", board))
                //     .await?;
                Ok(conn
                    .first_exec(self.inquiry(statement, id.clone()), params! {"jj" => json })
                    .await
                    .map(|(c, val)| val)?
                    .unwrap_or(1))
            }
            YotsubaStatement::Delete => {
                let no = no?;
                // conn.drop_query(format!(
                //     "SELECT num, deleted, timestamp_expired from `{}` WHERE num = {} for
                // update;",     board, no
                // ))
                // .await?
                conn.drop_exec(self.inquiry(statement, id.clone()), (&i64::try_from(no)?,)).await?;
                Ok(1)
            }

            YotsubaStatement::UpdateDeleteds => {
                // {thread_endpoint}.json
                // get posts from db
                // compare that with fetched posts
                // mark deleted - the ones missing in fetched posts
                // This method kinda makes things slow though

                let q: Thread = serde_json::from_slice(item?)?;
                let new: Queue = q.posts.into_iter().map(|post| post.no).collect();
                let min = new
                    .iter()
                    .min()
                    .ok_or_else(|| anyhow!("|Query::{}| Empty `min` from threads", statement))?;
                // q.min();
                let no = no?;
                let (conn, val) : (mysql_async::Conn, Option<serde_json::Value>) = conn
                    .first_exec(format!(
                        "SELECT JSON_ARRAYAGG(num) from `{board}` where thread_num=? and thread_num >= ?;",
                        board = board
                    ), (no, min))
                    .await?;
                let val =
                    val.ok_or_else(|| anyhow!("|Query::{}| Empty `json` item received", statement));
                if val.is_err() {
                    // Here, the threads diff return no changes, meaning no posts are deleted
                    return Ok(1);
                }

                let orig: Queue = serde_json::from_value(val?)?;
                let diff: HashSet<_> = orig.difference(&new).collect();
                if diff.is_empty() {
                    // Here, the threads diff return no changes, meaning no posts are deleted
                    return Ok(1);
                }
                log::info!("({})\t/{}/{}\tDeleted posts: {:?}", id.endpoint, id.board, no, diff);

                Ok(conn
                    .first_exec(
                        format!(
                            r#"
                            UPDATE `{board}`
                            SET deleted = 1
                            where num in (
                                    SELECT no from
                                    JSON_TABLE(:jj,     "$[*]" COLUMNS(
                                    `no`				bigint		PATH "$")) z);"#,
                            board = id.board
                        ),
                        params! {"jj" => serde_json::to_value(&diff)? }
                    )
                    .await
                    // This will return empty since we're not selecting anything, so we can return a
                    // code of 1.
                    .map(|(c, val): (mysql_async::Conn, Option<u64>)| val)?
                    .unwrap_or(1))
            }
            YotsubaStatement::InitType
            | YotsubaStatement::InitViews
            | YotsubaStatement::UpdateHashMedia
            | YotsubaStatement::UpdateHashThumbs => Ok(1),
            // YotsubaStatement::Medias => {},
            // YotsubaStatement::Threads => {},
            // YotsubaStatement::ThreadsModified => {},
            // YotsubaStatement::ThreadsCombined => {},
            _ => Err(anyhow!("|Query| Unknown statement: {}", statement))
        }
    }

    async fn get_list(
        &self, statement: YotsubaStatement, id: &QueryIdentifier,
        statements: &StatementStore<Statement>, item: Option<&[u8]>, no: Option<u64>
    ) -> Result<Queue>
    {
        log::debug!("|Query| Running: {} /{}/", statement, id.board);
        if !matches!(
            statement,
            YotsubaStatement::Threads
                | YotsubaStatement::ThreadsModified
                | YotsubaStatement::ThreadsCombined
        ) {
            return Err(anyhow!(
                "|Query::{}| Unknown statement: {}",
                YotsubaStatement::Threads,
                statement
            ));
        }
        let id = QueryIdentifier { media_mode: statement, ..id.clone() };
        let endpoint = id.endpoint;
        let board = id.board;
        let conn = self.get_conn().await?;
        let item =
            item.ok_or_else(|| anyhow!("|Query::{}| Empty `json` item received", statement))?;
        if matches!(endpoint, YotsubaEndpoint::Archive) {
            let u: Queue = serde_json::from_slice(item)?;
            let ret: Queue = conn
                .first_exec(
                    format!("select `{}` from metadata where board = '{}'", endpoint, board),
                    ()
                )
                .await
                .map(|(c, val): (mysql_async::Conn, Option<Row>)| val)?
                .map(|r| r.get(0))
                .flatten()
                .map(|j: Option<serde_json::Value>| j)
                .flatten()
                .map(|j| serde_json::from_value::<Queue>(j))
                .ok_or_else(|| {
                    anyhow!("|Query::{}| Empty or null in getting {}", statement, endpoint)
                })?
                .map(|t: Queue| match statement {
                    YotsubaStatement::Threads => u,
                    YotsubaStatement::ThreadsModified =>
                        t.symmetric_difference(&u).map(|&s| s).collect(),
                    _ => t.union(&u).map(|&s| s).collect()
                })?;

            // Diff against archived/deleted
            // Because this is archives, do additional checks for archived/deleted
            // This might be unwanted as the size of the database grows.
            match statement {
                YotsubaStatement::Threads | YotsubaStatement::ThreadsModified => {
                    return Ok(ret);
                }
                _ => {
                    // YotsubaStatement::ThreadsCombined

                    let conn = self.get_conn().await?;
                    let (conn, v):(mysql_async::Conn, Option<Option<serde_json::Value>>) = conn.first(format!("select JSON_ARRAYAGG(num) from `{board}` where op=1 and (deleted=1 or exif like '%archived%');", board=id.board)).await?;
                    let res = v.flatten().map(|val| serde_json::from_value::<HashSet<u64>>(val));
                    if let Some(Ok(rr)) = res {
                        return Ok(ret.difference(&rr).map(|&i| i).collect());
                    } else {
                        return Ok(ret);
                    }
                }
            }
        }
        let threads: Vec<Threads> = serde_json::from_slice(item)?;
        let conn = self.get_conn().await?;
        Ok(conn
            .first_exec(
                format!("select `{}` from metadata where board = '{}'", endpoint, board),
                ()
            )
            .await
            .map(|(c, val): (mysql_async::Conn, Option<Row>)| val)?
            .map(|r| r.get(0))
            .flatten()
            .map(|j: Option<serde_json::Value>| j)
            .flatten()
            .map(|j| serde_json::from_value::<ThreadsList>(j))
            .ok_or_else(|| anyhow!("|Query::{}| Empty or null in getting {}", statement, endpoint))?
            .map(|t: ThreadsList| match statement {
                YotsubaStatement::Threads => Ok(t.to_queue()),
                YotsubaStatement::ThreadsModified => t.symmetric_difference(endpoint, &threads),
                _ => t.union(endpoint, &threads)
            })??)
    }

    async fn get_rows(
        &self, statement: YotsubaStatement, id: &QueryIdentifier,
        statements: &StatementStore<Statement>, item: Option<&[u8]>, no: Option<u64>
    ) -> Result<Vec<Row>>
    {
        log::debug!("|Query| Running: {} /{}/", statement, id.board);
        if !matches!(statement, YotsubaStatement::Medias) {
            return Err(anyhow!(
                "|Query::{}| Unknown statement: {}",
                YotsubaStatement::Medias,
                statement
            ));
        }
        let id = QueryIdentifier { media_mode: statement, ..id.clone() };
        let conn = self.get_conn().await?;
        let no = no.ok_or_else(|| anyhow!("|Query::{}| Empty `no` received", statement));

        Ok(conn
            .prep_exec(
                self.inquiry(statement, id.clone()),
                // self.query_medias(id.board, id.media_mode),
                params! {"no" => no? as i64}
            )
            .await?
            .collect_and_drop()
            .await?
            .1)
    }

    async fn create_statements(
        &self, engine: Database, endpoint: YotsubaEndpoint, board: YotsubaBoard
    ) -> StatementStore<Statement> {
        // Can't use statments for Asagi and MySQL due to the way [`mysql_async`] is implemented.
        // Connections don't hold a shared reference and statements can only be run once because it
        // ALSO moves itself out... wtf.. Therefore new connections need to be taken from
        // the pool, and statments are always constanly being remade for each query..
        // Here just give a placeholder statement.
        std::collections::HashMap::new()
    }
}

fn query_4chan_schema() -> String {
    format!(
        r#"SELECT * FROM JSON_TABLE(:jj, "$.posts[*]" COLUMNS(
        `no`				BIGINT		PATH "$.no",
        `sticky`			TINYINT  	PATH "$.sticky",
        `closed`			TINYINT  	PATH "$.closed",
        `now`				TEXT		PATH "$.now",
        `name`				TEXT		PATH "$.name",
        `sub`				TEXT		PATH "$.sub",
        `com`				TEXT		PATH "$.com",
        `filedeleted`		TINYINT  	PATH "$.filedeleted",
        `spoiler`			TINYINT 	PATH "$.spoiler",
        `custom_spoiler`	SMALLINT	PATH "$.custom_spoiler",
        `filename`			TEXT		PATH "$.filename",
        `ext`				TEXT		PATH "$.ext",
        `w`					INT			PATH "$.h",
        `h`					INT			PATH "$.w",
        `tn_w`				INT			PATH "$.tn_w",
        `tn_h`				INT			PATH "$.tn_h",
        `tim`				BIGINT		PATH "$.tim",
        `time`				BIGINT		PATH "$.time",
        `md5`				TEXT		PATH "$.md5",
        `fsize`				BIGINT		PATH "$.fsize",
        `m_img`				TINYINT	PATH "$.m_img",
        `resto`				BIGINT			PATH "$.resto",
        `trip`				TEXT		PATH "$.trip",
        `id`				TEXT		PATH "$.id",
        `capcode`			TEXT		PATH "$.capcode",
        `country`			TEXT		PATH "$.country",
        `troll_country`		TEXT		PATH "$.troll_country",
        `country_name`		TEXT		PATH "$.country_name",
        `archived`			TINYINT    	PATH "$.archived",
        `bumplimit`			TINYINT   	PATH "$.bumplimit",
        `archived_on`		BIGINT		PATH "$.archived_on",
        `imagelimit`		SMALLINT	PATH "$.imagelimit",
        `semantic_url`		TEXT		PATH "$.semantic_url",
        `replies`			INT			PATH "$.replies",
        `images`			INT			PATH "$.images",
        `unique_ips`		INT			PATH "$.unique_ips",
        `tag`				TEXT		PATH "$.tag",
        `since4pass`		SMALLINT	PATH "$.since4pass")
        ) w
    "#
    )
}

// https://stackoverflow.com/questions/34662713/how-can-i-create-parameterized-tests-in-rust
// [`mysql_async`] only returns library or server errors. Queries such as /INSERT/DELETE
#[cfg(test)]
mod test {

    use super::*;
    use crate::enums::{YotsubaBoard, YotsubaHash};
    use once_cell::sync::Lazy;
    #[allow(unused_imports)]
    #[cfg(test)]
    use pretty_assertions::{assert_eq, assert_ne};
    use serde_json::json;
    static BOARD: Lazy<YotsubaBoard> = Lazy::new(|| YotsubaBoard::a);
    const DB_URL: &str = "mysql://root:@localhost:3306/asagi";
    const SCHEMA: &str = "asagi";
    const ENGINE: Database = Database::MySQL;
    // const CHARSET: &str = "utf8";

    enum JsonType {
        Unknown,
        Valid,
        DeprecatedFields,
        AddedFields,
        MixedFields
    }

    macro_rules! send_thread_tests {
        ($($name:ident: $value:expr,)*) => {
            $(
                #[tokio::test]
                async fn $name() -> Result<()> {
                    let ( endpoint, board, mode, json_type) = $value;
                    test_send_single_thread(endpoint, board, mode, json_type).await?;
                    // assert_eq!(expected, fib(input));
                    Ok(())
                }
            )*
        }
    }
    macro_rules! get_threads_tests {
        ($($name:ident: $value:expr,)*) => {
            $(
                #[tokio::test]
                // #[should_panic(expected = "|threads| Empty or null in getting threads")] // for unknowns
                async fn $name() -> Result<()> {
                    let ( endpoint, board, mode, json_type) = $value;
                    test_get_threads(endpoint, board, mode, json_type).await?;
                    // assert_eq!(expected, fib(input));
                    Ok(())
                }
            )*
        }
    }

    macro_rules! get_threads_tests_panic {
        ($($name:ident: $value:expr,)*) => {
            $(
                // #[should_panic(expected = "|threads| Empty or null in getting threads")] // for unknowns
                #[tokio::test]
                #[should_panic]
                async fn $name() {
                    let (endpoint, board, mode, json_type) = $value;
                    test_get_threads(endpoint, board, mode, json_type).await.unwrap();
                    // assert_eq!(expected, fib(input));
                }
            )*
        }
    }
    #[cfg(test)]
    send_thread_tests! {
        // Send single thread
        send_single_thread_valid_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::UpdateThread, JsonType::Valid),
        send_single_thread_deprecated_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::UpdateThread, JsonType::DeprecatedFields),
        send_single_thread_added_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::UpdateThread, JsonType::AddedFields),
        send_single_thread_mixed_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::UpdateThread, JsonType::MixedFields),
    }

    #[cfg(test)]
    get_threads_tests! {
        // threads.json
        get_threads_send_valid_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::Threads, JsonType::Valid),

        get_threads_modified_send_valid_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsModified, JsonType::Valid),

        get_threads_combined_send_valid_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::Valid),

        get_threads_send_added_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::Threads, JsonType::AddedFields),
        get_threads_modified_send_added_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsModified, JsonType::AddedFields),
        get_threads_combined_send_added_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::AddedFields),

        // archive.json
        get_archive_send_valid_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::Threads, JsonType::Valid),

        get_archive_modified_send_valid_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsModified, JsonType::Valid),
        get_archive_modified_send_deprecated_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsModified, JsonType::DeprecatedFields),

        get_archive_combined_send_valid_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::Valid),
        get_archive_combined_send_deprecated_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::DeprecatedFields),



    }

    #[cfg(test)]
    get_threads_tests_panic! {
        get_threads_send_unknown_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::Threads, JsonType::Unknown),
        get_threads_send_deprecated_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::Threads, JsonType::DeprecatedFields),
        get_threads_modified_send_deprecated_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsModified, JsonType::DeprecatedFields),
        get_threads_combined_send_deprecated_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::DeprecatedFields),

        get_threads_send_mixed_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::Threads, JsonType::MixedFields),

        get_threads_modified_send_unknown_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsModified, JsonType::Unknown),
        get_threads_combined_send_unknown_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::Unknown),

        get_threads_modified_send_mixed_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsModified, JsonType::MixedFields),

        get_threads_combined_send_mixed_json: (YotsubaEndpoint::Threads, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::MixedFields),

        get_archive_send_added_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::Threads, JsonType::AddedFields),
        get_archive_send_mixed_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::Threads, JsonType::MixedFields),

        get_archive_modified_send_added_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsModified, JsonType::AddedFields),
        get_archive_modified_send_mixed_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsModified, JsonType::MixedFields),

        get_archive_combined_send_added_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::AddedFields),
        get_archive_combined_send_mixed_json: (YotsubaEndpoint::Archive, *BOARD, YotsubaStatement::ThreadsCombined, JsonType::MixedFields),
    }

    async fn test_get_threads(
        endpoint: YotsubaEndpoint, board: YotsubaBoard, mode: YotsubaStatement, json_type: JsonType
    ) -> Result<Queue> {
        let _json = match json_type {
            JsonType::Unknown =>
                if endpoint == YotsubaEndpoint::Threads {
                    json!({"test":1, "test2":2, "test3":3})
                } else {
                    json!(["1243234", "5645756", "75686786", "456454325", "test", "test1"])
                },
            JsonType::Valid =>
                if endpoint == YotsubaEndpoint::Threads {
                    json!(
                    [
                        {
                          "page": 1,
                          "threads": [
                            { "no": 196649146, "last_modified": 1576266882, "replies": 349 },
                            { "no": 196656555, "last_modified": 1576266881, "replies": 6 },
                            { "no": 196654076, "last_modified": 1576266880, "replies": 191 },
                            { "no": 196637792, "last_modified": 1576266880, "replies": 233 },
                            { "no": 196647457, "last_modified": 1576266880, "replies": 110 },
                            { "no": 196624742, "last_modified": 1576266873, "replies": 103 },
                            { "no": 196656097, "last_modified": 1576266868, "replies": 7 },
                            { "no": 196645355, "last_modified": 1576266866, "replies": 361 },
                            { "no": 196655995, "last_modified": 1576266867, "replies": 3 },
                            { "no": 196655998, "last_modified": 1576266860, "replies": 5 },
                            { "no": 196652782, "last_modified": 1576266858, "replies": 42 },
                            { "no": 196656536, "last_modified": 1576266853, "replies": 5 },
                            { "no": 196621039, "last_modified": 1576266853, "replies": 189 },
                            { "no": 196640441, "last_modified": 1576266851, "replies": 495 },
                            { "no": 196637247, "last_modified": 1576266850, "replies": 101 }
                          ]
                        },
                        {
                          "page": 2,
                          "threads": [
                            { "no": 196650664, "last_modified": 1576266846, "replies": 29 },
                            { "no": 196646963, "last_modified": 1576266845, "replies": 387 },
                            { "no": 196648390, "last_modified": 1576266844, "replies": 36 },
                            { "no": 196651494, "last_modified": 1576266832, "replies": 10 },
                            { "no": 196656773, "last_modified": 1576266827, "replies": 0 },
                            { "no": 196653207, "last_modified": 1576266827, "replies": 20 },
                            { "no": 196643737, "last_modified": 1576266825, "replies": 82 },
                            { "no": 196626714, "last_modified": 1576266824, "replies": 467 },
                            { "no": 196654299, "last_modified": 1576266821, "replies": 9 },
                            { "no": 196636729, "last_modified": 1576266819, "replies": 216 },
                            { "no": 196655015, "last_modified": 1576266819, "replies": 3 },
                            { "no": 196642084, "last_modified": 1576266818, "replies": 233 },
                            { "no": 196649533, "last_modified": 1576266816, "replies": 122 },
                            { "no": 196640416, "last_modified": 1576266806, "replies": 381 },
                            { "no": 196656724, "last_modified": 1576266794, "replies": 1 }
                          ]
                        }
                    ])
                } else {
                    json!([1243234, 5645756, 75686786, 456454325, 231412, 564576567, 34523234])
                },
            JsonType::DeprecatedFields =>
                if endpoint == YotsubaEndpoint::Threads {
                    json!(
                    [
                        {
                          "page": 1,
                          "threads": [
                            { "no_more": 196649146, "last_modified": 1576266882, "replies": 349 },
                            { "no_more": 196656555, "last_modified": 1576266881, "replies": 7 }
                          ]
                        },
                        {
                          "page": 2,
                          "threads": [
                            { "no_more": 196650664, "last_modified": 1576266846, "replies": 387},
                            { "no_more": 196646963, "last_modified": 1576266845, "replies": 487 }
                          ]
                        }
                    ])
                } else {
                    json!([])
                },
            JsonType::AddedFields =>
                if endpoint == YotsubaEndpoint::Threads {
                    json!(
                    [
                        {
                          "page": 1,
                          "threads": [
                            { "no": 196649146, "last_modified": 1576266882, "replies": 349, "new_field": 349 },
                            { "no": 196656555, "last_modified": 1576266881, "replies": 6,  "new_field": 7 }
                          ]
                        },
                        {
                          "page": 2,
                          "threads": [
                            { "no": 196650664, "last_modified": 1576266846, "replies": 387, "new_field": 387 },
                            { "no": 196646963, "last_modified": 1576266845, "replies": 487, "new_field": 487 },
                            { "no": 196648390, "last_modified": 1576266844, "replies": 36 , "new_field": 36 }
                          ]
                        }
                    ])
                } else {
                    json!([{}, "1243234", "5645756", "75686786", "456454325", "test", "test1"])
                },
            JsonType::MixedFields =>
                if endpoint == YotsubaEndpoint::Threads {
                    json!(
                    [
                        {
                          "page": 1,
                          "threads": [
                            { "no": 196649146, "last_modified": 1576266882, "replies": 349, "new_field": 349 },
                            { "no_more": 196656555, "last_modified": 1576266881, "replies": 6,  "new_field": 7 }
                          ]
                        },
                        {
                          "page": 2,
                          "threads": [
                            { "no": 196650664, "last_modified": 1576266846, "replies": 387, "new_field": 387 },
                            { "no": 196646963, "last_modified": 1576266845, "replies": 487, "new_field": 487 },
                            { "no_more": 196648390, "last_modified": 1576266844, "replies": 36 , "new_field": 36 }
                          ]
                        }
                    ])
                } else {
                    json!(["1243234", 5645756, "75686786", 456454325, "test", "test1"])
                },
        };

        let json = serde_json::to_vec(&_json).unwrap();

        let pool = Pool::new(DB_URL);

        let statements = pool.create_statements(ENGINE, endpoint, board).await;

        // This is the ID used by `create_statements` for the get`threads_*` variants.
        let id = &QueryIdentifier::new(
            ENGINE,
            endpoint,
            board,
            None,
            None,
            YotsubaHash::Sha256,
            YotsubaStatement::Medias
        );

        match mode {
            YotsubaStatement::Threads
            | YotsubaStatement::ThreadsModified
            | YotsubaStatement::ThreadsCombined =>
                Ok(pool.get_list(mode, &id, &statements, Some(json.as_slice()), None).await?),
            _ => Err(anyhow!("Error. Entered this test with : `{}` statement", mode))
        }
    }
    async fn test_send_single_thread(
        endpoint: YotsubaEndpoint, board: YotsubaBoard, mode: YotsubaStatement, json_type: JsonType
    ) -> Result<u64> {
        let _json = match json_type {
            JsonType::Unknown => json!({"test":1, "test2":2, "test3":3}),
            JsonType::Valid => json!(
                {
                    "posts": [{
                      "no": 5679879,
                      "sticky": 1,
                      "closed": 1,
                      "now": r#"12\/31\/18(Mon)17:05:48"#,
                      "name": "Anonymous",
                      "sub": r#"Welcome to \/po\/!"#,
                      "com": r#"Welcome to \/po\/! We specialize in origami, papercraft, and everything that\u2019s relevant to paper engineering. This board is also an great library of relevant PDF books and instructions, one of the best resource of its kind on the internet.<br><br>Questions and discussions of papercraft and origami are welcome. Threads for topics covered by paper engineering in general are also welcome, such as kirigami, bookbinding, printing technology, sticker making, gift boxes, greeting cards, and more.<br><br>Requesting is permitted, even encouraged if it\u2019s a good request; fulfilled requests strengthens this board\u2019s role as a repository of books and instructions. However do try to keep requests in relevant threads, if you can.<br><br>\/po\/ is a slow board! Do not needlessly bump threads."#,
                      "filename": "yotsuba_folding",
                      "ext": ".png",
                      "w": 530,
                      "h": 449,
                      "tn_w": 250,
                      "tn_h": 211,
                      "tim": 1546293948883 as i64,
                      "time": 1546293948,
                      "md5": "uZUeZeB14FVR+Mc2ScHvVA==",
                      "fsize": 516657,
                      "resto": 0,
                      "capcode": "mod",
                      "semantic_url": "welcome-to-po",
                      "replies": 2,
                      "images": 2,
                      "unique_ips": 1
                    }]}
            ),
            JsonType::DeprecatedFields => json!(
                {
                    "posts": [{
                      "no": 4588723,
                      "sticky": 1,
                      "closed": 1,
                      "ext": ".png",
                      "resto": 123457,
                      "w": 530,
                      "h": 449,
                      "tn_w": 250,
                      "tn_h": 211,
                      "tim": 1546293948883 as i64,
                      "time": 1546293948,
                      "unique_ips": 1
                    }]}
            ),
            JsonType::AddedFields => json!(
                {
                    "posts": [{
                      "no": 462537,
                      "sticky": 1,
                      "closed": 1,
                      "now": r#"12\/31\/18(Mon)17:05:48"#,
                      "name": "Anonymous",
                      "sub": "Wrg!",
                      "com": "sdf",
                      "filename": "yotsuba_folding",
                      "ext": ".png",
                      "w": 530,
                      "h": 449,
                      "tn_w": 250,
                      "tn_h": 211,
                      "tim": 1546293948883 as i64,
                      "time": 1546293948,
                      "md5": "uZUeZeB14FVR+Mc2ScHvVA==",
                      "fsize": 516657,
                      "resto": 0,
                      "capcode": "mod",
                      "semantic_url": "welcome-to-po",
                      "replies": 2,
                      "images": 2,
                      "unique_ips": 1,
                      "test": 1,
                      "added": 1
                    }]}
            ),
            JsonType::MixedFields => json!(
                {
                    "posts": [{
                      "no": 6745672,
                      "sticky": 1,
                      "closed": 1,
                      "ext": ".png",
                      "w": 530,
                      "h": 449,
                      "tn_w": 250,
                      "resto": 123457,
                      "tn_h": 211,
                      "tim": 1546293948883 as i64,
                      "time": 1546293948,
                      "unique_ips": 1,
                      "test": 1,
                      "test2": 1
                    }]}
            )
        };

        let json = serde_json::to_vec(&_json).unwrap();

        let pool = Pool::new(DB_URL);

        let statements = pool.create_statements(ENGINE, endpoint, board).await;

        // This is the ID used by `create_statements` for the get`threads_*` variants.
        let id = &QueryIdentifier::new(
            ENGINE,
            endpoint,
            board,
            None,
            None,
            YotsubaHash::Sha256,
            YotsubaStatement::Medias
        );

        match mode {
            YotsubaStatement::UpdateThread =>
                Ok(pool.first(mode, &id, &statements, Some(json.as_slice()), None).await?),
            _ => Err(anyhow!("Error. Entered this test with : `{}` statement", mode))
        }
    }
}