Skip to main content

rust_query/
db.rs

1use std::{fmt::Debug, marker::PhantomData};
2
3use crate::Table;
4
5/// Row reference that can be used in any query in the same transaction.
6///
7/// [TableRow] is restricted to a single thread to prevent it from being used in a different transaction.
8pub struct TableRow<T: Table> {
9    pub(crate) _local: PhantomData<*const ()>,
10    pub(crate) inner: TableRowInner<T>,
11}
12
13impl<T: Table> TableRow<T> {
14    pub(crate) fn migrate_row(prev: TableRow<T::MigrateFrom>) -> Self {
15        Self {
16            _local: PhantomData,
17            inner: TableRowInner {
18                _p: PhantomData,
19                idx: prev.inner.idx,
20            },
21        }
22    }
23}
24
25impl<T: Table> Eq for TableRow<T> {}
26
27impl<T: Table> PartialOrd for TableRow<T> {
28    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
29        Some(self.cmp(other))
30    }
31}
32
33impl<T: Table> Ord for TableRow<T> {
34    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
35        self.inner.idx.cmp(&other.inner.idx)
36    }
37}
38
39pub(crate) struct TableRowInner<T> {
40    pub(crate) _p: PhantomData<T>,
41    pub(crate) idx: i64,
42}
43
44impl<T: Table> PartialEq for TableRow<T> {
45    fn eq(&self, other: &Self) -> bool {
46        self.inner.idx == other.inner.idx
47    }
48}
49
50impl<T: Table> Debug for TableRow<T> {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(f, "db_{}", self.inner.idx)
53    }
54}
55
56impl<T: Table> Clone for TableRow<T> {
57    fn clone(&self) -> Self {
58        *self
59    }
60}
61
62impl<T: Table> Copy for TableRow<T> {}
63
64impl<T> Clone for TableRowInner<T> {
65    fn clone(&self) -> Self {
66        *self
67    }
68}
69impl<T> Copy for TableRowInner<T> {}
70
71/// This makes it possible to use TableRow as a parameter in
72/// rusqlite queries and statements.
73impl<T: Table> rusqlite::ToSql for TableRow<T> {
74    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
75        self.inner.idx.to_sql()
76    }
77}