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
use crate::migration::{Migration, Migrations};
use crate::sql_migration::{to_sql_migrations, SqlMigration};
use c3p0_common::error::C3p0Error;
use c3p0_common::json::builder::C3p0JsonBuilder;
use c3p0_common::json::codec::DefaultJsonCodec;
use c3p0_common::json::model::{Model, NewModel};
use c3p0_common::json::C3p0Json;
use c3p0_common::pool::{C3p0Pool, Connection};
use log::*;
use serde_derive::{Deserialize, Serialize};

mod md5;
pub mod migration;
mod sql_migration;

pub mod include_dir {
    pub use include_dir::*;
}

pub const C3P0_MIGRATE_TABLE_DEFAULT: &str = "C3P0_MIGRATE_SCHEMA_HISTORY";

#[derive(Clone, Debug)]
pub struct C3p0MigrateBuilder<C3P0: C3p0Pool> {
    table: String,
    schema: Option<String>,
    migrations: Vec<Migration>,
    c3p0: C3P0,
}

impl<C3P0: C3p0Pool> C3p0MigrateBuilder<C3P0> {
    pub fn new(c3p0: C3P0) -> Self {
        C3p0MigrateBuilder {
            table: C3P0_MIGRATE_TABLE_DEFAULT.to_owned(),
            schema: None,
            migrations: vec![],
            c3p0,
        }
    }

    pub fn with_schema_name<T: Into<Option<String>>>(
        mut self,
        schema_name: T,
    ) -> C3p0MigrateBuilder<C3P0> {
        self.schema = schema_name.into();
        self
    }

    pub fn with_table_name<T: Into<String>>(mut self, table_name: T) -> C3p0MigrateBuilder<C3P0> {
        self.table = table_name.into();
        self
    }

    pub fn with_migrations<M: Into<Migrations>>(
        mut self,
        migrations: M,
    ) -> C3p0MigrateBuilder<C3P0> {
        self.migrations = migrations.into().migrations;
        self
    }

    pub fn build(self) -> C3p0Migrate<C3P0> {
        C3p0Migrate {
            table: self.table,
            schema: self.schema,
            migrations: to_sql_migrations(self.migrations),
            c3p0: self.c3p0,
        }
    }
}

pub type MigrationModel = Model<MigrationData>;

#[derive(Clone, Serialize, Deserialize, PartialEq)]
pub struct MigrationData {
    pub migration_id: String,
    pub migration_type: MigrationType,
    pub md5_checksum: String,
    pub installed_on_epoch_ms: u64,
    pub execution_time_ms: u64,
    pub success: bool,
}

#[derive(Clone, Serialize, Deserialize, PartialEq)]
pub enum MigrationType {
    C3P0INIT,
    UP,
    DOWN,
}

#[derive(Clone)]
pub struct C3p0Migrate<C3P0: C3p0Pool> {
    table: String,
    schema: Option<String>,
    migrations: Vec<SqlMigration>,
    c3p0: C3P0,
}

const C3P0_INIT_MIGRATION_ID: &str = "C3P0_INIT_MIGRATION";

#[cfg(feature = "pg")]
impl C3p0Migrate<c3p0_pool_pg::C3p0PoolPg> {
    pub fn migrate(&self) -> Result<(), C3p0Error> {
        let c3p0_json = self.build_cp30_json();

        {
            let conn = self.c3p0.connection()?;
            if let Err(err) = c3p0_json.create_table_if_not_exists(&conn) {
                warn!("Create table process completed with error. This 'COULD' be fine if another process attempted the same operation concurrently. Err: {}", err);
            };
        }

        // Start Migration
        self.c3p0.transaction(|conn| {
            self.lock_table(&c3p0_json, conn)?;
            Ok(self.create_migration_zero(&c3p0_json, conn)?)
        })?;

        // Start Migration
        self.c3p0.transaction(|conn| {
            self.lock_first_migration_row(&c3p0_json, conn)?;
            Ok(self.start_migration(&c3p0_json, conn)?)
        })
    }

    pub fn get_migrations_history(
        &self,
        conn: &c3p0_pool_pg::PgConnection,
    ) -> Result<Vec<MigrationModel>, C3p0Error> {
        let c3p0_json = self.build_cp30_json();
        c3p0_json.fetch_all(conn)
    }

    fn lock_table(
        &self,
        c3p0_json: &c3p0_pool_pg::json::C3p0JsonPg<MigrationData, DefaultJsonCodec>,
        conn: &c3p0_pool_pg::PgConnection,
    ) -> Result<(), C3p0Error> {
        conn.batch_execute(&format!(
            "LOCK TABLE {} IN ACCESS EXCLUSIVE MODE",
            c3p0_json.queries().qualified_table_name
        ))
    }

    fn lock_first_migration_row(
        &self,
        c3p0_json: &c3p0_pool_pg::json::C3p0JsonPg<MigrationData, DefaultJsonCodec>,
        conn: &c3p0_pool_pg::PgConnection,
    ) -> Result<(), C3p0Error> {
        let lock_sql = format!(
            r#"select * from {} where {}->>'migration_id' = $1 FOR UPDATE"#,
            c3p0_json.queries().qualified_table_name,
            c3p0_json.queries().data_field_name
        );
        conn.fetch_one(&lock_sql, &[&C3P0_INIT_MIGRATION_ID], |_| Ok(()))
    }

    fn build_cp30_json(&self) -> c3p0_pool_pg::json::C3p0JsonPg<MigrationData, DefaultJsonCodec> {
        use c3p0_pool_pg::json::C3p0JsonBuilderPg;

        C3p0JsonBuilder::<c3p0_pool_pg::C3p0PoolPg>::new(self.table.clone())
            .with_schema_name(self.schema.clone())
            .build()
    }
}

#[cfg(feature = "mysql")]
impl C3p0Migrate<c3p0_pool_mysql::C3p0PoolMysql> {
    pub fn migrate(&self) -> Result<(), C3p0Error> {
        let c3p0_json = self.build_cp30_json();

        {
            let conn = self.c3p0.connection()?;
            if let Err(err) = c3p0_json.create_table_if_not_exists(&conn) {
                warn!("Create table process completed with error. This 'COULD' be fine if another process attempted the same operation concurrently. Err: {}", err);
            };
        }

        // Start Migration
        self.c3p0.transaction(|conn| {
            self.lock_table(&c3p0_json, conn)?;
            Ok(self.create_migration_zero(&c3p0_json, conn)?)
        })?;

        // Start Migration
        self.c3p0.transaction(|conn| {
            self.lock_first_migration_row(&c3p0_json, conn)?;
            Ok(self.start_migration(&c3p0_json, conn)?)
        })
    }

    pub fn get_migrations_history(
        &self,
        conn: &c3p0_pool_mysql::MysqlConnection,
    ) -> Result<Vec<MigrationModel>, C3p0Error> {
        let c3p0_json = self.build_cp30_json();
        c3p0_json.fetch_all(conn)
    }

    fn lock_table(
        &self,
        c3p0_json: &c3p0_pool_mysql::json::C3p0JsonMysql<MigrationData, DefaultJsonCodec>,
        conn: &c3p0_pool_mysql::MysqlConnection,
    ) -> Result<(), C3p0Error> {
        conn.batch_execute(&format!(
            "LOCK TABLES {} WRITE",
            c3p0_json.queries().qualified_table_name
        ))
    }

    fn lock_first_migration_row(
        &self,
        c3p0_json: &c3p0_pool_mysql::json::C3p0JsonMysql<MigrationData, DefaultJsonCodec>,
        conn: &c3p0_pool_mysql::MysqlConnection,
    ) -> Result<(), C3p0Error> {
        let lock_sql = format!(
            r#"select * from {} where JSON_EXTRACT({}, "$.migration_id") = ? FOR UPDATE"#,
            c3p0_json.queries().qualified_table_name,
            c3p0_json.queries().data_field_name
        );
        conn.fetch_one(&lock_sql, &[&C3P0_INIT_MIGRATION_ID], |_| Ok(()))
    }

    fn build_cp30_json(
        &self,
    ) -> c3p0_pool_mysql::json::C3p0JsonMysql<MigrationData, DefaultJsonCodec> {
        use c3p0_pool_mysql::json::C3p0JsonBuilderMysql;
        C3p0JsonBuilder::<c3p0_pool_mysql::C3p0PoolMysql>::new(self.table.clone())
            .with_schema_name(self.schema.clone())
            .build()
    }
}

#[cfg(feature = "sqlite")]
impl C3p0Migrate<c3p0_pool_sqlite::C3p0PoolSqlite> {
    pub fn migrate(&self) -> Result<(), C3p0Error> {
        let c3p0_json = self.build_cp30_json();

        {
            let conn = self.c3p0.connection()?;
            if let Err(err) = c3p0_json.create_table_if_not_exists(&conn) {
                warn!("Create table process completed with error. This 'COULD' be fine if another process attempted the same operation concurrently. Err: {}", err);
            };
        }

        // Start Migration
        self.c3p0
            .transaction(|conn| Ok(self.create_migration_zero(&c3p0_json, conn)?))?;

        // Start Migration
        self.c3p0.transaction(|conn| {
            self.lock_first_migration_row(&c3p0_json, conn)?;
            Ok(self.start_migration(&c3p0_json, conn)?)
        })
    }

    pub fn get_migrations_history(
        &self,
        conn: &c3p0_pool_sqlite::SqliteConnection,
    ) -> Result<Vec<MigrationModel>, C3p0Error> {
        let c3p0_json = self.build_cp30_json();
        c3p0_json.fetch_all(conn)
    }

    fn lock_first_migration_row(
        &self,
        c3p0_json: &c3p0_pool_sqlite::json::C3p0JsonSqlite<MigrationData, DefaultJsonCodec>,
        conn: &c3p0_pool_sqlite::SqliteConnection,
    ) -> Result<(), C3p0Error> {
        let lock_sql = format!(
            r#"select * from {} where JSON_EXTRACT({}, "$.migration_id") = ?"#,
            c3p0_json.queries().qualified_table_name,
            c3p0_json.queries().data_field_name
        );
        conn.fetch_one(&lock_sql, &[&C3P0_INIT_MIGRATION_ID], |_| Ok(()))
    }

    fn build_cp30_json(
        &self,
    ) -> c3p0_pool_sqlite::json::C3p0JsonSqlite<MigrationData, DefaultJsonCodec> {
        use c3p0_pool_sqlite::json::C3p0JsonBuilderSqlite;
        C3p0JsonBuilder::<c3p0_pool_sqlite::C3p0PoolSqlite>::new(self.table.clone())
            .with_schema_name(self.schema.clone())
            .build()
    }
}

impl<C3P0: C3p0Pool> C3p0Migrate<C3P0> {
    fn create_migration_zero<C3P0JSON: C3p0Json<MigrationData, DefaultJsonCodec>>(
        &self,
        c3p0_json: &C3P0JSON,
        conn: &C3P0JSON::CONNECTION,
    ) -> Result<(), C3p0Error> {
        let count = c3p0_json.count_all(&conn)?;

        if count == 0 {
            let migration_zero = MigrationData {
                md5_checksum: "".to_owned(),
                migration_id: C3P0_INIT_MIGRATION_ID.to_owned(),
                migration_type: MigrationType::C3P0INIT,
                execution_time_ms: 0,
                installed_on_epoch_ms: 0,
                success: true,
            };
            c3p0_json.save(&conn, migration_zero.into())?;
        };

        Ok(())
    }

    fn start_migration<C3P0JSON: C3p0Json<MigrationData, DefaultJsonCodec>>(
        &self,
        c3p0_json: &C3P0JSON,
        conn: &C3P0JSON::CONNECTION,
    ) -> Result<(), C3p0Error> {
        let migration_history = self.fetch_migrations_history(c3p0_json, conn)?;
        let migration_history = self.clean_history(migration_history)?;

        for i in 0..self.migrations.len() {
            let migration = &self.migrations[i];

            if migration_history.len() > i {
                let applied_migration = &migration_history[i];

                if applied_migration.data.migration_id.eq(&migration.id) {
                    if applied_migration.data.md5_checksum.eq(&migration.up.md5) {
                        continue;
                    }
                    return Err(C3p0Error::AlteredMigrationSql {
                        message: format!(
                            "Wrong checksum for migration [{}]. Expected [{}], found [{}].",
                            applied_migration.data.migration_id,
                            applied_migration.data.md5_checksum,
                            migration.up.md5
                        ),
                    });
                }
                return Err(C3p0Error::WrongMigrationSet {
                    message: format!(
                        "Wrong migration set! Expected migration [{}], found [{}].",
                        applied_migration.data.migration_id, migration.id
                    ),
                });
            }

            conn.batch_execute(&migration.up.sql)?;

            c3p0_json.save(
                conn,
                NewModel::new(MigrationData {
                    success: true,
                    md5_checksum: migration.up.md5.clone(),
                    migration_id: migration.id.clone(),
                    migration_type: MigrationType::UP,
                    execution_time_ms: 0,
                    installed_on_epoch_ms: 0,
                }),
            )?;
        }

        Ok(())
    }

    fn fetch_migrations_history<C3P0JSON: C3p0Json<MigrationData, DefaultJsonCodec>>(
        &self,
        c3p0_json: &C3P0JSON,
        conn: &C3P0JSON::CONNECTION,
    ) -> Result<Vec<MigrationModel>, C3p0Error> {
        c3p0_json.fetch_all(conn)
    }

    fn clean_history(
        &self,
        migrations: Vec<MigrationModel>,
    ) -> Result<Vec<MigrationModel>, C3p0Error> {
        let mut result = vec![];

        for migration in migrations {
            match migration.data.migration_type {
                MigrationType::UP => {
                    result.push(migration);
                }
                MigrationType::DOWN => {
                    let last = result.remove(result.len() - 1);
                    if !migration.data.migration_id.eq(&last.data.migration_id)
                        || !last.data.migration_type.eq(&MigrationType::UP)
                    {
                        return Err(C3p0Error::CorruptedDbMigrationState {
                            message: "Migration history is not valid!!".to_owned(),
                        });
                    }
                }
                MigrationType::C3P0INIT => {}
            }
        }

        Ok(result)
    }
}