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
//! This module exists to help backwards compatibility
//!
//! Might remove it in the future, let's see

use super::util::info_data_to_sql;
use super::{Info, TableTemplate};

use crate::connection::ConnectionOwned;
use crate::database::DatabaseError;
use crate::filter::{Filter, WhereFilter};
use crate::row::ToRow;
use crate::{filter, Database, Error, Result};

use std::borrow::Borrow;
use std::marker::PhantomData;
use std::sync::Arc;

#[derive(Debug)]
struct TableMeta {
	info: Info,
}

#[derive(Debug)]
pub struct TableOwned<T>
where
	T: TableTemplate,
{
	db: Database,
	name: &'static str,
	meta: Arc<TableMeta>,
	phantom: PhantomData<T>,
}

impl<T> TableOwned<T>
where
	T: TableTemplate,
{
	pub(crate) fn new(db: Database, name: &'static str) -> Self {
		let info = T::table_info();
		let meta = TableMeta { info };

		Self {
			db,
			name,
			meta: Arc::new(meta),
			phantom: PhantomData,
		}
	}

	pub fn name(&self) -> &'static str {
		self.name
	}

	pub fn info(&self) -> &Info {
		&self.meta.info
	}

	pub async fn get_connection(&self) -> Result<ConnectionOwned> {
		self.db.get().await.map_err(|e| match e {
			DatabaseError::Other(e) => e.into(),
			e => Error::Unknown(e.into()),
		})
	}

	// Create
	pub async fn try_create(&self) -> Result<()> {
		let sql = info_data_to_sql(self.name, self.meta.info.data());

		self.get_connection()
			.await?
			.connection()
			.batch_execute(sql.as_str())
			.await
	}

	/// ## Panics
	/// if the table could not be created
	pub async fn create(self) -> Self {
		self.try_create().await.expect("could not create table");
		self
	}

	// find
	// maybe rename to insert
	// and store statement in table
	pub async fn insert_one(&self, input: &T) -> Result<()> {
		self.get_connection()
			.await?
			.connection()
			.insert(self.name, input)
			.await
	}

	pub async fn insert_many<I>(&self, input: I) -> Result<()>
	where
		I: IntoIterator,
		I::Item: Borrow<T>,
	{
		let mut conn = self.get_connection().await?;
		let trans = conn.transaction().await?;
		let conn = trans.connection();

		conn.insert_many(self.name, input).await?;

		trans.commit().await?;

		Ok(())
	}

	/*
	SELECT id, name, FROM {}
	*/
	pub async fn find_all(&self) -> Result<Vec<T>> {
		self.get_connection()
			.await?
			.connection()
			.select(self.name, filter!())
			.await
	}

	pub async fn find_many(
		&self,
		filter: impl Borrow<Filter<'_>>,
	) -> Result<Vec<T>> {
		self.get_connection()
			.await?
			.connection()
			.select(self.name, filter)
			.await
	}

	pub async fn find_one(
		&self,
		filter: impl Borrow<Filter<'_>>,
	) -> Result<Option<T>> {
		self.get_connection()
			.await?
			.connection()
			.select_opt(self.name, filter)
			.await
	}

	pub async fn count<'a>(
		&self,
		column: &str,
		filter: impl Borrow<Filter<'_>>,
	) -> Result<u32> {
		self.get_connection()
			.await?
			.connection()
			.count(self.name, column, filter)
			.await
	}

	// update one
	pub async fn update<'a, U>(
		&self,
		item: &U,
		filter: impl Borrow<WhereFilter<'a>>,
	) -> Result<()>
	where
		U: ToRow,
	{
		self.get_connection()
			.await?
			.connection()
			.update(self.name, item, filter)
			.await
	}

	pub async fn update_full<'a>(
		&self,
		input: &'a T,
		filter: impl Borrow<WhereFilter<'a>>,
	) -> Result<()> {
		self.get_connection()
			.await?
			.connection()
			.update(self.name, input, filter)
			.await
	}

	// delete one
	pub async fn delete(
		&self,
		filter: impl Borrow<WhereFilter<'_>>,
	) -> Result<()> {
		self.get_connection()
			.await?
			.connection()
			.delete(self.name, filter)
			.await
	}
}

impl<T> Clone for TableOwned<T>
where
	T: TableTemplate,
{
	fn clone(&self) -> Self {
		Self {
			db: self.db.clone(),
			name: self.name,
			meta: self.meta.clone(),
			phantom: PhantomData,
		}
	}
}