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
//! Module for creating and running cli with help of migrator
//!
//! CLI Command can directly used or extended
//!
//! For direct usage you can run `parse_and_run` function for `MigrationCommand`
//!
//! OR
//!
//! If you want to extend your own clap based cli then you can add migrator to
//! sub command enum and then run migrator
//! ```rust,no_run
//! #[derive(clap::Parser)]
//! struct Cli {
//!     #[command(subcommand)]
//!     sub_command: CliSubcommand,
//! }
//!
//! #[derive(clap::Subcommand)]
//! enum CliSubcommand {
//!     #[command()]
//!     Migrator(sqlx_migrator::cli::MigrationCommand),
//! }
//! ```
use std::io::Write;
use std::ops::Not;

use clap::{Parser, Subcommand};

use crate::error::Error;
use crate::migrator::{Migrate, Plan};

/// Migration command for performing rust based sqlx migrations
#[derive(Parser, Debug)]
pub struct MigrationCommand {
    #[command(subcommand)]
    sub_command: SubCommand,
}

impl MigrationCommand {
    /// Parse `MigrationCommand` and run migration command line interface
    ///
    /// # Errors
    /// If migration command fails to complete and raise some issue
    pub async fn parse_and_run<DB, State>(
        migrator: Box<dyn Migrate<DB, State>>,
        connection: &mut <DB as sqlx::Database>::Connection,
    ) -> Result<(), Error>
    where
        DB: sqlx::Database,
        State: Send + Sync,
    {
        let migration_command = Self::parse();
        migration_command.run(migrator, connection).await
    }

    /// Run migration command line interface
    ///
    /// # Errors
    /// If migration command fails to complete and raise some issue
    pub async fn run<DB, State>(
        &self,
        migrator: Box<dyn Migrate<DB, State>>,
        connection: &mut <DB as sqlx::Database>::Connection,
    ) -> Result<(), Error>
    where
        DB: sqlx::Database,
        State: Send + Sync,
    {
        self.sub_command
            .handle_subcommand(migrator, connection)
            .await?;
        Ok(())
    }
}

#[derive(Subcommand, Debug)]
enum SubCommand {
    /// Apply migrations
    #[command()]
    Apply(Apply),
    /// Drop migration information table. Needs all migrations to be
    /// reverted else raises error
    #[command()]
    Drop,
    /// List migrations along with their status and time applied if migrations
    /// is already applied
    #[command()]
    List,
    /// Revert migrations
    #[command()]
    Revert(Revert),
}

impl SubCommand {
    async fn handle_subcommand<DB, State>(
        &self,
        migrator: Box<dyn Migrate<DB, State>>,
        connection: &mut <DB as sqlx::Database>::Connection,
    ) -> Result<(), Error>
    where
        DB: sqlx::Database,
        State: Send + Sync,
    {
        match self {
            SubCommand::Apply(apply) => apply.run(migrator, connection).await?,
            SubCommand::Drop => drop_migrations(migrator, connection).await?,
            SubCommand::List => list_migrations(migrator, connection).await?,
            SubCommand::Revert(revert) => revert.run(migrator, connection).await?,
        }
        Ok(())
    }
}

async fn drop_migrations<DB, State>(
    migrator: Box<dyn Migrate<DB, State>>,
    connection: &mut <DB as sqlx::Database>::Connection,
) -> Result<(), Error>
where
    DB: sqlx::Database,
{
    migrator.ensure_migration_table_exists(connection).await?;
    if migrator
        .fetch_applied_migration_from_db(connection)
        .await?
        .is_empty()
        .not()
    {
        return Err(Error::AppliedMigrationExists);
    }
    migrator.drop_migration_table_if_exists(connection).await?;
    println!("Dropped migrations table");
    Ok(())
}

async fn list_migrations<DB, State>(
    migrator: Box<dyn Migrate<DB, State>>,
    connection: &mut <DB as sqlx::Database>::Connection,
) -> Result<(), Error>
where
    DB: sqlx::Database,
    State: Send + Sync,
{
    let migration_plan = migrator.generate_migration_plan(None, connection).await?;

    if !migration_plan.is_empty() {
        let applied_migrations = migrator.fetch_applied_migration_from_db(connection).await?;
        let apply_plan = migrator
            .generate_migration_plan(Some(&Plan::apply_all()), connection)
            .await?;

        let widths = [5, 10, 50, 10, 40];
        let full_width = widths.iter().sum::<usize>() + widths.len() * 3;

        let first_width = widths[0];
        let second_width = widths[1];
        let third_width = widths[2];
        let fourth_width = widths[3];
        let fifth_width = widths[4];

        println!(
            "{:^first_width$} | {:^second_width$} | {:^third_width$} | {:^fourth_width$} | \
             {:^fifth_width$}",
            "ID", "App", "Name", "Status", "Applied time"
        );

        println!("{:^full_width$}", "-".repeat(full_width));
        for migration in migration_plan {
            let mut id = String::from("N/A");
            let mut status = "\u{2717}";
            let mut applied_time = String::from("N/A");

            let find_applied_migrations = applied_migrations
                .iter()
                .find(|&applied_migration| applied_migration == migration);

            if let Some(sqlx_migration) = find_applied_migrations {
                id = sqlx_migration.id().to_string();
                status = "\u{2713}";
                applied_time = sqlx_migration.applied_time().to_string();
            } else if !apply_plan
                .iter()
                .any(|&plan_migration| plan_migration == migration)
            {
                status = "\u{2194}";
            }

            println!(
                "{:^first_width$} | {:^second_width$} | {:^third_width$} | {:^fourth_width$} | \
                 {:^fifth_width$}",
                id,
                migration.app(),
                migration.name(),
                status,
                applied_time
            );
        }
    }
    Ok(())
}

#[derive(Parser, Debug)]
#[allow(clippy::struct_excessive_bools)]
struct Apply {
    /// App name up to which migration needs to be applied. If migration option
    /// is also present than only till migration is applied
    #[arg(long)]
    app: Option<String>,
    /// Check for pending migration
    #[arg(long)]
    check: bool,
    /// Number of migration to apply. Conflicts with app args
    #[arg(long, conflicts_with = "app")]
    count: Option<usize>,
    /// Make migration applied without running migration operations
    #[arg(long)]
    fake: bool,
    /// Force run apply operation without asking question if migration is
    /// destructible
    #[arg(long)]
    force: bool,
    /// Apply migration till provided migration. Requires app options to be
    /// present
    #[arg(long, requires = "app")]
    migration: Option<String>,
    /// Show plan
    #[arg(long)]
    plan: bool,
}
impl Apply {
    async fn run<DB, State>(
        &self,
        migrator: Box<dyn Migrate<DB, State>>,
        connection: &mut <DB as sqlx::Database>::Connection,
    ) -> Result<(), Error>
    where
        DB: sqlx::Database,
        State: Send + Sync,
    {
        let plan;
        if let Some(count) = self.count {
            plan = Plan::apply_count(count);
        } else if let Some(app) = &self.app {
            plan = Plan::apply_name(app, &self.migration);
        } else {
            plan = Plan::apply_all();
        };
        let migrations = migrator
            .generate_migration_plan(Some(&plan), connection)
            .await?;
        if self.check && !migrations.is_empty() {
            return Err(Error::PendingMigrationPresent);
        }
        if self.plan {
            if migrations.is_empty() {
                println!("No migration exists for applying");
            } else {
                let first_width = 10;
                let second_width = 50;
                let full_width = first_width + second_width + 3;
                println!("{:^first_width$} | {:^second_width$}", "App", "Name");
                println!("{:^full_width$}", "-".repeat(full_width));
                for migration in migrations {
                    println!(
                        "{:^first_width$} | {:^second_width$}",
                        migration.app(),
                        migration.name(),
                    );
                }
            }
        } else if self.fake {
            for migration in migrations {
                migrator
                    .add_migration_to_db_table(migration, connection)
                    .await?;
            }
        } else {
            let destructible_migrations = migrations
                .iter()
                .filter(|m| m.operations().iter().any(|o| o.is_destructible()))
                .collect::<Vec<_>>();
            if !self.force && !destructible_migrations.is_empty() {
                let mut input = String::new();
                println!(
                    "Do you want to apply destructible migrations {} (y/N)",
                    destructible_migrations.len()
                );
                for (position, migration) in destructible_migrations.iter().enumerate() {
                    println!("{position}. {} : {}", migration.app(), migration.name());
                }
                std::io::stdout().flush()?;
                std::io::stdin().read_line(&mut input)?;
                let input_trimmed = input.trim().to_ascii_lowercase();
                // If answer is not y or yes then return
                if !["y", "yes"].contains(&input_trimmed.as_str()) {
                    return Ok(());
                }
            }
            migrator.run(connection, &plan).await?;
            println!("Successfully applied migrations according to plan");
        }
        Ok(())
    }
}

#[derive(Parser, Debug)]
#[allow(clippy::struct_excessive_bools)]
struct Revert {
    /// Revert all migration. Conflicts with app args
    #[arg(long, conflicts_with = "app")]
    all: bool,
    /// Revert migration till app migrations is reverted. If it is present
    /// alongside migration options than only till migration is reverted
    #[arg(long)]
    app: Option<String>,
    /// Number of migration to revert. Conflicts with all and app args
    #[arg(long, conflicts_with_all = ["all", "app"])]
    count: Option<usize>,
    /// Make migration reverted without running revert operation
    #[arg(long)]
    fake: bool,
    /// Force run revert operation without asking question
    #[arg(long)]
    force: bool,
    /// Revert migration till provided migration. Requires app options to be
    /// present
    #[arg(long, requires = "app")]
    migration: Option<String>,
    /// Show plan
    #[arg(long)]
    plan: bool,
}
impl Revert {
    async fn run<DB, State>(
        &self,
        migrator: Box<dyn Migrate<DB, State>>,
        connection: &mut <DB as sqlx::Database>::Connection,
    ) -> Result<(), Error>
    where
        DB: sqlx::Database,
        State: Send + Sync,
    {
        let plan;
        if let Some(count) = self.count {
            plan = Plan::revert_count(count);
        } else if let Some(app) = &self.app {
            plan = Plan::revert_name(app, &self.migration);
        } else if self.all {
            plan = Plan::revert_all();
        } else {
            plan = Plan::revert_count(1);
        };
        let revert_migrations = migrator
            .generate_migration_plan(Some(&plan), connection)
            .await?;

        if self.plan {
            if revert_migrations.is_empty() {
                println!("No migration exists for reverting");
            } else {
                let first_width = 10;
                let second_width = 50;
                let full_width = first_width + second_width + 3;
                println!("{:^first_width$} | {:^second_width$}", "App", "Name");
                println!("{:^full_width$}", "-".repeat(full_width));
                for migration in revert_migrations {
                    println!(
                        "{:^first_width$} | {:^second_width$}",
                        migration.app(),
                        migration.name(),
                    );
                }
            }
        } else if self.fake {
            for migration in revert_migrations {
                migrator
                    .delete_migration_from_db_table(migration, connection)
                    .await?;
            }
        } else {
            if !self.force && !revert_migrations.is_empty() {
                let mut input = String::new();
                println!(
                    "Do you want to revert {} migrations (y/N)",
                    revert_migrations.len()
                );
                for (position, migration) in revert_migrations.iter().enumerate() {
                    println!("{position}. {} : {}", migration.app(), migration.name());
                }
                std::io::stdout().flush()?;
                std::io::stdin().read_line(&mut input)?;
                let input_trimmed = input.trim().to_ascii_lowercase();
                // If answer is not y or yes then return
                if !["y", "yes"].contains(&input_trimmed.as_str()) {
                    return Ok(());
                }
            }
            migrator.run(connection, &plan).await?;
            println!("Successfully reverted migrations according to plan");
        }
        Ok(())
    }
}