drizzle 0.3.1

A type-safe SQL query builder for Rust
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
//! Blocking MySQL adapter using the [`mysql`] crate.
//!
//! [`Drizzle`] owns the exact connection passed to [`Drizzle::new`]. To use a
//! pool, check out a [`mysql::PooledConn`] first and pass that connection to
//! Drizzle. Dropping the wrapper then returns the connection to its original
//! pool through the upstream driver's normal ownership rules.
//!
//! The adapter executes every statement through MySQL's prepared binary
//! protocol, including statements without parameters. Before its first query,
//! it fixes the session time zone at UTC and removes
//! `NO_UNSIGNED_SUBTRACTION` and `REAL_AS_FLOAT` so typed numeric expressions
//! and `REAL` columns have stable Rust types.
//!
//! # Quick start
//!
//! Add `mysql = "28"` beside `drizzle` in the application manifest, then pass
//! an upstream connection into Drizzle:
//!
//! ```no_run
//! use drizzle::mysql::{mysql_sync::Drizzle, prelude::*};
//!
//! #[MySQLTable]
//! struct User {
//!     #[column(PRIMARY, AUTO_INCREMENT)]
//!     id: u64,
//!     #[column(VARCHAR(255))]
//!     name: String,
//! }
//!
//! #[derive(MySQLSchema)]
//! struct AppSchema {
//!     user: User,
//! }
//!
//! fn main() -> drizzle::Result<()> {
//!     let opts = ::mysql::Opts::from_url("mysql://root:mysql@localhost/app")
//!         .map_err(|error| drizzle::error::DrizzleError::driver("MySQL", error))?;
//!     let connection = ::mysql::Conn::new(opts)
//!         .map_err(|error| drizzle::error::DrizzleError::driver("MySQL", error))?;
//!     let (mut db, AppSchema { user }) = Drizzle::new(connection);
//!     db.create()?;
//!
//!     db.insert(user).value(InsertUser::new("Alice")).execute()?;
//!     let users: Vec<SelectUser> = db.select(()).from(user).all()?;
//!     assert_eq!(users.len(), 1);
//!     Ok(())
//! }
//! ```

mod migration;
pub mod prepared;

use drizzle_core::{
    error::{DrizzleError, QueryContext, Result, ResultExt},
    row::{
        DecodeSelectedRef, FromDrizzleRow, MarkerAggValidFor, MarkerColumnCountValid,
        MarkerScopeValidFor, StrictDecodeMarker,
    },
    traits::ToSQL,
};
use drizzle_mysql::{
    MySQLMutationResult, MySQLRow,
    builder::{
        self, DeleteBuilder, DeleteInitial, InsertBuilder, InsertInitial, QueryBuilder,
        SelectBuilder, SelectInitial, UpdateBuilder, UpdateInitial,
    },
    traits::MySQLTable,
    values::MySQLValue,
};
use mysql::{Row, Value, prelude::Queryable};

use crate::builder::mysql::{
    common,
    driver_common::{QueryOutput, positional, render},
    introspect,
};
use crate::transaction::{
    mysql::mysql_sync::{Transaction, TransactionConnection},
    savepoint::sync_transaction,
};

/// A MySQL query attached to this blocking adapter.
pub type DrizzleBuilder<'db, Connection, Schema, Builder, State> =
    common::DrizzleBuilder<'db, &'db mut Drizzle<Connection, Schema>, Schema, Builder, State>;

/// Decoded MySQL rows from a fully materialized query result.
///
/// The iterator owns its result rows and does not retain a connection or
/// transaction borrow while callers decode them.
pub type Rows<R> = crate::builder::mysql::driver_common::Rows<R>;

pub(crate) fn driver_error(error: mysql::Error) -> DrizzleError {
    DrizzleError::driver("MySQL", error)
}

pub(crate) fn execute_request_observing<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
    mut observe_error: impl FnMut(&mysql::Error),
) -> Result<MySQLMutationResult> {
    drizzle_core::drizzle_trace_query!(sql, values.len());
    let context_values = values.iter().collect::<Vec<_>>();
    let params = positional(values.iter().cloned().map(Value::from));
    let result = connection
        .exec_iter(sql, params)
        .map_err(|error| {
            observe_error(&error);
            driver_error(error)
        })
        .with_query(|| QueryContext::new(sql, &context_values))?;
    let mutation = MySQLMutationResult::new(result.affected_rows(), result.last_insert_id());
    drop(result);
    Ok(mutation)
}

pub(crate) fn execute_request<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
) -> Result<MySQLMutationResult> {
    execute_request_observing(connection, sql, values, |_| {})
}

pub(crate) fn initialize_session(connection: &mut impl Queryable) -> Result<()> {
    initialize_session_observing(connection, |_| {})
}

pub(crate) fn initialize_session_observing(
    connection: &mut impl Queryable,
    observe_error: impl FnMut(&mysql::Error),
) -> Result<()> {
    let sql = "SET time_zone = '+00:00', sql_mode = REPLACE(REPLACE(@@SESSION.sql_mode, 'NO_UNSIGNED_SUBTRACTION', ''), 'REAL_AS_FLOAT', '')";
    execute_request_observing(connection, sql, &[], observe_error).map(|_| ())
}

pub(crate) fn query_request_observing<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
    mut observe_error: impl FnMut(&mysql::Error),
) -> Result<Vec<Row>> {
    drizzle_core::drizzle_trace_query!(sql, values.len());
    let context_values = values.iter().collect::<Vec<_>>();
    let params = positional(values.iter().cloned().map(Value::from));
    let result = connection
        .exec_iter(sql, params)
        .map_err(|error| {
            observe_error(&error);
            driver_error(error)
        })
        .with_query(|| QueryContext::new(sql, &context_values))?;

    result
        .map(|row| {
            row.map_err(|error| {
                observe_error(&error);
                driver_error(error)
            })
            .with_query(|| QueryContext::new(sql, &context_values))
        })
        .collect::<Result<Vec<_>>>()
}

pub(crate) fn query_request<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
) -> Result<Vec<Row>> {
    query_request_observing(connection, sql, values, |_| {})
}

pub(crate) fn query_first_request_observing<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
    mut observe_error: impl FnMut(&mysql::Error),
) -> Result<Option<Row>> {
    drizzle_core::drizzle_trace_query!(sql, values.len());
    let context_values = values.iter().collect::<Vec<_>>();
    let params = positional(values.iter().cloned().map(Value::from));
    let mut result = connection
        .exec_iter(sql, params)
        .map_err(|error| {
            observe_error(&error);
            driver_error(error)
        })
        .with_query(|| QueryContext::new(sql, &context_values))?;
    let row = result
        .next()
        .transpose()
        .map_err(|error| {
            observe_error(&error);
            driver_error(error)
        })
        .with_query(|| QueryContext::new(sql, &context_values))?;
    drop(result);
    Ok(row)
}

pub(crate) fn query_first_request<C: Queryable>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
) -> Result<Option<Row>> {
    query_first_request_observing(connection, sql, values, |_| {})
}

fn catalog_query<C, T>(
    connection: &mut C,
    sql: &str,
    values: &[MySQLValue<'_>],
    decode: impl FnOnce(Vec<Row>) -> Result<T>,
) -> Result<T>
where
    C: Queryable,
{
    let context_values = values.iter().collect::<Vec<_>>();
    decode(query_request(connection, sql, values)?)
        .with_query(|| QueryContext::new(sql, &context_values))
}

fn catalog<C: Queryable>(connection: &mut C) -> Result<introspect::Catalog> {
    use drizzle_migrations::mysql::introspect::{
        RawIntrospection, apply_show_create_view, queries,
    };

    let database = catalog_query(connection, queries::DATABASE, &[], introspect::database)?;
    let selected_database = database.name.clone();
    let values = [MySQLValue::from(selected_database.as_str())];
    let mut raw = RawIntrospection {
        database,
        tables: catalog_query(connection, queries::TABLES, &values, introspect::tables)?,
        columns: catalog_query(connection, queries::COLUMNS, &values, introspect::columns)?,
        indexes: catalog_query(connection, queries::INDEXES, &values, introspect::indexes)?,
        primary_keys: catalog_query(
            connection,
            queries::PRIMARY_KEYS,
            &values,
            introspect::primary_keys,
        )?,
        foreign_keys: catalog_query(
            connection,
            queries::FOREIGN_KEYS,
            &values,
            introspect::foreign_keys,
        )?,
        checks: catalog_query(connection, queries::CHECKS, &values, introspect::checks)?,
        views: catalog_query(connection, queries::VIEWS, &values, introspect::views)?,
    };

    for view in &mut raw.views {
        let sql = introspect::view_sql(&view.database, &view.name);
        let statement = catalog_query(connection, &sql, &[], |rows| {
            introspect::view_statement(rows, &view.name)
        })?;
        apply_show_create_view(view, &statement);
    }

    introspect::Catalog::assemble(raw)
}

fn apply<C, S>(connection: &mut C, schema: &S) -> Result<()>
where
    C: Queryable,
    S: drizzle_migrations::Schema,
{
    let catalog = catalog(connection)?;
    let desired = schema.to_snapshot();
    for statement in catalog.plan(&desired)?.statements {
        if !statement.trim().is_empty() {
            execute_request(connection, &statement, &[])?;
        }
    }
    Ok(())
}

/// Blocking MySQL database wrapper.
///
/// `Connection` is the exact upstream resource supplied by the caller. A
/// [`mysql::PooledConn`] therefore returns to its pool when this wrapper is
/// dropped; Drizzle does not hide checkout or replacement behind its API.
pub struct Drizzle<Connection, Schema = ()> {
    connection: Connection,
    schema: Schema,
    session_ready: bool,
}

impl<Connection, Schema> core::fmt::Debug for Drizzle<Connection, Schema> {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        formatter
            .debug_struct("Drizzle")
            .field("session_ready", &self.session_ready)
            .finish_non_exhaustive()
    }
}

impl<Connection, Schema: Default> Drizzle<Connection, Schema> {
    /// Attaches a schema to an upstream MySQL connection or checked-out pool
    /// connection. Construction performs no I/O.
    ///
    /// Returns `(Drizzle, Schema)`, with the schema built by `Default`. The
    /// pattern that destructures the schema usually names its type. When
    /// nothing else names it, put the type on the call, and use `()` for a
    /// connection with no schema:
    ///
    /// ```no_run
    /// # use drizzle::mysql::{mysql_sync::Drizzle, prelude::*};
    /// # #[MySQLTable]
    /// # struct Users {
    /// #     #[column(PRIMARY, AUTO_INCREMENT)]
    /// #     id: u64,
    /// #     #[column(VARCHAR(255))]
    /// #     name: String,
    /// # }
    /// # #[derive(MySQLSchema)] struct Schema { users: Users }
    /// # fn connect() -> drizzle::Result<::mysql::Conn> {
    /// #     let opts = ::mysql::Opts::from_url("mysql://root:mysql@localhost/app")
    /// #         .map_err(|error| drizzle::error::DrizzleError::driver("MySQL", error))?;
    /// #     ::mysql::Conn::new(opts)
    /// #         .map_err(|error| drizzle::error::DrizzleError::driver("MySQL", error))
    /// # }
    /// # fn main() -> drizzle::Result<()> {
    /// let (mut db, Schema { users }) = Drizzle::new(connect()?);
    /// db.insert(users).value(InsertUsers::new("Alice")).execute()?;
    ///
    /// let (mut db, schema) = Drizzle::<_, Schema>::new(connect()?);
    /// db.insert(schema.users).value(InsertUsers::new("Bob")).execute()?;
    ///
    /// let (db, ()) = Drizzle::new(connect()?);
    /// # let _ = db;
    /// # Ok(()) }
    /// ```
    #[must_use]
    pub fn new(connection: Connection) -> (Self, Schema) {
        (
            Self {
                connection,
                schema: Schema::default(),
                session_ready: false,
            },
            Schema::default(),
        )
    }
}

impl<Connection, Schema> Drizzle<Connection, Schema> {
    /// Borrows the exact upstream connection supplied at construction.
    #[must_use]
    pub const fn conn(&self) -> &Connection {
        &self.connection
    }

    /// Mutably borrows the exact upstream connection supplied at construction.
    pub fn conn_mut(&mut self) -> &mut Connection {
        // Raw access can change session variables. Force the adapter to restore
        // its decoding invariants before the next attached query.
        self.session_ready = false;
        &mut self.connection
    }

    /// Borrows the schema attached at construction.
    #[must_use]
    pub const fn schema(&self) -> &Schema {
        &self.schema
    }

    /// Consumes the wrapper and returns the upstream connection.
    #[must_use]
    pub fn into_inner(self) -> Connection {
        self.connection
    }
}

impl<Connection: Queryable, Schema> Drizzle<Connection, Schema> {
    fn ensure_session(&mut self) -> Result<()> {
        if self.session_ready {
            return Ok(());
        }

        initialize_session(&mut self.connection)?;
        self.session_ready = true;
        Ok(())
    }

    /// Introspects the selected MySQL database.
    ///
    /// # Errors
    ///
    /// Returns an error when no database is selected, a catalog query fails,
    /// or MySQL reports metadata that cannot be represented losslessly.
    pub fn introspect(&mut self) -> Result<drizzle_migrations::schema::Snapshot> {
        self.ensure_session()?;
        catalog(&mut self.connection).map(introspect::Catalog::into_snapshot)
    }

    /// Brings the selected MySQL database in sync with the desired schema.
    ///
    /// MySQL can implicitly commit DDL. If a statement fails, earlier
    /// statements from this push may already be committed.
    ///
    /// # Errors
    ///
    /// Returns an error if introspection, planning, or applying a generated
    /// statement fails.
    pub fn push<S: drizzle_migrations::Schema>(&mut self, schema: &S) -> Result<()> {
        self.ensure_session()?;
        apply(&mut self.connection, schema)
    }

    pub(crate) fn execute_rendered<'q>(
        &mut self,
        query: impl ToSQL<'q, MySQLValue<'q>>,
    ) -> Result<MySQLMutationResult> {
        self.ensure_session()?;
        let (sql, values) = render(query);
        execute_request(&mut self.connection, &sql, &values)
    }

    pub(crate) fn query_rendered<'q>(
        &mut self,
        query: impl ToSQL<'q, MySQLValue<'q>>,
    ) -> Result<QueryOutput<'q>> {
        self.ensure_session()?;
        let (sql, values) = render(query);
        let rows = query_request(&mut self.connection, &sql, &values)?;
        Ok(QueryOutput::new(sql, values, rows))
    }

    pub(crate) fn query_first_rendered<'q>(
        &mut self,
        query: impl ToSQL<'q, MySQLValue<'q>>,
    ) -> Result<QueryOutput<'q>> {
        self.ensure_session()?;
        let (sql, values) = render(query);
        let rows = query_first_request(&mut self.connection, &sql, &values)?
            .into_iter()
            .collect();
        Ok(QueryOutput::new(sql, values, rows))
    }

    /// Executes arbitrary typed MySQL SQL through the prepared/binary protocol.
    ///
    /// The result contains affected-row and last-insert-ID metadata from the
    /// server's OK packet.
    ///
    /// # Errors
    ///
    /// Returns an error if session initialization or statement execution fails.
    pub fn execute<'q>(
        &mut self,
        query: impl ToSQL<'q, MySQLValue<'q>>,
    ) -> Result<MySQLMutationResult> {
        let result = self.execute_rendered(query);
        // Arbitrary SQL can change the session settings owned by this adapter.
        self.session_ready = false;
        result
    }

    /// Executes typed MySQL SQL and decodes every returned row.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or row decoding fails.
    pub fn all<'q, R>(&mut self, query: impl ToSQL<'q, MySQLValue<'q>>) -> Result<Vec<R>>
    where
        for<'row> R: FromDrizzleRow<MySQLRow<'row, Row>>,
    {
        self.rows::<_, R>(query)?.collect()
    }

    /// Executes typed MySQL SQL and returns a decoded iterator over its
    /// materialized rows.
    ///
    /// The database result is fully consumed before this method returns.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or row decoding fails.
    pub fn rows<'q, T, R>(&mut self, query: T) -> Result<Rows<R>>
    where
        T: ToSQL<'q, MySQLValue<'q>>,
        for<'row> R: FromDrizzleRow<MySQLRow<'row, Row>>,
    {
        Ok(self.query_rendered(query)?.rows::<R>())
    }

    /// Executes typed MySQL SQL and decodes the first row.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or decoding fails, or no row is returned.
    pub fn get<'q, R>(&mut self, query: impl ToSQL<'q, MySQLValue<'q>>) -> Result<R>
    where
        for<'row> R: FromDrizzleRow<MySQLRow<'row, Row>>,
    {
        self.query_first_rendered(query)?.decode_first_row()
    }

    /// Creates a typed relational query for `table`.
    #[cfg(feature = "query")]
    pub fn query<'db, 'q, Table>(
        &'db mut self,
        _table: Table,
    ) -> common::DrizzleQueryBuilder<'db, 'q, &'db mut Self, Schema, Table>
    where
        Table: drizzle_core::query::QueryTable,
    {
        common::DrizzleQueryBuilder {
            runner: self,
            builder: drizzle_core::query::QueryBuilder::new(),
            state: core::marker::PhantomData,
        }
    }

    mysql_builder_constructors!(Connection, [&'db mut self], self);
}

#[cfg(feature = "query")]
#[doc(hidden)]
pub struct RelationalPrepared;

#[cfg(feature = "query")]
impl<Connection, Schema> common::RelationalPreparedDriver for &mut Drizzle<Connection, Schema> {
    type PreparedDriver = RelationalPrepared;
}

#[cfg(feature = "query")]
impl<'db, 'q, Connection, Schema, Table, Relations, Clauses>
    common::DrizzleQueryBuilder<
        'db,
        'q,
        &'db mut Drizzle<Connection, Schema>,
        Schema,
        Table,
        Relations,
        drizzle_core::query::AllColumns,
        Clauses,
    >
where
    Connection: Queryable,
{
    /// Executes the relational query and decodes every full row.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or relational row decoding fails.
    pub fn find_many(
        self,
    ) -> Result<Vec<<Relations as drizzle_core::query::BuildRow<Table::Select>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        for<'row> Table::Select: FromDrizzleRow<MySQLRow<'row, Row>>,
        Relations: drizzle_core::query::BuildRow<Table::Select>
            + drizzle_core::query::RenderRelations<'q, MySQLValue<'q>>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        let query = common::render_relational_all(self.builder);
        self.runner
            .query_rendered(query)?
            .decode_relational_all::<Table, Relations>()
    }
}

#[cfg(feature = "query")]
impl<'db, 'q, Connection, Schema, Table, Relations, Where, Order>
    common::DrizzleQueryBuilder<
        'db,
        'q,
        &'db mut Drizzle<Connection, Schema>,
        Schema,
        Table,
        Relations,
        drizzle_core::query::AllColumns,
        drizzle_core::query::Clauses<Where, Order, drizzle_core::query::NoLimit>,
    >
where
    Connection: Queryable,
{
    /// Executes the relational query with a one-row limit.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or relational row decoding fails.
    pub fn find_first(
        self,
    ) -> Result<Option<<Relations as drizzle_core::query::BuildRow<Table::Select>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        for<'row> Table::Select: FromDrizzleRow<MySQLRow<'row, Row>>,
        Relations: drizzle_core::query::BuildRow<Table::Select>
            + drizzle_core::query::RenderRelations<'q, MySQLValue<'q>>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        Ok(self.limit(1).find_many()?.into_iter().next())
    }
}

#[cfg(feature = "query")]
impl<'db, 'q, Connection, Schema, Table, Relations, Clauses>
    common::DrizzleQueryBuilder<
        'db,
        'q,
        &'db mut Drizzle<Connection, Schema>,
        Schema,
        Table,
        Relations,
        drizzle_core::query::PartialColumns,
        Clauses,
    >
where
    Connection: Queryable,
{
    /// Executes the relational query and decodes every partial row.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or relational row decoding fails.
    pub fn find_many(
        self,
    ) -> Result<Vec<<Relations as drizzle_core::query::BuildRow<Table::PartialSelect>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        Table::PartialSelect: drizzle_core::query::FromJsonObject,
        Relations: drizzle_core::query::BuildRow<Table::PartialSelect>
            + drizzle_core::query::RenderRelations<'q, MySQLValue<'q>>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        let query = common::render_relational_partial(self.builder);
        self.runner
            .query_rendered(query)?
            .decode_relational_partial::<Table, Relations>()
    }
}

#[cfg(feature = "query")]
impl<'db, 'q, Connection, Schema, Table, Relations, Where, Order>
    common::DrizzleQueryBuilder<
        'db,
        'q,
        &'db mut Drizzle<Connection, Schema>,
        Schema,
        Table,
        Relations,
        drizzle_core::query::PartialColumns,
        drizzle_core::query::Clauses<Where, Order, drizzle_core::query::NoLimit>,
    >
where
    Connection: Queryable,
{
    /// Executes the partial relational query with a one-row limit.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or relational row decoding fails.
    pub fn find_first(
        self,
    ) -> Result<Option<<Relations as drizzle_core::query::BuildRow<Table::PartialSelect>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        Table::PartialSelect: drizzle_core::query::FromJsonObject,
        Relations: drizzle_core::query::BuildRow<Table::PartialSelect>
            + drizzle_core::query::RenderRelations<'q, MySQLValue<'q>>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        Ok(self.limit(1).find_many()?.into_iter().next())
    }
}

#[cfg(feature = "query")]
impl<'q, Table, Relations>
    common::DrizzlePreparedQuery<
        'q,
        RelationalPrepared,
        Table,
        Relations,
        drizzle_core::query::AllColumns,
    >
{
    /// Executes the prepared relational query and decodes every full row.
    ///
    /// # Errors
    ///
    /// Returns an error if binding, execution, or relational decoding fails.
    pub fn find_many(
        &self,
        connection: &mut impl Queryable,
        params: impl IntoIterator<Item = drizzle_core::ParamBind<'q, MySQLValue<'q>>>,
    ) -> Result<Vec<<Relations as drizzle_core::query::BuildRow<Table::Select>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        for<'row> Table::Select: FromDrizzleRow<MySQLRow<'row, Row>>,
        Relations: drizzle_core::query::BuildRow<Table::Select>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        initialize_session(connection)?;
        let (sql, values) = self.inner.bind(params)?;
        let values = values.collect::<Vec<_>>();
        let rows = query_request(connection, sql, &values)?;
        QueryOutput::new(sql.to_owned(), values, rows).decode_relational_all::<Table, Relations>()
    }

    /// Executes the prepared relational query and decodes its first full row.
    ///
    /// # Errors
    ///
    /// Returns an error if binding, execution, or relational decoding fails.
    pub fn find_first(
        &self,
        connection: &mut impl Queryable,
        params: impl IntoIterator<Item = drizzle_core::ParamBind<'q, MySQLValue<'q>>>,
    ) -> Result<Option<<Relations as drizzle_core::query::BuildRow<Table::Select>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        for<'row> Table::Select: FromDrizzleRow<MySQLRow<'row, Row>>,
        Relations: drizzle_core::query::BuildRow<Table::Select>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        Ok(self.find_many(connection, params)?.into_iter().next())
    }
}

#[cfg(feature = "query")]
impl<'q, Table, Relations>
    common::DrizzlePreparedQuery<
        'q,
        RelationalPrepared,
        Table,
        Relations,
        drizzle_core::query::PartialColumns,
    >
{
    /// Executes the prepared relational query and decodes every partial row.
    ///
    /// # Errors
    ///
    /// Returns an error if binding, execution, or relational decoding fails.
    pub fn find_many(
        &self,
        connection: &mut impl Queryable,
        params: impl IntoIterator<Item = drizzle_core::ParamBind<'q, MySQLValue<'q>>>,
    ) -> Result<Vec<<Relations as drizzle_core::query::BuildRow<Table::PartialSelect>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        Table::PartialSelect: drizzle_core::query::FromJsonObject,
        Relations: drizzle_core::query::BuildRow<Table::PartialSelect>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        initialize_session(connection)?;
        let (sql, values) = self.inner.bind(params)?;
        let values = values.collect::<Vec<_>>();
        let rows = query_request(connection, sql, &values)?;
        QueryOutput::new(sql.to_owned(), values, rows)
            .decode_relational_partial::<Table, Relations>()
    }

    /// Executes the prepared relational query and decodes its first partial row.
    ///
    /// # Errors
    ///
    /// Returns an error if binding, execution, or relational decoding fails.
    pub fn find_first(
        &self,
        connection: &mut impl Queryable,
        params: impl IntoIterator<Item = drizzle_core::ParamBind<'q, MySQLValue<'q>>>,
    ) -> Result<Option<<Relations as drizzle_core::query::BuildRow<Table::PartialSelect>>::Row>>
    where
        Table: drizzle_core::query::QueryTable,
        Table::PartialSelect: drizzle_core::query::FromJsonObject,
        Relations: drizzle_core::query::BuildRow<Table::PartialSelect>,
        Relations::Store: drizzle_core::query::DeserializeStore,
    {
        Ok(self.find_many(connection, params)?.into_iter().next())
    }
}

#[allow(private_bounds)]
impl<Connection: TransactionConnection, Schema: Copy> Drizzle<Connection, Schema> {
    fn start(
        &mut self,
        config: drizzle_mysql::TransactionConfig,
    ) -> Result<Transaction<'_, Schema>> {
        self.ensure_session()?;
        let transaction =
            crate::transaction::mysql::mysql_sync::start_transaction(&mut self.connection, config)
                .map_err(driver_error)?;
        // Raw transaction queries can change session variables. Restore the
        // adapter invariants when the parent becomes available again.
        self.session_ready = false;
        Ok(Transaction::new(transaction, self.schema))
    }

    /// Runs a transaction, committing on `Ok` and rolling back on `Err` or
    /// panic.
    ///
    /// # Errors
    ///
    /// Returns an error if transaction startup, the callback, commit, or
    /// rollback fails.
    pub fn transaction<R>(
        &mut self,
        config: drizzle_mysql::TransactionConfig,
        body: impl FnOnce(&Transaction<Schema>) -> Result<R>,
    ) -> Result<R> {
        let transaction = self.start(config)?;
        sync_transaction(
            transaction,
            "mysql.sync",
            || {
                drizzle_core::drizzle_trace_tx!("commit", "mysql.sync");
            },
            || {
                drizzle_core::drizzle_trace_tx!("rollback", "mysql.sync");
            },
            |transaction| body(transaction),
            |transaction| transaction.commit(),
            |transaction| transaction.rollback(),
        )
    }
}

impl<Schema> Drizzle<mysql::Conn, Schema> {
    /// Applies pending embedded migrations in MySQL autocommit mode.
    ///
    /// Each migration is marked dirty before its first statement and marked
    /// complete only after its last statement succeeds. MySQL DDL cannot be
    /// made migration-wide atomic, so an interrupted run must be reconciled
    /// manually before this method will continue.
    ///
    /// The connection must have autocommit enabled. Finish transactions begun
    /// through raw SQL or the raw driver before calling this method because
    /// the client does not expose their protocol transaction state.
    ///
    /// # Errors
    ///
    /// Returns an error if locking, migration discovery, statement execution,
    /// or tracking-table maintenance fails.
    pub fn migrate(
        &mut self,
        migrations: &[drizzle_migrations::Migration],
        tracking: drizzle_migrations::Tracking,
    ) -> Result<drizzle_migrations::MigrateOutcome> {
        let result = migration::Runner::new(&mut self.connection, migrations, tracking).run();
        self.session_ready = false;
        result
    }
}

impl<Schema> Drizzle<mysql::PooledConn, Schema> {
    /// Applies pending embedded migrations in MySQL autocommit mode.
    ///
    /// This holds the checked-out connection for the advisory lock's entire
    /// lifetime. Interrupted migrations remain dirty and require manual
    /// reconciliation before this method will continue.
    ///
    /// The checked-out connection must have autocommit enabled and must not be
    /// inside a transaction begun through raw SQL or the raw driver.
    ///
    /// # Errors
    ///
    /// Returns an error if locking, migration discovery, statement execution,
    /// or tracking-table maintenance fails.
    pub fn migrate(
        &mut self,
        migrations: &[drizzle_migrations::Migration],
        tracking: drizzle_migrations::Tracking,
    ) -> Result<drizzle_migrations::MigrateOutcome> {
        let result = migration::Runner::new(&mut self.connection, migrations, tracking).run();
        self.session_ready = false;
        result
    }
}

impl<Connection: Queryable, Schema> Drizzle<Connection, Schema>
where
    Schema: drizzle_core::traits::SQLSchemaImpl + Default,
{
    /// Creates every schema object in dependency order.
    ///
    /// # Errors
    ///
    /// Returns an error if schema rendering, session initialization, or DDL
    /// execution fails.
    pub fn create(&mut self) -> Result<()> {
        for statement in Schema::default().create_statements()? {
            self.ensure_session()?;
            execute_request(&mut self.connection, &statement, &[])?;
        }
        Ok(())
    }
}

impl<'db, 'q, Connection, Schema, State, Table, Mk, Rw, Grouped>
    DrizzleBuilder<
        'db,
        Connection,
        Schema,
        QueryBuilder<'q, Schema, State, Table, Mk, Rw, Grouped>,
        State,
    >
where
    Connection: Queryable,
    State: builder::ExecutableState,
{
    /// Executes this statement through MySQL's prepared/binary protocol.
    ///
    /// Returns affected-row and last-insert-ID metadata from the server's OK
    /// packet.
    ///
    /// # Errors
    ///
    /// Returns an error if session initialization or execution fails.
    pub fn execute(self) -> Result<MySQLMutationResult> {
        self.runner.execute_rendered(self.builder)
    }

    /// Executes this query and decodes every row using its inferred marker.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or row decoding fails.
    pub fn all<R, ScopeProof, AggProof>(self) -> Result<Vec<R>>
    where
        for<'row> Mk: DecodeSelectedRef<&'row MySQLRow<'row, Row>, R>
            + MarkerScopeValidFor<ScopeProof>
            + StrictDecodeMarker
            + MarkerColumnCountValid<MySQLRow<'row, Row>, Rw, R, ScopeProof>,
        Mk: MarkerAggValidFor<Grouped, AggProof>,
    {
        self.runner
            .query_rendered(self.builder)?
            .decode_all::<Mk, R>()
    }

    /// Executes this query and returns a decoded iterator over its
    /// materialized rows.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or row decoding fails.
    pub fn rows<ScopeProof, AggProof>(self) -> Result<Rows<Rw>>
    where
        for<'row> Mk: MarkerScopeValidFor<ScopeProof>
            + StrictDecodeMarker
            + MarkerColumnCountValid<MySQLRow<'row, Row>, Rw, Rw, ScopeProof>,
        Mk: MarkerAggValidFor<Grouped, AggProof>,
        for<'row> Rw: FromDrizzleRow<MySQLRow<'row, Row>>,
    {
        Ok(self.runner.query_rendered(self.builder)?.rows::<Rw>())
    }

    /// Executes this query and decodes its first row.
    ///
    /// # Errors
    ///
    /// Returns an error if execution or decoding fails, or no row is returned.
    pub fn get<R, ScopeProof, AggProof>(self) -> Result<R>
    where
        for<'row> Mk: DecodeSelectedRef<&'row MySQLRow<'row, Row>, R>
            + MarkerScopeValidFor<ScopeProof>
            + StrictDecodeMarker
            + MarkerColumnCountValid<MySQLRow<'row, Row>, Rw, R, ScopeProof>,
        Mk: MarkerAggValidFor<Grouped, AggProof>,
    {
        self.runner
            .query_first_rendered(self.builder)?
            .decode_first::<Mk, R>()
    }

    /// Detaches a reusable prepared query from this runner.
    #[must_use]
    pub fn prepare(self) -> prepared::PreparedStatement<'q, Mk, Rw, Grouped> {
        prepared::PreparedStatement::new(drizzle_core::prepared::prepare_render(
            &self.builder.into_sql(),
        ))
    }
}