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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Latitude is a library for dynamic runtime DDL based on [`sqlx`](https://github.com/launchbadge/sqlx)
//! and [`barrel`](https://github.com/rust-db/barrel). **_NOTE_**: This project
//! is in early development along with `sqlx`. Please use at your own risk and strongly
//! consider using a better tested and polished project such as
//! [Refinery](https://github.com/rust-db/refinery). There will definitely be API changes
//! in the near future.
//!
//! Originally this was intended to to be a migration toolkit, but, it has been slimmed down. It's
//! unclear if we will still pursue a migration oriented API. Adding migration capability would be
//! a feature addition as opposed to a rewrite.
//! With the migratio changes this library could be considered amore portable but less
//! accessible alternative to `sqlx-cli`: users require less concern over understanding and
//! maintaining multiple SQL dialects, but, must have familiarity with Rust to get up and
//! running. It may be a good fit if your application is already written in Rust and either:
//!     
//! - you want migration compatibility across multiple databases (e.g. if you are using MySQL
//!     in production and SQLite for development); or
//!
//! - you just like writing in the DSL over plain SQL
//!
//! Please raise an issue on GitHub if you have suggestions, feedback, bug reports, or
//! otherwise.
//!
//! ## Getting Started
//!
//! ```toml
//! latitude = 0.0.1
//! ```
//!
//! ## Usage
//!
//! ```
//! use latitude::prelude::*;
//!
//! let connection = Connection::new("sqlite::memory:").await?;
//!
//! table::create("users")
//!       .column("name", varchar(255))
//!       .column("age",  integer())
//!       .column("xyx",  boolean())
//!       .execute(&connection)
//!       .await?
//! ```
use async_trait::async_trait;
use barrel::Migration;
use sqlx::{any::AnyKind, any::AnyPool, Any, Database, Executor};
use std::str::FromStr;
use thiserror::Error;

pub use barrel::types;

/// Exports commonly used types and modules
pub mod prelude {
    pub use crate::db;
    pub use crate::table;
    pub use crate::table::CreateTable;
    pub use crate::types;
    pub use crate::types::boolean;
    pub use crate::types::date;
    pub use crate::types::integer;
    pub use crate::types::primary;
    pub use crate::types::text;
    pub use crate::types::varchar;
    pub use crate::Statement;
}

pub mod db {
    /// A `DROP DATABASE` statement. This is a permanent action
    /// and the data will most likely be non-recoverable.
    pub struct DropDatabase {}

    /// A `CREATE DATABASE` statement.
    pub struct CreateDatabase {}

    /// Create a `DropDatabase` statement. This is a permanent action
    /// and the data will most likely be non-recoverable.
    pub fn drop() -> DropDatabase {
        DropDatabase {}
    }

    /// Create a `CreateDatabase` statement
    pub fn create() -> CreateDatabase {
        CreateDatabase {}
    }
}

/// DDL operations for tables such as `CREATE`, `DROP`, and `ALTER`
///
/// # Examples
///
/// ```
/// use latitude::{table, types};
///
/// table::create("users")
///       .column("id", types::primary())
///       .column("name", types::varchar(50))
///       .if_not_exists();
/// ```
pub mod table {

    use barrel::types::Type;

    /// A `CREATE TABLE` statement
    pub struct CreateTable {
        pub(crate) name: String,
        pub(crate) columns: Vec<(String, Type)>,
        pub(crate) if_not_exists: bool,
    }

    impl CreateTable {
        /// Add the `IF NOT EXISTS` qualifier to the create table
        /// statement
        pub fn if_not_exists(mut self) -> Self {
            self.if_not_exists = true;
            self
        }

        /// Add a column to the create table statement
        pub fn column<N: Into<String>>(mut self, name: N, _type: Type) -> Self {
            self.columns.push((name.into(), _type));
            self
        }
    }

    /// Create a `CREATE TABLE` statement for the provided table `name`
    ///
    /// # Examples
    ///
    /// ```
    /// use latitude::{table, types};
    ///
    /// table::create("users")
    ///       .column("id", types::primary())
    ///       .column("name", types::varchar(50))
    ///       .if_not_exists();
    /// ```
    pub fn create<N: Into<String>>(name: N) -> CreateTable {
        CreateTable {
            name: name.into(),
            columns: Vec::new(),
            if_not_exists: false,
        }
    }

    /// A `DROP TABLE` statement
    pub struct DropTable {
        #[allow(dead_code)]
        pub(crate) name: String,
        pub(crate) if_exists: bool,
    }

    impl DropTable {
        /// Add the `IF EXISTS` qualifier to this drop table statement
        pub fn if_exists(mut self) -> Self {
            self.if_exists = true;
            self
        }
    }

    /// Create a `DROP TABLE` statement for the provided table `name`.
    ///
    /// # Examples
    ///
    /// ```
    /// use latitude::table;
    ///
    /// table::drop("users")
    ///       .if_exists();
    /// ```
    pub fn drop<N: Into<String>>(name: N) -> DropTable {
        DropTable {
            name: name.into(),
            if_exists: false,
        }
    }
}

#[derive(Debug, Error)]
enum Error {
    #[error("Attempted to use an unsupported SQL dialect; available options are SQLite and MySQL")]
    UnsupportedDialect,
}

#[async_trait]
pub trait Dialect {
    fn dialect() -> AnyKind;

    /// cant for the life of me get A: Acquire to work directly on statement
    async fn execute_statement(&self, statement: &str) -> Result<(), sqlx::Error>;
}

#[async_trait]
impl Dialect for sqlx::Pool<sqlx::Sqlite> {
    fn dialect() -> AnyKind {
        AnyKind::Sqlite
    }

    async fn execute_statement(&self, statement: &str) -> Result<(), sqlx::Error> {
        sqlx::query(statement).execute(self).await?;
        Ok(())
    }
}

#[async_trait]
impl Dialect for sqlx::Pool<sqlx::MySql> {
    fn dialect() -> AnyKind {
        AnyKind::MySql
    }

    async fn execute_statement(&self, statement: &str) -> Result<(), sqlx::Error> {
        sqlx::query(statement).execute(self).await?;
        Ok(())
    }
}

/// An executable DDL Statement.
#[async_trait]
pub trait Statement: Sized {
    /// Create a String DDL statement for the given SQL Dialect
    fn into_string(self, dialect: AnyKind) -> Result<String, sqlx::Error>;

    /// Execute the DDL statement
    /// NOTE/TODO: this should do something like conn: A: Acquire, but I couldn't get it to
    /// work with async_trait's lifetime bounds
    async fn execute<D: Dialect + Sync + Send>(self, conn: D) -> Result<(), sqlx::Error> {
        let statement = self.into_string(D::dialect())?;
        conn.execute_statement(statement.as_str()).await
    }
}

#[async_trait]
pub trait SystemStatement {
    async fn execute(self, uri: &str) -> Result<(), sqlx::Error>;
}

#[async_trait]
impl SystemStatement for db::CreateDatabase {
    /// Execute the DDL statement
    async fn execute(self, uri: &str) -> Result<(), sqlx::Error> {
        use sqlx::migrate::MigrateDatabase;
        Any::create_database(uri).await?;
        Ok(())
    }
}

#[async_trait]
impl SystemStatement for db::DropDatabase {
    /// Execute the DDL statement
    async fn execute(self, uri: &str) -> Result<(), sqlx::Error> {
        use sqlx::migrate::MigrateDatabase;
        if Any::database_exists(uri).await? {
            Any::drop_database(uri).await?;
        }
        return Ok(());
    }
}

impl Statement for table::CreateTable {
    fn into_string(self, dialect: AnyKind) -> Result<String, sqlx::Error> {
        let mut migration = Migration::new();
        if self.if_not_exists {
            migration.create_table_if_not_exists(self.name.clone(), move |table| {
                for (name, ty) in self.columns.clone() {
                    table.add_column(name, ty);
                }
            });
        } else {
            migration.create_table(self.name.clone(), move |table| {
                for (name, ty) in self.columns.clone() {
                    table.add_column(name, ty);
                }
            });
        }

        migration.into_string(dialect)
    }
}

impl Statement for Migration {
    fn into_string(self, dialect: AnyKind) -> Result<String, sqlx::Error> {
        let variant = match dialect {
            AnyKind::MySql => Some(barrel::backend::SqlVariant::Mysql),
            AnyKind::Sqlite => Some(barrel::backend::SqlVariant::Sqlite),
            #[allow(unreachable_patterns)]
            _ => None,
        };

        let variant = variant.map(Ok).unwrap_or_else(|| {
            Err(sqlx::Error::Configuration(Box::new(
                Error::UnsupportedDialect,
            )))
        })?;

        Ok(self.make_from(variant))
    }
}

//impl Latitude {
//    pub fn new<I: IntoIterator<Item = Transition>>(transitions: I) -> Self {
//        Self {
//            transitions: transitions.into_iter().collect(),
//        }
//    }
//
//    async fn _migrate(
//        self,
//        mut conn: AnyPool,
//        variant: barrel::backend::SqlVariant,
//    ) -> Result<(), sqlx::Error> {
//        let mut global = conn.begin().await?;
//
//        let mut transaction = global.begin().await?;
//
//        // Create internal table if not exists
//        let mut migration = Migration::new();
//        migration.drop_table(name)
//        migration.create_table_if_not_exists("_latitude_transitions", |table| {
//            table.add_column("id", types::primary());
//        });
//
//        let _done = sqlx::query::<Any>(migration.make_from(variant).as_str())
//            .execute(&mut transaction)
//            .await?;
//
//        // Apply each transition from max_id+1 onward
//        let max_id: Option<i64> = sqlx::query::<Any>("SELECT MAX(id) FROM _latitude_transitions")
//            .map(|row: AnyRow| row.try_get(0).unwrap())
//            .fetch_optional(&mut transaction)
//            .await
//            .unwrap();
//
//        //let ids: Vec<i64> = sqlx::query::<Any>("SELECT id FROM _latitude_transitions")
//        //    .map(|row: AnyRow| row.try_get(0).unwrap())
//        //    .fetch_all(&mut transaction)
//        //    .await
//        //    .unwrap();
//
//        // assert: SQL IDs start at 1
//        //println!("All IDs are {:?}", ids);
//        println!("Max ID was: {:?}", max_id);
//
//        let skip_from = match max_id {
//            // TODO, SQLITE returns MAX(id) = 0 when there are no rows;
//            // need to see if this is consistent (unlikely), and special case or
//            // refactor appropriately
//            Some(max) if max > 0 => max as usize,
//            _ => 0,
//        };
//
//        transaction.commit().await?;
//
//        for (id, transition) in self
//            .transitions
//            .into_iter()
//            .enumerate()
//            .map(|(i, v)| (i + 1, v))
//            .skip(skip_from)
//        {
//            let mut transaction = global.begin().await?;
//
//            // Apply the forward migration
//            sqlx::query::<Any>(transition.up.make_from(variant).as_str())
//                .execute(&mut transaction)
//                .await?;
//
//            // Preserve migration state
//            sqlx::query::<Any>("INSERT INTO _latitude_transitions(id) VALUES(?)")
//                .bind(id as i64)
//                .execute(&mut transaction)
//                .await?;
//
//            transaction.commit().await?;
//        }
//
//        //let table_count: i64 = sqlx::query::<Any>("SELECT COUNT(1) FROM _latitude_transitions")
//        //    .map(|row: AnyRow| row.try_get(0).unwrap())
//        //    .fetch_one(&mut global)
//        //    .await?;
//
//        global.commit().await?;
//
//        Ok(())
//    }
//
//    /// Migrate the latest transitions. This compares existing
//    /// database state to the runtime-defined migrations you supplied in
//    /// `Latitude::new`.
//    pub async fn migrate(mut self, uri: &str) -> Result<(), sqlx::Error> {
//        let variant = match AnyKind::from_str(uri).unwrap() {
//            AnyKind::MySql => barrel::backend::SqlVariant::Mysql,
//            AnyKind::Sqlite => barrel::backend::SqlVariant::Sqlite,
//            _ => panic!(),
//        };
//
//        let mut conn = AnyPool::connect(uri).await?;
//        self._migrate(conn, variant).await
//    }
//}

#[cfg(test)]
mod tests {

    //    #[tokio::test(threaded_scheduler)]
    //    async fn test_example_todos() {
    //        use crate::{table, Statement};
    //        use sqlx::AnyPool;
    //    }
}