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
//! # Backend Module for GeekORM
//!
//! **Example:**
//!
//! Here is an example of how to use GeekORM with a mock connection.
//!
//! ```no_run
//! # #[cfg(feature = "backends")] {
//! # use anyhow::Result;
//! use geekorm::prelude::*;
//!
//! # #[derive(Debug, Clone)]
//! # struct Connection;
//! # impl GeekConnection for Connection {
//! #     type Connection = Self;
//! #     type Row = ();
//! #     type Rows = ();
//! #     type Statement = ();
//! # }
//!
//! #[derive(Table, Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
//! pub struct Users {
//!     #[geekorm(primary_key, auto_increment)]
//!     pub id: PrimaryKey<i32>,
//!     #[geekorm(unique)]
//!     pub username: String,
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     // Create a new connection (this is a mock connection)
//!     let connection = Connection {};
//!
//!     Users::create_table(&connection).await?;
//!
//!     let users = vec!["geekmasher", "bob", "alice", "eve", "mallory", "trent"];
//!     for user in users {
//!         let mut new_user = Users::new(user);
//!         new_user.save(&connection).await?;
//!     }
//!
//!     // Fetch or create a user
//!     let mut geek = Users::new("geekmasher");
//!     geek.fetch_or_create(&connection).await?;
//!     
//!     // Fetch a user by their username (exact match)
//!     let geekmasher = Users::fetch_by_username(&connection, "geekmasher").await?;
//!
//!     // Search for a user (partial match)
//!     let search = Users::search(&connection, "geek").await?;
//!     # assert_eq!(search.len(), 1);
//!
//!     // Fetch first and last user
//!     let first_user = Users::first(&connection).await?;
//!     # assert_eq!(first_user.username, "geekmasher");
//!     let last_user = Users::last(&connection).await?;
//!     # assert_eq!(last_user.username, "trent");
//!
//!
//!     Ok(())
//! }
//! # }
//! ```

use std::collections::HashMap;

use crate::{Query, QueryBuilder, QueryBuilderTrait, TableBuilder, TablePrimaryKey, Value};

#[cfg(feature = "libsql")]
pub mod libsql;
#[cfg(feature = "rusqlite")]
pub mod rusqlite;

/// GeekConnection is the trait used for models to interact with the database.
///
/// This trait is used to define the methods that are used to interact with the database.
pub trait GeekConnector
where
    Self: Sized + TableBuilder + QueryBuilderTrait + serde::Serialize + serde::de::DeserializeOwned,
{
    /// Query the database with an active Connection and Query
    #[allow(async_fn_in_trait, unused_variables)]
    async fn query<'a, T>(
        connection: impl Into<&'a T>,
        query: Query,
    ) -> Result<Vec<Self>, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Ok(T::query::<Self>(connection.into(), query).await?)
    }

    /// Query the first row from the database with an active Connection and Query
    #[allow(async_fn_in_trait, unused_variables)]
    async fn query_first<'a, T>(
        connection: impl Into<&'a T>,
        query: Query,
    ) -> Result<Self, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Ok(T::query_first::<Self>(connection.into(), query).await?)
    }

    /// Execute a query on the database and do not return any rows
    #[allow(async_fn_in_trait, unused_variables)]
    async fn execute<'a, T>(connection: impl Into<&'a T>, query: Query) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Ok(T::execute::<Self>(connection.into(), query).await?)
    }

    /// Create a table in the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn create_table<'a, T>(connection: impl Into<&'a T>) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
        Self: serde::Serialize,
    {
        Ok(T::create_table::<Self>(connection.into()).await?)
    }

    /// Count the number of rows based on a Query
    #[allow(async_fn_in_trait, unused_variables)]
    async fn row_count<'a, T>(
        connection: impl Into<&'a T>,
        query: Query,
    ) -> Result<i64, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Ok(T::row_count(connection.into(), query).await?)
    }

    /// Update the current object in the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn update<'a, T>(&self, connection: impl Into<&'a T>) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Self::execute(connection, Self::query_update(self)).await
    }

    /// Save the current object to the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn save<'a, T>(&mut self, connection: impl Into<&'a T>) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a;

    /// Delete the current object from the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn delete<'a, T>(&self, connection: impl Into<&'a T>) -> Result<(), crate::Error>
    where
        T: GeekConnection + 'a,
    {
        Err(crate::Error::NotImplemented)
    }

    /// Fetches all of the foreign key values for the current object
    #[allow(async_fn_in_trait, unused_variables)]
    async fn fetch<'a, T>(&mut self, connection: impl Into<&'a T>) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a;

    /// Fetch all rows from the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn fetch_all<'a, T>(connection: impl Into<&'a T>) -> Result<Vec<Self>, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
    {
        Ok(T::query::<Self>(
            connection.into(),
            QueryBuilder::select().table(Self::table()).build()?,
        )
        .await?)
    }

    /// Fetch or create a row in the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn fetch_or_create<'a, T>(
        &mut self,
        connection: impl Into<&'a T>,
    ) -> Result<(), crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a;

    /// Search for a row in the database based on specific criteria
    #[cfg(feature = "search")]
    #[allow(async_fn_in_trait, unused_variables)]
    async fn search<'a, T>(
        connection: impl Into<&'a T>,
        search: impl Into<String>,
    ) -> Result<Vec<Self>, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a;

    /// Fetch the first row from the database (based on the primary key)
    #[allow(async_fn_in_trait, unused_variables)]
    async fn first<'a, T>(connection: impl Into<&'a T>) -> Result<Self, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
        Self: TablePrimaryKey,
    {
        Ok(T::query_first::<Self>(
            connection.into(),
            Self::query_select()
                .table(Self::table())
                .order_by(
                    &Self::primary_key(),
                    crate::builder::models::QueryOrder::Asc,
                )
                .limit(1)
                .build()?,
        )
        .await?)
    }

    /// Fetch last row from the database (based on the primary key)
    #[allow(async_fn_in_trait, unused_variables)]
    async fn last<'a, T>(connection: impl Into<&'a T>) -> Result<Self, crate::Error>
    where
        T: GeekConnection<Connection = T> + 'a,
        Self: TablePrimaryKey,
    {
        Ok(T::query_first::<Self>(
            connection.into(),
            Self::query_select()
                .table(Self::table())
                .order_by(
                    &Self::primary_key(),
                    crate::builder::models::QueryOrder::Desc,
                )
                .limit(1)
                .build()?,
        )
        .await?)
    }
}

/// GeekConnection is the trait that all backends must implement to be able
/// to interact with the database.
pub trait GeekConnection {
    /// Single item
    type Row;
    /// Multiple items
    type Rows;
    /// Native Connection
    type Connection;
    /// Native Statement (if any)
    type Statement;

    /// Create a table in the database
    #[allow(async_fn_in_trait, unused_variables)]
    async fn create_table<T>(connection: &Self::Connection) -> Result<(), crate::Error>
    where
        T: TableBuilder
            + QueryBuilderTrait
            + Sized
            + serde::Serialize
            + serde::de::DeserializeOwned,
    {
        Err(crate::Error::NotImplemented)
    }

    /// Run a SELECT Count query on the database and return the number of rows
    #[allow(async_fn_in_trait, unused_variables)]
    async fn row_count(connection: &Self::Connection, query: Query) -> Result<i64, crate::Error> {
        Err(crate::Error::NotImplemented)
    }

    /// Execute a query on the database and do not return any rows
    #[allow(async_fn_in_trait, unused_variables)]
    async fn execute<T>(connection: &Self::Connection, query: Query) -> Result<(), crate::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        Err(crate::Error::NotImplemented)
    }

    /// Query the database with an active Connection and Query
    #[allow(async_fn_in_trait, unused_variables)]
    async fn query<T>(connection: &Self::Connection, query: Query) -> Result<Vec<T>, crate::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        Err(crate::Error::NotImplemented)
    }

    /// Query the database with an active Connection and Query and return the first row.
    ///
    /// Note: Make sure the query is limited to 1 row to avoid retrieving multiple rows
    /// and only using the first one.
    #[allow(async_fn_in_trait, unused_variables)]
    async fn query_first<T>(connection: &Self::Connection, query: Query) -> Result<T, crate::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        Err(crate::Error::NotImplemented)
    }

    /// Query the database with an active Connection and Query and return a list of GeekORM Values.
    #[allow(async_fn_in_trait, unused_variables)]
    async fn query_raw(
        connection: &Self::Connection,
        query: Query,
    ) -> Result<Vec<HashMap<String, Value>>, crate::Error> {
        Err(crate::Error::NotImplemented)
    }
}