chuchi_postgres/table/
table.rs1use std::borrow::{Borrow, Cow};
2
3use crate::{
4 Connection, Error,
5 filter::{Filter, WhereFilter},
6 row::{FromRowOwned, NamedColumns, ToRow, ToRowStatic},
7};
8
9#[derive(Debug, Clone)]
10pub struct Table {
11 name: Cow<'static, str>,
12}
13
14impl Table {
15 pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
16 Self { name: name.into() }
17 }
18
19 pub fn name(&self) -> &str {
20 self.name.as_ref()
21 }
22
23 pub fn with_conn<'a>(&'a self, conn: Connection<'a>) -> TableWithConn<'a> {
24 TableWithConn { table: &self, conn }
25 }
26}
27
28#[derive(Debug, Clone)]
29pub struct TableWithConn<'a> {
30 table: &'a Table,
31 conn: Connection<'a>,
32}
33
34impl TableWithConn<'_> {
35 pub fn name(&self) -> &str {
37 self.table.name.as_ref()
38 }
39
40 pub async fn select<R>(
41 &self,
42 filter: impl Borrow<Filter<'_>>,
43 ) -> Result<Vec<R>, Error>
44 where
45 R: FromRowOwned + NamedColumns,
46 {
47 self.conn.select(self.name(), filter).await
48 }
49
50 pub async fn select_one<R>(
51 &self,
52 filter: impl Borrow<Filter<'_>>,
53 ) -> Result<R, Error>
54 where
55 R: FromRowOwned + NamedColumns,
56 {
57 self.conn.select_one(self.name(), filter).await
58 }
59
60 pub async fn select_opt<R>(
61 &self,
62 filter: impl Borrow<Filter<'_>>,
63 ) -> Result<Option<R>, Error>
64 where
65 R: FromRowOwned + NamedColumns,
66 {
67 self.conn.select_opt(self.name(), filter).await
68 }
69
70 pub async fn count(
71 &self,
72 column: &str,
73 filter: impl Borrow<Filter<'_>>,
74 ) -> Result<u64, Error> {
75 self.conn.count(self.name(), column, filter).await
76 }
77
78 pub async fn insert<U>(&self, item: &U) -> Result<(), Error>
79 where
80 U: ToRow,
81 {
82 self.conn.insert(self.name(), item).await
83 }
84
85 pub async fn insert_many<U, I>(&self, items: I) -> Result<(), Error>
86 where
87 U: ToRowStatic,
88 I: IntoIterator,
89 I::Item: Borrow<U>,
90 {
91 self.conn.insert_many(self.name(), items).await
92 }
93
94 pub async fn update<U>(
95 &self,
96 item: &U,
97 filter: impl Borrow<WhereFilter<'_>>,
98 ) -> Result<(), Error>
99 where
100 U: ToRow,
101 {
102 self.conn.update(self.name(), item, filter).await
103 }
104
105 pub async fn delete(
106 &self,
107 filter: impl Borrow<WhereFilter<'_>>,
108 ) -> Result<(), Error> {
109 self.conn.delete(self.name(), filter).await
110 }
111
112 pub fn conn(&self) -> &Connection<'_> {
113 &self.conn
114 }
115}