microrm 0.6.3

Lightweight ORM using sqlite as a backend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
//! Database query interface.

use crate::{
    db::{StatementContext, Transaction},
    schema::{
        datum::{BorrowedDatum, BorrowedDatumList, Datum},
        entity::{Entity, EntityID, EntityPart, EntityPartList, EntityRef},
        index::Index,
        relation::{LocalSide, RelationData},
        Borrowed, Stored,
    },
    DBResult, Error,
};

use std::collections::HashMap;
use std::hash::{Hash, Hasher};

pub(crate) mod base_queries;
pub(crate) mod components;
pub(crate) mod containers;
use containers::*;

#[derive(Debug, Clone)]
pub(crate) enum QueryPartData<'l> {
    Owned(String),
    Borrowed(&'l str),
}

impl std::fmt::Display for QueryPartData<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Owned(s) => f.write_str(s),
            Self::Borrowed(s) => f.write_str(s),
        }
    }
}

impl From<String> for QueryPartData<'_> {
    fn from(value: String) -> Self {
        Self::Owned(value)
    }
}

impl<'l> From<&'l str> for QueryPartData<'l> {
    fn from(value: &'l str) -> Self {
        Self::Borrowed(value)
    }
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
pub(crate) enum QueryPart {
    Root,
    Columns,
    From,
    Set,
    Join,
    Where,
    Order,
    Limit,
    Trailing,
}

// helper trait to replace itertools dependency
trait Joinable {
    fn join(self, sep: &str) -> String;
}

impl<T: std::fmt::Display, I: Iterator<Item = T>> Joinable for I {
    fn join(self, sep: &str) -> String {
        use std::fmt::Write;
        let mut out = String::new();
        let mut first = true;
        for item in self {
            if first {
                first = false
            } else {
                out.push_str(sep);
            }
            write!(&mut out, "{}", item).unwrap();
        }
        out
    }
}

/// Represents a SQL query built during runtime.
#[derive(Debug)]
pub struct Query<'l> {
    parts: HashMap<QueryPart, Vec<QueryPartData<'l>>>,
}

impl<'l> Query<'l> {
    pub(crate) fn new() -> Self {
        Self {
            parts: Default::default(),
        }
    }

    pub(crate) fn attach<T: Into<QueryPartData<'l>>>(mut self, qp: QueryPart, val: T) -> Self {
        self.attach_mut(qp, val.into());
        self
    }

    pub(crate) fn replace<T: Into<QueryPartData<'l>>>(mut self, qp: QueryPart, val: T) -> Self {
        self.parts.remove(&qp);
        self.attach(qp, val.into())
    }

    pub(crate) fn attach_mut<T: Into<QueryPartData<'l>>>(&mut self, qp: QueryPart, val: T) {
        self.parts.entry(qp).or_default().push(val.into());
    }

    pub(crate) fn assemble(mut self) -> String {
        let root = self.parts.remove(&QueryPart::Root).unwrap().remove(0);

        let columns_ = match self.parts.remove(&QueryPart::Columns) {
            None => String::new(),
            Some(v) => v.into_iter().join(","),
        };

        let from_ = match self.parts.remove(&QueryPart::From) {
            None => String::new(),
            Some(v) => {
                format!("FROM {}", v.into_iter().join(","))
            },
        };

        let set_ = match self.parts.remove(&QueryPart::Set) {
            None => String::new(),
            Some(v) => {
                format!("SET {}", v.into_iter().join(","))
            },
        };

        let join_ = match self.parts.remove(&QueryPart::Join) {
            None => String::new(),
            Some(v) => v
                .into_iter()
                .map(|j| format!("INNER JOIN {}", j))
                .reduce(|a, b| format!("{} {}", a, b))
                .unwrap(),
        };

        let where_ = match self.parts.remove(&QueryPart::Where) {
            None => String::new(),
            Some(v) => {
                format!("WHERE {}", v.into_iter().join(" AND "))
            },
        };

        let order_ = match self.parts.remove(&QueryPart::Order) {
            None => String::new(),
            Some(v) => v.into_iter().join(" "),
        };

        let limit_ = match self.parts.remove(&QueryPart::Limit) {
            None => String::new(),
            Some(v) => v.into_iter().join(" "),
        };

        let trailing_ = match self.parts.remove(&QueryPart::Trailing) {
            None => String::new(),
            Some(v) => v.into_iter().join(" "),
        };

        format!("{root} {columns_} {from_} {set_} {join_} {where_} {order_} {limit_} {trailing_}")
    }
}

pub(crate) struct RelationNames {
    local_name: &'static str,
    remote_name: &'static str,
    part_name: &'static str,
    dist_name: &'static str,
    domain_name: &'static str,
    range_name: &'static str,
    local_field: &'static str,
    remote_field: &'static str,
}

impl RelationNames {
    fn collect<AI: RelationInterface>(iface: &AI) -> DBResult<RelationNames> {
        let rdata = iface.get_data()?;
        let local_name = rdata.local_name;
        let remote_name = <AI::RemoteEntity>::entity_name();
        let part_name = rdata.part_name;
        let dist_name = iface.get_distinguishing_name()?;

        let (domain_name, range_name) = match AI::SIDE {
            LocalSide::Domain => (local_name, remote_name),
            LocalSide::Range => (remote_name, local_name),
        };
        let (local_field, remote_field) = match AI::SIDE {
            LocalSide::Domain => ("domain", "range"),
            LocalSide::Range => ("range", "domain"),
        };
        Ok(Self {
            local_name,
            remote_name,
            part_name,
            dist_name,
            domain_name,
            range_name,
            local_field,
            remote_field,
        })
    }

    fn relation_name(&self) -> String {
        format!(
            "{domain_name}_{range_name}_relation_{dist_name}",
            domain_name = self.domain_name,
            range_name = self.range_name,
            dist_name = self.dist_name
        )
    }
}

fn hash_of<T: Hash>(val: T) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    val.hash(&mut hasher);
    hasher.finish()
}

/// Relation map generic interface trait.
pub trait RelationInterface {
    /// The type of the entity on the non-local end of the relation.
    type RemoteEntity: Entity;
    /// A static version of the current interface, used for type-based query caching.
    type StaticVersion: RelationInterface<RemoteEntity = Self::RemoteEntity> + 'static;

    #[doc(hidden)]
    fn get_data(&self) -> DBResult<&RelationData>;
    #[doc(hidden)]
    fn get_distinguishing_name(&self) -> DBResult<&'static str>;

    /// Which side is the "local" side of the relation.
    const SIDE: LocalSide;

    /// Query this entity type without the relation filter.
    fn query_all(&self) -> impl Queryable<EntityOutput = Self::RemoteEntity> {
        components::TableComponent::<Self::RemoteEntity>::new()
    }

    /// Attempt to connect the contextual instance to a remote instance.
    fn connect_to(
        &self,
        txn: &mut Transaction,
        remote_id: <Self::RemoteEntity as Entity>::ID,
    ) -> DBResult<()>
    where
        Self: Sized,
    {
        let rdata = self.get_data()?;
        let an = RelationNames::collect::<Self>(self)?;

        base_queries::do_connect::<Self::RemoteEntity>(txn, rdata, an, remote_id)
    }

    /// Attempt to disconnect the contextual instance from a remote instance.
    fn disconnect_from(
        &self,
        txn: &mut Transaction,
        remote_id: <Self::RemoteEntity as Entity>::ID,
    ) -> DBResult<()>
    where
        Self: Sized,
    {
        let rdata = self.get_data()?;
        let an = RelationNames::collect::<Self>(self)?;

        // second, add to the relation table
        txn.lease().with_prepared(
            hash_of(("disconnect", an.local_name, an.remote_name, an.part_name)),
            || {
                Ok(format!(
                    "delete from `{relation_name}` where `{local_field}` = ? and `{remote_field}` = ?",
                    relation_name = an.relation_name(),
                    local_field = an.local_field,
                    remote_field = an.remote_field
                ))
            },
            |ctx| {
                ctx.bind(1, rdata.local_id)?;
                ctx.bind(2, remote_id.into_raw())?;

                ctx.run().map(|_| ())
            },
        )
    }
}

// ----------------------------------------------------------------------
// New query interface
// ----------------------------------------------------------------------

/// Represents a context in which we can insert an entity type `E`.
pub trait Insertable<E: Entity> {
    /// Insert an entity instance and return its new ID.
    fn insert(&self, txn: &mut Transaction, value: E) -> DBResult<E::ID>;
    /// Insert an entity reference and return its new ID.
    fn insert_ref(&self, txn: &mut Transaction, value: E::ERef<'_>) -> DBResult<E::ID>;
    /// Insert an entity instance and return a [`Stored`] instance that can be used to synchronize
    /// its values back into the database later.
    fn insert_and_return(&self, txn: &mut Transaction, value: E) -> DBResult<Stored<E>>;
}

impl<AI: RelationInterface> Insertable<AI::RemoteEntity> for AI {
    fn insert(
        &self,
        txn: &mut Transaction,
        value: AI::RemoteEntity,
    ) -> DBResult<<AI::RemoteEntity as Entity>::ID>
    where
        Self: Sized,
    {
        // we're doing two things:
        // - inserting the entity into the target table
        // - adding the relation row into the relation table

        let rdata = self.get_data()?;
        let an = RelationNames::collect::<Self>(self)?;

        // so first, into the remote table
        let remote_id = base_queries::insert(txn, &value)?;
        // then the relation
        base_queries::do_connect::<AI::RemoteEntity>(txn, rdata, an, remote_id)?;

        Ok(remote_id)
    }

    fn insert_ref(
        &self,
        txn: &mut Transaction,
        value: <AI::RemoteEntity as Entity>::ERef<'_>,
    ) -> DBResult<<AI::RemoteEntity as Entity>::ID> {
        // as with insert() above, we're first adding the entity and then doing the connection.
        let rdata = self.get_data()?;
        let an = RelationNames::collect::<Self>(self)?;

        // so first, into the remote table
        let remote_id = base_queries::insert_ref::<AI::RemoteEntity>(txn, value)?;
        // then the relation
        base_queries::do_connect::<AI::RemoteEntity>(txn, rdata, an, remote_id)?;

        Ok(remote_id)
    }

    fn insert_and_return(
        &self,
        txn: &mut Transaction,
        value: AI::RemoteEntity,
    ) -> DBResult<Stored<AI::RemoteEntity>>
    where
        Self: Sized,
    {
        // we're doing two things:
        // - inserting the entity into the target table
        // - adding the relation row into the relation table

        let rdata = self.get_data()?;
        let an = RelationNames::collect::<Self>(self)?;

        // so first, into the remote table
        let remote = base_queries::insert_and_return(txn, value)?;
        // then the relation
        base_queries::do_connect::<AI::RemoteEntity>(txn, rdata, an, remote.id())?;

        Ok(remote)
    }
}

/// Represents a searchable context of a given entity.
pub trait Queryable: Clone {
    /// The entity that results from a search in this context.
    type EntityOutput: Entity;
    /// How results will be provided. This is either a `Vec` or an `Option`.
    type OutputContainer: OutputContainer<Self::EntityOutput>;
    /// A `'static`-version of `Self`, used for `TypeId`-based caching.
    type StaticVersion: Queryable<EntityOutput = Self::EntityOutput> + 'static;

    /// Construct a concrete SQL query from this abstract type representation.
    #[doc(hidden)]
    fn build(&self) -> DBResult<Query<'_>>;
    /// Bind into any required placeholders to 'fill' an instance created by [`build`].
    #[doc(hidden)]
    fn bind(&self, stmt: &mut StatementContext, index: &mut i32) -> DBResult<()>;

    // ----------------------------------------------------------------------
    // Verbs
    // ----------------------------------------------------------------------
    /// Count all entities in the current context.
    ///
    /// Returns the number of entities.
    fn count(self, txn: &mut Transaction) -> DBResult<usize>
    where
        Self: Sized,
    {
        struct CountTag;
        txn.lease().with_prepared(
            std::any::TypeId::of::<(Self::StaticVersion, CountTag)>(),
            || {
                Ok(self
                    .build()?
                    .replace(
                        QueryPart::Columns,
                        format!(
                            "COUNT(DISTINCT `{}`.`id`)",
                            Self::EntityOutput::entity_name()
                        ),
                    )
                    .assemble())
            },
            |mut ctx| {
                // starting index is 1
                let mut index = 1;
                self.bind(&mut ctx, &mut index)?;

                Ok(ctx
                    .run()?
                    .ok_or(Error::InternalError("no resulting rows from COUNT query"))?
                    .read::<i64>(0)? as usize)
            },
        )
    }
    /// Get all entities in the current context.
    fn get(self, txn: &mut Transaction) -> DBResult<Self::OutputContainer>
    where
        Self: Sized,
    {
        struct GetTag;
        txn.lease().with_prepared(
            std::any::TypeId::of::<(Self::StaticVersion, GetTag)>(),
            || Ok(self.build()?.assemble()),
            |mut ctx| {
                // starting index is 1
                let mut index = 1;
                self.bind(&mut ctx, &mut index)?;

                <Self::OutputContainer>::assemble_from(ctx)
            },
        )
    }
    /// Iterate through all entities in the current context.
    fn iter(
        self,
        txn: &mut Transaction,
    ) -> DBResult<impl Iterator<Item = DBResult<Stored<Self::EntityOutput>>>>
    where
        Self: Sized,
    {
        struct IterTag;
        Ok(txn
            .lease()
            .iter_with_prepared(
                self,
                std::any::TypeId::of::<(Self::StaticVersion, IterTag)>(),
                |q| Ok(q.build()?.assemble()),
                |q, ctx| {
                    // starting index is 1
                    let mut index = 1;
                    q.bind(ctx, &mut index)
                },
            )?
            .map(|row| {
                let mut row = row?;
                let id = row.read::<i64>(0).expect("couldn't read ID");
                let datum_list =
                    <<Self::EntityOutput as Entity>::Parts>::build_datum_list(&mut row)
                        .expect("couldn't build datum list");
                Ok(Stored::new(
                    <Self::EntityOutput as Entity>::ID::from_raw(id),
                    <Self::EntityOutput as Entity>::build(datum_list),
                ))
            }))
    }
    /// Applies a function over references to all entities in the current context.
    fn iter_refs<'a>(
        self,
        txn: &'a mut Transaction,
        mut f: impl for<'b> FnMut(
            Borrowed<'b, <Self::EntityOutput as Entity>::ERef<'b>>,
        ) -> std::ops::ControlFlow<()>,
    ) -> DBResult<()>
    where
        Self: Sized,
    {
        struct IterRefTag;

        let mut early_break = false;

        txn.lease()
            .iter_with_prepared(
                self,
                std::any::TypeId::of::<(Self::StaticVersion, IterRefTag)>(),
                |q| Ok(q.build()?.assemble()),
                |q, ctx| {
                    // starting index is 1
                    let mut index = 1;
                    q.bind(ctx, &mut index)
                },
            )?
            .try_for_each::<_, DBResult<()>>(|row| {
                if early_break {
                    return Ok(());
                }
                let mut row = row?;
                let id = row.read::<i64>(0).expect("couldn't read ID");
                let datum_list =
                    <<Self::EntityOutput as Entity>::Parts>::build_datum_ref_list(&mut row)?;

                let r =
                    <<Self::EntityOutput as Entity>::ERef<'_> as EntityRef<'_>>::from_borrowed_list(
                        datum_list,
                    );

                match f(Borrowed::new(
                    <Self::EntityOutput as Entity>::ID::from_raw(id),
                    r,
                )) {
                    std::ops::ControlFlow::Continue(_) => Ok(()),
                    std::ops::ControlFlow::Break(_) => {
                        early_break = true;
                        Ok(())
                    },
                }
            })
    }
    /// Get IDs of all entities in the current context.
    fn get_ids(
        self,
        txn: &mut Transaction,
    ) -> DBResult<<Self::OutputContainer as OutputContainer<Self::EntityOutput>>::IDContainer>
    where
        Self: Sized,
    {
        struct GetIDTag;
        txn.lease().with_prepared(
            std::any::TypeId::of::<(Self::StaticVersion, GetIDTag)>(),
            || {
                Ok(self
                    .build()?
                    .replace(
                        QueryPart::Columns,
                        format!("`{}`.`id`", Self::EntityOutput::entity_name()),
                    )
                    .assemble())
            },
            |mut ctx| {
                // starting index is 1
                let mut index = 1;
                self.bind(&mut ctx, &mut index)?;

                <<Self::OutputContainer as OutputContainer<
                        Self::EntityOutput,
                    >>::IDContainer>::assemble_from(ctx)
            },
        )
    }
    /// Delete all entities in the current context.
    fn delete(self, txn: &mut Transaction) -> DBResult<()>
    where
        Self: Sized,
    {
        struct DeleteTag;
        txn.lease().with_prepared(
            std::any::TypeId::of::<(Self::StaticVersion, DeleteTag)>(),
            || {
                Ok(format!(
                    "DELETE FROM `{}` WHERE `id` = ({})",
                    Self::EntityOutput::entity_name(),
                    self.build()?
                        .replace(
                            QueryPart::Columns,
                            format!("`{}`.`id`", Self::EntityOutput::entity_name())
                        )
                        .assemble()
                ))
            },
            |mut ctx| {
                // starting index is 1
                let mut index = 1;
                self.bind(&mut ctx, &mut index)?;

                ctx.run()?;
                Ok(())
            },
        )
    }

    /// Delete all entities in the current context and return them
    fn remove(self, txn: &mut Transaction) -> DBResult<Self::OutputContainer>
    where
        Self: Sized,
    {
        struct DeleteTag;
        txn.lease().with_prepared(
            std::any::TypeId::of::<(Self::StaticVersion, DeleteTag)>(),
            || {
                Ok(format!(
                    "DELETE FROM `{entity}` WHERE `id` = ({subquery}) RETURNING *",
                    entity = Self::EntityOutput::entity_name(),
                    subquery = self
                        .build()?
                        .replace(
                            QueryPart::Columns,
                            format!("`{}`.`id`", Self::EntityOutput::entity_name())
                        )
                        .assemble()
                ))
            },
            |mut ctx| {
                // starting index is 1
                let mut index = 1;
                self.bind(&mut ctx, &mut index)?;

                <Self::OutputContainer>::assemble_from(ctx)
            },
        )
    }

    // ----------------------------------------------------------------------
    // Filtering methods
    // ----------------------------------------------------------------------
    /// Filter using the keying index on the entity.
    fn keyed<'l>(
        self,
        values: impl BorrowedDatumList<
            'l,
            <<Self::EntityOutput as Entity>::Keys as EntityPartList>::DatumList,
        >,
    ) -> impl Queryable<
        EntityOutput = Self::EntityOutput,
        OutputContainer = Option<Stored<Self::EntityOutput>>,
    >
    where
        Self: Sized,
    {
        components::IndexComponent::<_, _, <Self::EntityOutput as Entity>::Keys, _>::new(
            self, values,
        )
    }

    /// Filter using an arbitrary unique index on the entity.
    fn indexed<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _index: &Index<true, Self::EntityOutput, EPL>,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<
        EntityOutput = Self::EntityOutput,
        OutputContainer = Option<Stored<Self::EntityOutput>>,
    >
    where
        Self: Sized,
    {
        components::IndexComponent::<_, _, EPL, _>::new(self, values)
    }

    /// Filter using an arbitrary column on the entity.
    fn with<'l, EP: EntityPart<Entity = Self::EntityOutput>>(
        self,
        part: EP,
        value: impl BorrowedDatum<'l, EP::Datum>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    where
        Self: Sized,
    {
        components::WithComponent::new(self, part, value)
    }

    /// Filter exactly on an entity ID.
    fn with_id(
        self,
        id: <Self::EntityOutput as Entity>::ID,
    ) -> impl Queryable<
        EntityOutput = Self::EntityOutput,
        OutputContainer = Option<Stored<Self::EntityOutput>>,
    >
    where
        Self: Sized,
    {
        self.with(<Self::EntityOutput as Entity>::IDPart::default(), id)
            .first()
    }

    /// Filter using a less-than relationship on an arbitrary list of columns.
    fn filter_lt<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _parts: EPL,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EPL, 0, _>::new(self, values)
    }

    /// Filter using a less-than-or-equal relationship on an arbitrary list of columns.
    fn filter_lte<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _parts: EPL,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EPL, 1, _>::new(self, values)
    }

    /// Filter using an equality relationship on an arbitrary list of columns.
    fn filter_eq<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _parts: EPL,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EPL, 2, _>::new(self, values)
    }

    /// Filter using a greather-than-or-equal relationship on an arbitrary list of columns.
    fn filter_gte<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _parts: EPL,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EPL, 3, _>::new(self, values)
    }

    /// Filter using a greather-than relationship on an arbitrary list of columns.
    fn filter_gt<'l, EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        _parts: EPL,
        values: impl BorrowedDatumList<'l, EPL::DatumList>,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EPL, 4, _>::new(self, values)
    }

    /// Filter by using a GLOB clause. This interprets `*` and `?` to mean "any number of
    /// characters" and "single character", respectively.
    fn filter_glob<EP: EntityPart<Entity = Self::EntityOutput, Datum = String>>(
        self,
        _part: EP,
        filter: &str,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EP, 5, _>::new(self, filter)
    }

    #[cfg(feature = "regex")]
    /// Filter by using a REGEX clause. This interprets `*` and `?` to mean "any number of
    /// characters" and "single character", respectively.
    fn filter_regex<'l, EP: EntityPart<Entity = Self::EntityOutput, Datum = String>>(
        self,
        _part: EP,
        filter: &'l str,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    {
        components::FilterComponent::<_, EP, 6, _>::new(self, filter)
    }

    /// Ask to return at most a single result.
    fn first(
        self,
    ) -> impl Queryable<
        EntityOutput = Self::EntityOutput,
        OutputContainer = Option<Stored<Self::EntityOutput>>,
    >
    where
        Self: Sized,
    {
        components::SingleComponent::new(self)
    }

    /// Specify columns to sort the result by, in ascending order.
    fn order_by_asc<EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        part: EPL,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    where
        Self: Sized,
    {
        components::OrderByComponent::<_, _, true>::new(self, part)
    }

    /// Specify columns to sort the result by, in descending order.
    fn order_by_desc<EPL: EntityPartList<Entity = Self::EntityOutput>>(
        self,
        part: EPL,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    where
        Self: Sized,
    {
        components::OrderByComponent::<_, _, false>::new(self, part)
    }

    /// Limit the output to a specified number of rows. See [`Self::offset_limit`] if you also want
    /// an offset.
    fn limit(
        self,
        limit: usize,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    where
        Self: Sized,
    {
        components::LimitComponent::new(self, limit)
    }

    /// Skip the first `offset` rows of output and limit to `limit` rows.
    fn offset_limit(
        self,
        limit: usize,
        offset: usize,
    ) -> impl Queryable<EntityOutput = Self::EntityOutput, OutputContainer = Self::OutputContainer>
    where
        Self: Sized,
    {
        components::LimitComponent::new_with_offset(self, limit, offset)
    }

    // ----------------------------------------------------------------------
    // Relation-following and joining methods
    // ----------------------------------------------------------------------
    /// Join based on an existing relation.
    fn join<
        AD: RelationInterface + Datum,
        EP: EntityPart<Entity = Self::EntityOutput, Datum = AD>,
    >(
        self,
        part: EP,
    ) -> impl Queryable<EntityOutput = AD::RemoteEntity, OutputContainer = Vec<Stored<AD::RemoteEntity>>>
    where
        Self: Sized,
    {
        components::JoinComponent::<AD::RemoteEntity, Self::EntityOutput, _, Self>::new(self, part)
    }

    /// Follow a foreign key.
    #[allow(clippy::type_complexity)]
    fn foreign<EP: EntityPart<Entity = Self::EntityOutput>>(
        self,
        part: EP,
    ) -> impl Queryable<
        EntityOutput = <EP::Datum as EntityID>::Entity,
        OutputContainer = <Self::OutputContainer as OutputContainer<
            Self::EntityOutput,
        >>::WithReplacedEntity<<EP::Datum as EntityID>::Entity>,
    >
    where
        Self: Sized,
        EP::Datum: EntityID,
    {
        components::ForeignComponent::<_, EP, Self>::new(self, part)
    }
}

// Generic implementation for all relation specification types
impl<AI: RelationInterface> Queryable for &AI {
    type EntityOutput = AI::RemoteEntity;
    type OutputContainer = Vec<Stored<AI::RemoteEntity>>;
    type StaticVersion = &'static AI::StaticVersion;

    fn build(&self) -> DBResult<Query<'_>> {
        let anames = RelationNames::collect(*self).unwrap();
        let relation_name = anames.relation_name();
        Ok(Query::new()
            .attach(QueryPart::Root, "SELECT DISTINCT")
            .attach(QueryPart::Columns, format!("`{}`.*", anames.remote_name))
            .attach(QueryPart::From, format!("`{}`", relation_name))
            .attach(
                QueryPart::Join,
                format!(
                    "`{}` ON `{}`.`id` = `{}`.`{}`",
                    anames.remote_name, anames.remote_name, relation_name, anames.remote_field
                ),
            )
            .attach(
                QueryPart::Where,
                format!("`{}`.`{}` = ?", relation_name, anames.local_field),
            ))
    }
    fn bind(&self, ctx: &mut StatementContext, index: &mut i32) -> DBResult<()> {
        let rdata = self
            .get_data()
            .expect("binding query for relation with no data");

        ctx.bind(*index, rdata.local_id)?;
        *index += 1;
        Ok(())
    }
}

impl<E: Entity, EPL: EntityPartList<Entity = E>> Index<true, E, EPL> {
    /// Perform a search through this index
    ///
    /// Note that this is simply sugar for `idmap_instance.indexed(self, values)`.
    pub fn search<'a>(
        &'a self,
        values: impl BorrowedDatumList<'a, EPL::DatumList> + 'a,
    ) -> impl 'a + Queryable<EntityOutput = E, OutputContainer = Option<Stored<E>>> {
        self.indexed(self, values)
    }
}

impl<const UNIQUE: bool, E: Entity, EPL: EntityPartList<Entity = E>> Queryable
    for &Index<UNIQUE, E, EPL>
{
    type EntityOutput = E;
    type OutputContainer = Vec<Stored<E>>;
    type StaticVersion = &'static Index<UNIQUE, E, EPL>;

    fn build(&self) -> DBResult<Query<'_>> {
        Ok(Query::new()
            .attach(QueryPart::Root, "SELECT DISTINCT")
            .attach(QueryPart::Columns, "*")
            .attach(QueryPart::From, format!("`{}`", E::entity_name())))
    }
    fn bind(&self, _stmt: &mut StatementContext, _index: &mut i32) -> DBResult<()> {
        Ok(())
    }
}