turnloop-mysql 0.1.0-beta.2

Pull-driven sans-I/O MySQL client protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
use mysql_common::{
    constants::CapabilityFlags as Caps, packets::Column as UpstreamColumn, proto::MySerialize,
};
use turnloop_mysql::*;
fn frame(seq: u8, body: &[u8]) -> Vec<u8> {
    let mut b = (body.len() as u32).to_le_bytes()[..3].to_vec();
    b.push(seq);
    b.extend_from_slice(body);
    b
}
fn flush(c: &mut Connection) -> Vec<u8> {
    let b = c.output().to_vec();
    c.consume_output(b.len())
        .expect("fixture operation must succeed");
    b
}
fn handshake(plugin: &str, extra: Caps) -> Vec<u8> {
    let caps = Caps::CLIENT_PROTOCOL_41
        | Caps::CLIENT_SECURE_CONNECTION
        | Caps::CLIENT_PLUGIN_AUTH
        | Caps::CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA
        | Caps::CLIENT_LONG_PASSWORD
        | Caps::CLIENT_MULTI_RESULTS
        | Caps::CLIENT_PS_MULTI_RESULTS
        | Caps::CLIENT_TRANSACTIONS
        | extra;
    let mut b = vec![10];
    b.extend_from_slice(b"9.6.0\0");
    b.extend_from_slice(&7u32.to_le_bytes());
    b.extend_from_slice(b"12345678\0");
    b.extend_from_slice(&(caps.bits() as u16).to_le_bytes());
    b.push(45);
    b.extend_from_slice(&2u16.to_le_bytes());
    b.extend_from_slice(&((caps.bits() >> 16) as u16).to_le_bytes());
    b.push(21);
    b.extend_from_slice(&[0; 10]);
    b.extend_from_slice(b"901234567890\0");
    b.extend_from_slice(plugin.as_bytes());
    b.push(0);
    frame(0, &b)
}
fn ok(seq: u8, affected: u8, status: u16) -> Vec<u8> {
    let mut b = vec![0, affected, 0];
    b.extend_from_slice(&status.to_le_bytes());
    b.extend_from_slice(&[0, 0]);
    frame(seq, &b)
}
fn eof(seq: u8, status: u16) -> Vec<u8> {
    let mut b = vec![0xfe, 0, 0];
    b.extend_from_slice(&status.to_le_bytes());
    frame(seq, &b)
}
fn column(seq: u8, t: ColumnType) -> Vec<u8> {
    let col = UpstreamColumn::new(t)
        .with_name(b"answer")
        .with_character_set(45);
    let mut b = Vec::new();
    col.serialize(&mut b);
    frame(seq, &b)
}
fn ready() -> Connection {
    let mut c = Connection::new(Config::default()).expect("fixture operation must succeed");
    c.receive(&handshake("mysql_native_password", Caps::empty()))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Progress)
    ));
    let b = flush(&mut c);
    assert_eq!(b[3], 1);
    c.receive(&ok(2, 0, 2))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Connected { connection_id: 7 })
    ));
    c
}
#[test]
fn native_and_caching_fast_full_tls_and_auth_switch() {
    let mut c = Connection::new(Config {
        password: b"secret".to_vec(),
        ..Config::default()
    })
    .expect("fixture operation must succeed");
    c.receive(&handshake("mysql_native_password", Caps::empty()))
        .expect("fixture operation must succeed");
    c.next_event().expect("fixture operation must succeed");
    let bytes = flush(&mut c);
    assert!(bytes.windows(20).any(|v| v
        == [
            0x0f, 0x8b, 0x90, 0x33, 0xe0, 0x89, 0x7c, 0x0a, 0x83, 0x38, 0xeb, 0xe3, 0xde, 0xa9,
            0x01, 0x0d, 0xda, 0x47, 0xab, 0x56
        ]));
    let mut switch = vec![0xfe];
    switch.extend_from_slice(b"caching_sha2_password\0abcdefghijklmnopqrst\0");
    c.receive(&frame(2, &switch))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Progress)
    ));
    let b = flush(&mut c);
    assert_eq!(b[3], 3);
    assert_eq!(b.len(), 36);
    c.receive(&frame(4, &[1, 3]))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::AuthFastSuccess)
    ));
    c.receive(&ok(5, 0, 2))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Connected { .. })
    ));
    let mut c = Connection::new(Config {
        password: b"secret".to_vec(),
        tls: true,
        ..Config::default()
    })
    .expect("fixture operation must succeed");
    c.receive(&handshake("caching_sha2_password", Caps::CLIENT_SSL))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::UpgradeTls)
    ));
    let ssl = flush(&mut c);
    assert_eq!(ssl.len(), 36);
    assert_eq!(ssl[3], 1);
    assert!(c.query(1, "SELECT 1", None).is_err());
    c.tls_established().expect("fixture operation must succeed");
    assert_eq!(flush(&mut c)[3], 2);
    c.receive(&frame(3, &[1, 4]))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::AuthFull)
    ));
    assert_eq!(flush(&mut c), frame(4, b"secret\0"));
    c.receive(&ok(5, 0, 2))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Connected { .. })
    ));
    let mut c = Connection::new(Config {
        password: b"secret".to_vec(),
        ..Config::default()
    })
    .expect("fixture operation must succeed");
    c.receive(&handshake("caching_sha2_password", Caps::empty()))
        .expect("fixture operation must succeed");
    c.next_event().expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&frame(2, &[1, 4]))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::AuthFull)
    ));
    assert_eq!(flush(&mut c), frame(3, &[2]));
}
#[test]
fn fragmented_multiset_rows_error_and_prepare_binary() {
    let mut c = ready();
    c.query(1, "SELECT 42; SELECT 99", None)
        .expect("fixture operation must succeed");
    assert_eq!(&flush(&mut c)[4..], b"\x03SELECT 42; SELECT 99");
    let bytes = [
        frame(1, &[1]),
        column(2, ColumnType::MYSQL_TYPE_LONG),
        eof(3, 2),
        frame(4, b"\x0242"),
        eof(5, 10),
        frame(6, &[1]),
        column(7, ColumnType::MYSQL_TYPE_LONG),
        eof(8, 2),
        frame(9, b"\x0299"),
        eof(10, 2),
    ]
    .concat();
    let mut values = Vec::new();
    let mut completed = 0;
    let mut columns = 0;
    for b in bytes {
        c.receive(&[b]).expect("fixture operation must succeed");
        while let Some(e) = c.next_event().expect("fixture operation must succeed") {
            match e {
                Event::Row { row, .. } => {
                    for v in row {
                        let RawValue::Bytes(b) = v.expect("fixture operation must succeed") else {
                            panic!()
                        };
                        values.push(b.to_vec());
                    }
                }
                Event::Column { column, .. } => {
                    assert_eq!(column.name, b"answer");
                    columns += 1;
                }
                Event::Completed { token, outcome } => {
                    assert_eq!(token, 1);
                    assert_eq!(outcome, Outcome::Success);
                    completed += 1;
                }
                _ => {}
            }
        }
    }
    assert_eq!(values, [b"42", b"99"]);
    assert_eq!(columns, 2);
    assert_eq!(completed, 1);
    c.prepare(2, "SELECT ?", None)
        .expect("fixture operation must succeed");
    assert_eq!(flush(&mut c)[4], 0x16);
    let mut prepare = vec![0];
    prepare.extend_from_slice(&17u32.to_le_bytes());
    prepare.extend_from_slice(&[1, 0, 1, 0, 0, 0, 0]);
    c.receive(
        &[
            frame(1, &prepare),
            column(2, ColumnType::MYSQL_TYPE_LONG),
            eof(3, 2),
            column(4, ColumnType::MYSQL_TYPE_LONG),
            eof(5, 2),
        ]
        .concat(),
    )
    .expect("fixture operation must succeed");
    let mut stmt = None;
    while let Some(e) = c.next_event().expect("fixture operation must succeed") {
        if let Event::Prepared { statement, .. } = e {
            stmt = Some(statement);
        }
    }
    let stmt = stmt.expect("fixture operation must succeed");
    assert_eq!(stmt.parameters, 1);
    c.execute(3, stmt.id, &[Value::Int(42)], None)
        .expect("fixture operation must succeed");
    let execute = flush(&mut c);
    assert_eq!(
        &execute[4..],
        &[
            0x17, 17, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 8, 0, 42, 0, 0, 0, 0, 0, 0, 0
        ]
    );
    c.receive(
        &[
            frame(1, &[1]),
            column(2, ColumnType::MYSQL_TYPE_LONG),
            eof(3, 2),
            frame(4, &[0, 0, 42, 0, 0, 0]),
            eof(5, 2),
        ]
        .concat(),
    )
    .expect("fixture operation must succeed");
    let mut rows = 0;
    while let Some(e) = c.next_event().expect("fixture operation must succeed") {
        if let Event::Row { mut row, .. } = e {
            assert_eq!(
                row.next()
                    .expect("fixture operation must succeed")
                    .expect("fixture operation must succeed"),
                RawValue::Scalar(Value::Int(42))
            );
            rows += 1;
        }
    }
    assert_eq!(rows, 1);
    c.reset_statement(4, stmt.id)
        .expect("fixture operation must succeed");
    assert_eq!(flush(&mut c), frame(0, &[0x1a, 17, 0, 0, 0]));
    c.receive(&ok(1, 0, 2))
        .expect("fixture operation must succeed");
    while c
        .next_event()
        .expect("fixture operation must succeed")
        .is_some()
    {}
    c.close_statement(5, stmt.id)
        .expect("fixture operation must succeed");
    assert!(
        c.next_event()
            .expect("fixture operation must succeed")
            .is_none()
    );
    flush(&mut c);
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 5,
            outcome: Outcome::Success
        })
    ));
    assert!(c.execute(6, stmt.id, &[], None).is_err());
    c.query(7, "bad", None)
        .expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&frame(1, b"\xff\x28\x04#42000syntax error"))
        .expect("fixture operation must succeed");
    let Some(Event::Error { error, .. }) = c.next_event().expect("fixture operation must succeed")
    else {
        panic!()
    };
    assert_eq!(error.errno, 1064);
    assert_eq!(error.code(), Some("ER_PARSE_ERROR"));
    assert_eq!(error.sql_state, "42000");
    assert_eq!(error.sql_message, "syntax error");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 7,
            outcome: Outcome::ServerError
        })
    ));
}
#[test]
fn infile_disabled_timeout_and_bad_sequence() {
    let mut c = ready();
    c.query(1, "LOAD DATA", None)
        .expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&frame(1, b"\xfb/etc/passwd"))
        .expect("fixture operation must succeed");
    assert_eq!(c.next_event().unwrap_err(), Error::LocalInfileDisabled);
    assert!(c.output().is_empty());
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 1,
            outcome: Outcome::Aborted(Error::LocalInfileDisabled)
        })
    ));
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Closed { .. })
    ));
    assert!(
        c.next_event()
            .expect("fixture operation must succeed")
            .is_none()
    );
    let mut c = ready();
    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
    let now = Instant::now();
    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
    let now = Instant::from_duration(std::time::Duration::ZERO);
    c.query(2, "slow", Some(now))
        .expect("fixture operation must succeed");
    c.handle_timeout(now);
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 2,
            outcome: Outcome::Aborted(Error::Timeout)
        })
    ));
    let mut c = ready();
    c.query(3, "SELECT 1", None)
        .expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&ok(99, 0, 2))
        .expect("fixture operation must succeed");
    assert!(c.next_event().is_err());
    c.abort(Error::Transport);
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed { token: 3, .. })
    ));
}

#[test]
fn rsa_full_auth_uses_host_seed_and_matches_independent_oaep_vector() {
    let mut c = Connection::new(Config {
        password: b"secret".to_vec(),
        ..Config::default()
    })
    .expect("fixture operation must succeed");
    c.receive(&handshake("caching_sha2_password", Caps::empty()))
        .expect("fixture operation must succeed");
    c.next_event().expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&frame(2, &[1, 4]))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::AuthFull)
    ));
    assert_eq!(flush(&mut c), frame(3, &[2]));
    let mut key = vec![1];
    key.extend_from_slice(include_bytes!("fixtures/rsa-public.pem"));
    c.receive(&frame(4, &key))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::RsaSeedNeeded)
    ));
    assert!(c.output().is_empty());
    let mut seed = [0; 20];
    for (i, b) in seed.iter_mut().enumerate() {
        *b = i as u8;
    }
    c.rsa_seed(seed).expect("fixture operation must succeed");
    assert_eq!(
        flush(&mut c),
        frame(5, include_bytes!("fixtures/rsa-oaep-expected.bin"))
    );
    c.receive(&ok(6, 0, 2))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Connected { .. })
    ));
    assert!(c.rsa_seed(seed).is_err());
}
#[test]
fn local_infile_enabled_is_an_explicit_borrowed_request() {
    let mut c = Connection::new(Config {
        local_infile: true,
        ..Config::default()
    })
    .expect("fixture operation must succeed");
    c.receive(&handshake(
        "mysql_native_password",
        Caps::CLIENT_LOCAL_FILES,
    ))
    .expect("fixture operation must succeed");
    c.next_event().expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&ok(2, 0, 2))
        .expect("fixture operation must succeed");
    c.next_event().expect("fixture operation must succeed");
    c.query(1, "LOAD DATA LOCAL INFILE 'fixture.tsv'", None)
        .expect("fixture operation must succeed");
    flush(&mut c);
    c.receive(&frame(1, b"\xfbfixture.tsv"))
        .expect("fixture operation must succeed");
    let Some(Event::LocalInfile { token, file_name }) =
        c.next_event().expect("fixture operation must succeed")
    else {
        panic!()
    };
    assert_eq!(token, 1);
    assert_eq!(file_name, b"fixture.tsv");
    assert!(c.output().is_empty());
    c.local_infile_data(b"42\n")
        .expect("fixture operation must succeed");
    assert_eq!(flush(&mut c), frame(2, b"42\n"));
    c.local_infile_finish()
        .expect("fixture operation must succeed");
    assert_eq!(flush(&mut c), frame(3, b""));
    c.receive(&ok(4, 1, 2))
        .expect("fixture operation must succeed");
    let Some(Event::Ok { packet, .. }) = c.next_event().expect("fixture operation must succeed")
    else {
        panic!()
    };
    assert_eq!(packet.affected_rows(), 1);
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 1,
            outcome: Outcome::Success
        })
    ));
}
/// Prepare `id` with no parameters or columns; the server's reply completes it.
fn prepare_statement(c: &mut Connection, token: Token, id: u32) -> Statement {
    c.prepare(token, "DO 1", None)
        .expect("fixture operation must succeed");
    flush(c);
    let mut prepare = vec![0];
    prepare.extend_from_slice(&id.to_le_bytes());
    prepare.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0]);
    c.receive(&frame(1, &prepare))
        .expect("fixture operation must succeed");
    let Some(Event::Prepared { statement, .. }) =
        c.next_event().expect("fixture operation must succeed")
    else {
        panic!("expected Prepared")
    };
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed { .. })
    ));
    statement
}
/// A completion-driven host only calls into the connection when a write or a
/// read completes. COM_STMT_CLOSE and COM_QUIT get no reply, so the write
/// acknowledgement alone must say "call next_event() now"; no timer is used.
#[test]
fn no_reply_commands_complete_from_the_write_acknowledgement() {
    let mut c = ready();
    let stmt = prepare_statement(&mut c, 1, 17);
    c.close_statement(2, stmt.id)
        .expect("fixture operation must succeed");
    let close = c.output().to_vec();
    assert_eq!(close, frame(0, &[0x19, 17, 0, 0, 0]));
    assert!(c.next_event().expect("unwritten close").is_none());
    // Partial write completion: nothing to deliver yet.
    assert!(!c.consume_output(3).expect("fixture operation must succeed"));
    assert!(c.next_event().expect("half-written close").is_none());
    // Final write completion: the only wakeup this command will ever get.
    assert!(
        c.consume_output(close.len() - 3)
            .expect("fixture operation must succeed"),
        "acknowledging COM_STMT_CLOSE must ask for next_event()"
    );
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 2,
            outcome: Outcome::Success
        })
    ));
    assert!(c.next_event().expect("drained").is_none());
    assert!(c.can_accept());

    // A command that does get a reply is not reported early.
    c.ping(3).expect("fixture operation must succeed");
    let n = c.output().len();
    assert!(!c.consume_output(n).expect("fixture operation must succeed"));
    assert!(c.next_event().expect("awaiting reply").is_none());
    c.receive(&ok(1, 0, 2))
        .expect("fixture operation must succeed");
    while c.next_event().expect("ping reply").is_some() {}

    c.quit().expect("fixture operation must succeed");
    assert_eq!(c.output(), frame(0, &[1]));
    assert!(c.next_event().expect("unwritten quit").is_none());
    let n = c.output().len();
    assert!(
        c.consume_output(n).expect("fixture operation must succeed"),
        "acknowledging COM_QUIT must ask for next_event()"
    );
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Closed {
            reason: Error::Cancelled
        })
    ));
    assert!(c.next_event().expect("closed").is_none());
}
/// The statement stays registered until the COM_STMT_CLOSE bytes are
/// acknowledged, so a failed flush cannot leave the core believing the server
/// dropped a statement it never heard about.
#[test]
fn close_statement_forgets_the_statement_only_after_its_bytes_are_sent() {
    let mut c = ready();
    let stmt = prepare_statement(&mut c, 1, 17);
    assert_eq!(c.statements(), [stmt]);
    c.close_statement(2, stmt.id)
        .expect("fixture operation must succeed");
    assert_eq!(c.statements(), [stmt], "close not yet written");
    let n = c.output().len();
    assert!(!c.consume_output(n - 1).expect("partial write"));
    assert_eq!(c.statements(), [stmt], "close only partly written");
    // The flush carrying the last byte fails: the host aborts.
    c.abort(Error::Transport);
    assert_eq!(c.statements(), [stmt], "the server still holds it");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 2,
            outcome: Outcome::Aborted(Error::Transport)
        })
    ));

    let mut c = ready();
    let stmt = prepare_statement(&mut c, 1, 17);
    c.close_statement(2, stmt.id)
        .expect("fixture operation must succeed");
    let n = c.output().len();
    assert!(c.consume_output(n).expect("full write"));
    assert_eq!(c.statements(), []);
    assert_eq!(
        c.execute(3, stmt.id, &[], None),
        Err(Error::State("connection busy or closed")),
        "Completed not yet delivered"
    );
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 2,
            outcome: Outcome::Success
        })
    ));
    assert_eq!(
        c.execute(3, stmt.id, &[], None),
        Err(Error::State("unknown prepared statement"))
    );
}
/// A statement's OK packet and a result set's terminating EOF are different
/// events, so a host never reads an EOF's bytes as affected rows.
#[test]
fn ok_packets_and_result_set_eofs_are_distinct_events() {
    let mut c = ready();
    c.query(1, "INSERT INTO t VALUES (1),(2),(3); SELECT 42", None)
        .expect("fixture operation must succeed");
    flush(&mut c);
    // OK: affected_rows 3, last_insert_id 9, SERVER_MORE_RESULTS_EXISTS | AUTOCOMMIT.
    let insert = frame(1, &[0, 3, 9, 10, 0, 0, 0]);
    // Legacy EOF: 0xfe, warnings = 3, status = AUTOCOMMIT.
    let end = frame(6, &[0xfe, 3, 0, 2, 0]);
    c.receive(
        &[
            insert,
            frame(2, &[1]),
            column(3, ColumnType::MYSQL_TYPE_LONG),
            eof(4, 2),
            frame(5, b"\x0242"),
            end,
        ]
        .concat(),
    )
    .expect("fixture operation must succeed");
    let mut seen = Vec::new();
    while let Some(e) = c.next_event().expect("fixture operation must succeed") {
        match e {
            Event::Ok { token, packet } => seen.push(format!(
                "ok {token} affected={} id={:?} more={}",
                packet.affected_rows(),
                packet.last_insert_id(),
                packet
                    .status_flags()
                    .contains(StatusFlags::SERVER_MORE_RESULTS_EXISTS)
            )),
            Event::Eof {
                token,
                warnings,
                status,
            } => seen.push(format!(
                "eof {token} warnings={warnings} more={}",
                status.contains(StatusFlags::SERVER_MORE_RESULTS_EXISTS)
            )),
            Event::Row { .. } => seen.push("row".into()),
            Event::Completed { token, outcome } => {
                seen.push(format!("completed {token} {outcome:?}"))
            }
            _ => {}
        }
    }
    assert_eq!(
        seen,
        [
            "ok 1 affected=3 id=Some(9) more=true",
            "row",
            "eof 1 warnings=3 more=false",
            "completed 1 Success",
        ]
    );
    assert_eq!(c.status(), StatusFlags::SERVER_STATUS_AUTOCOMMIT);
}
/// `can_accept` is the admission rule itself: whenever it is false a command is
/// rejected without side effects, and whenever it is true the next one is taken.
#[test]
fn can_accept_reports_the_exact_admission_decision() {
    let mut c = Connection::new(Config::default()).expect("fixture operation must succeed");
    assert!(!c.can_accept());
    assert_eq!(
        c.ping(1),
        Err(Error::State("connection busy or closed")),
        "handshake in progress"
    );
    let mut c = ready();
    assert!(c.can_accept());
    c.query(1, "SELECT 1", None)
        .expect("admitted when can_accept is true");
    let request = c.output().len();
    assert!(!c.can_accept());
    assert!(c.ping(2).is_err());
    assert_eq!(
        c.output().len(),
        request,
        "a rejected command adds no bytes"
    );
    c.consume_output(request - 1)
        .expect("fixture operation must succeed");
    assert!(!c.can_accept(), "unacknowledged output");
    assert!(c.ping(2).is_err());
    c.consume_output(1).expect("fixture operation must succeed");
    assert!(!c.can_accept(), "command still pending");
    assert!(c.ping(2).is_err());
    c.receive(&ok(1, 0, 2))
        .expect("fixture operation must succeed");
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Ok { token: 1, .. })
    ));
    assert!(!c.can_accept(), "Completed not yet delivered");
    assert!(c.ping(2).is_err());
    assert!(matches!(
        c.next_event().expect("fixture operation must succeed"),
        Some(Event::Completed {
            token: 1,
            outcome: Outcome::Success
        })
    ));
    assert!(c.can_accept());
    c.ping(2).expect("admitted when can_accept is true");
    assert_eq!(flush(&mut c), frame(0, &[0x0e]));
    c.abort(Error::Transport);
    assert!(!c.can_accept());
    assert!(c.quit().is_err());
}