1use crate::error::Error;
2use crate::types::DatabaseValue;
3use std::borrow::Cow;
4
5pub trait SqlBackend {
6 type Param;
7 fn convert(value: DatabaseValue) -> Self::Param;
8}
9
10pub trait IntoResultCow {
11 fn into_result_cow(self) -> Result<Cow<'static, str>, Error>;
12}
13
14impl IntoResultCow for &'static str {
15 fn into_result_cow(self) -> Result<Cow<'static, str>, Error> {
16 Ok(Cow::Borrowed(self))
17 }
18}
19
20impl IntoResultCow for String {
21 fn into_result_cow(self) -> Result<Cow<'static, str>, Error> {
22 Ok(Cow::Owned(self))
23 }
24}
25
26impl IntoResultCow for Cow<'static, str> {
27 fn into_result_cow(self) -> Result<Cow<'static, str>, Error> {
28 Ok(self)
29 }
30}
31
32impl IntoResultCow for Result<Cow<'static, str>, Error> {
33 fn into_result_cow(self) -> Result<Cow<'static, str>, Error> {
34 self
35 }
36}
37
38pub trait Query {
39 fn build(&self) -> Result<(Cow<'static, str>, Vec<DatabaseValue>), Error>;
40}
41
42pub trait QueryExt: Query {
43 fn build_params<B: SqlBackend>(&self) -> Result<(Cow<'static, str>, Vec<B::Param>), Error> {
44 self.build()
45 .map(|(sql, values)| (sql, values.into_iter().map(B::convert).collect()))
46 }
47}
48
49impl<T: Query + ?Sized> QueryExt for T {}
50
51pub trait FieldUpdate {
52 fn field(&self) -> &'static str;
53 fn to_value(&self) -> DatabaseValue;
54}
55
56pub trait FieldMeta {
57 fn is_primary_key(&self) -> bool;
58}
59
60pub trait ToParams {
61 fn add_params(&self, params: &mut Vec<DatabaseValue>);
62}
63
64impl<T: Clone + Into<DatabaseValue>> ToParams for T {
65 fn add_params(&self, params: &mut Vec<DatabaseValue>) {
66 params.push(self.clone().into());
67 }
68}
69
70impl ToParams for Vec<DatabaseValue> {
71 fn add_params(&self, params: &mut Vec<DatabaseValue>) {
72 for v in self {
73 params.push(v.clone());
74 }
75 }
76}
77
78#[derive(Clone, Copy, Debug)]
79pub enum MigrationInfo {
80 Table(&'static str),
81 Index(&'static str),
82 Column {
83 table: &'static str,
84 column: &'static str,
85 },
86}
87
88impl ToParams for MigrationInfo {
89 fn add_params(&self, _params: &mut Vec<DatabaseValue>) {}
90}
91
92pub trait MigrationMeta {
93 fn migration_info(&self) -> Option<MigrationInfo>;
94}
95
96#[async_trait::async_trait(?Send)]
97pub trait DatabaseExecutor {
98 async fn query_all<T, Q>(&self, sql: Q) -> Result<Vec<T>, Error>
99 where
100 T: serde::de::DeserializeOwned,
101 Q: Query + 'async_trait;
102
103 async fn query_first<T, Q>(&self, sql: Q) -> Result<Option<T>, Error>
104 where
105 T: serde::de::DeserializeOwned,
106 Q: Query + 'async_trait;
107
108 async fn execute<Q>(&self, sql: Q) -> Result<(), Error>
109 where
110 Q: Query + 'async_trait;
111
112 async fn execute_batch<Q>(&self, sqls: Vec<Q>) -> Result<(), Error>
113 where
114 Q: Query + 'async_trait;
115}