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
use clap::{ArgGroup, Parser, Subcommand, ValueEnum};
#[cfg(feature = "codegen")]
use dotenvy::dotenv;

#[cfg(feature = "codegen")]
use crate::{handle_error, run_generate_command, run_migrate_command};

#[derive(Parser, Debug)]
#[command(
    version,
    author,
    help_template = r#"{before-help}{name} {version}
{about-with-newline}

{usage-heading} {usage}

{all-args}{after-help}

AUTHORS:
    {author}
"#,
    about = r#"
   ____                 ___   ____   __  __        /\
  / ___|   ___   __ _  / _ \ |  _ \ |  \/  |      {.-}
  \___ \  / _ \ / _` || | | || |_) || |\/| |     ;_.-'\
   ___) ||  __/| (_| || |_| ||  _ < | |  | |    {    _.}_
  |____/  \___| \__,_| \___/ |_| \_\|_|  |_|     \.-' /  `,
                                                  \  |    /
  An async & dynamic ORM for Rust                  \ |  ,/
  ===============================                   \|_/

  Getting Started
    - Documentation: https://www.sea-ql.org/SeaORM
    - Tutorial: https://www.sea-ql.org/sea-orm-tutorial
    - Examples: https://github.com/SeaQL/sea-orm/tree/master/examples
    - Cookbook: https://www.sea-ql.org/sea-orm-cookbook

  Join our Discord server to chat with others in the SeaQL community!
    - Invitation: https://discord.com/invite/uCPdDXzbdv

  SeaQL Community Survey 2024
    - Link: https://sea-ql.org/community-survey

  If you like what we do, consider starring, sharing and contributing!
"#
)]
pub struct Cli {
    #[arg(global = true, short, long, help = "Show debug messages")]
    pub verbose: bool,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, PartialEq, Eq, Debug)]
pub enum Commands {
    #[command(
        about = "Codegen related commands",
        arg_required_else_help = true,
        display_order = 10
    )]
    Generate {
        #[command(subcommand)]
        command: GenerateSubcommands,
    },
    #[command(about = "Migration related commands", display_order = 20)]
    Migrate {
        #[arg(
            global = true,
            short = 'd',
            long,
            help = "Migration script directory.
If your migrations are in their own crate,
you can provide the root of that crate.
If your migrations are in a submodule of your app,
you should provide the directory of that submodule.",
            default_value = "./migration"
        )]
        migration_dir: String,

        #[arg(
            global = true,
            short = 's',
            long,
            env = "DATABASE_SCHEMA",
            long_help = "Database schema\n \
                        - For MySQL and SQLite, this argument is ignored.\n \
                        - For PostgreSQL, this argument is optional with default value 'public'.\n"
        )]
        database_schema: Option<String>,

        #[arg(
            global = true,
            short = 'u',
            long,
            env = "DATABASE_URL",
            help = "Database URL"
        )]
        database_url: Option<String>,

        #[command(subcommand)]
        command: Option<MigrateSubcommands>,
    },
}

#[derive(Subcommand, PartialEq, Eq, Debug)]
pub enum MigrateSubcommands {
    #[command(about = "Initialize migration directory", display_order = 10)]
    Init,
    #[command(about = "Generate a new, empty migration", display_order = 20)]
    Generate {
        #[arg(required = true, help = "Name of the new migration")]
        migration_name: String,

        #[arg(
            long,
            default_value = "true",
            help = "Generate migration file based on Utc time",
            conflicts_with = "local_time",
            display_order = 1001
        )]
        universal_time: bool,

        #[arg(
            long,
            help = "Generate migration file based on Local time",
            conflicts_with = "universal_time",
            display_order = 1002
        )]
        local_time: bool,
    },
    #[command(
        about = "Drop all tables from the database, then reapply all migrations",
        display_order = 30
    )]
    Fresh,
    #[command(
        about = "Rollback all applied migrations, then reapply all migrations",
        display_order = 40
    )]
    Refresh,
    #[command(about = "Rollback all applied migrations", display_order = 50)]
    Reset,
    #[command(about = "Check the status of all migrations", display_order = 60)]
    Status,
    #[command(about = "Apply pending migrations", display_order = 70)]
    Up {
        #[arg(short, long, help = "Number of pending migrations to apply")]
        num: Option<u32>,
    },
    #[command(about = "Rollback applied migrations", display_order = 80)]
    Down {
        #[arg(
            short,
            long,
            default_value = "1",
            help = "Number of applied migrations to be rolled back",
            display_order = 90
        )]
        num: u32,
    },
}

#[derive(Subcommand, PartialEq, Eq, Debug)]
pub enum GenerateSubcommands {
    #[command(about = "Generate entity")]
    #[command(group(ArgGroup::new("formats").args(&["compact_format", "expanded_format"])))]
    #[command(group(ArgGroup::new("group-tables").args(&["tables", "include_hidden_tables"])))]
    Entity {
        #[arg(long, help = "Generate entity file of compact format")]
        compact_format: bool,

        #[arg(long, help = "Generate entity file of expanded format")]
        expanded_format: bool,

        #[arg(
            long,
            help = "Generate entity file for hidden tables (i.e. table name starts with an underscore)"
        )]
        include_hidden_tables: bool,

        #[arg(
            short = 't',
            long,
            value_delimiter = ',',
            help = "Generate entity file for specified tables only (comma separated)"
        )]
        tables: Vec<String>,

        #[arg(
            long,
            value_delimiter = ',',
            default_value = "seaql_migrations",
            help = "Skip generating entity file for specified tables (comma separated)"
        )]
        ignore_tables: Vec<String>,

        #[arg(
            long,
            default_value = "1",
            help = "The maximum amount of connections to use when connecting to the database."
        )]
        max_connections: u32,

        #[arg(
            short = 'o',
            long,
            default_value = "./",
            help = "Entity file output directory"
        )]
        output_dir: String,

        #[arg(
            short = 's',
            long,
            env = "DATABASE_SCHEMA",
            default_value = "public",
            long_help = "Database schema\n \
                        - For MySQL, this argument is ignored.\n \
                        - For PostgreSQL, this argument is optional with default value 'public'."
        )]
        database_schema: String,

        #[arg(short = 'u', long, env = "DATABASE_URL", help = "Database URL")]
        database_url: String,

        #[arg(
            long,
            default_value = "none",
            help = "Automatically derive serde Serialize / Deserialize traits for the entity (none, \
                serialize, deserialize, both)"
        )]
        with_serde: String,

        #[arg(
            long,
            help = "Generate a serde field attribute, '#[serde(skip_deserializing)]', for the primary key fields to skip them during deserialization, this flag will be affective only when '--with-serde' is 'both' or 'deserialize'"
        )]
        serde_skip_deserializing_primary_key: bool,

        #[arg(
            long,
            default_value = "false",
            help = "Opt-in to add skip attributes to hidden columns (i.e. when 'with-serde' enabled and column name starts with an underscore)"
        )]
        serde_skip_hidden_column: bool,

        #[arg(
            long,
            default_value = "false",
            long_help = "Automatically derive the Copy trait on generated enums.\n\
            Enums generated from a database don't have associated data by default, and as such can \
            derive Copy.
            "
        )]
        with_copy_enums: bool,

        #[arg(
            long,
            default_value_t,
            value_enum,
            help = "The datetime crate to use for generating entities."
        )]
        date_time_crate: DateTimeCrate,

        #[arg(
            long,
            short = 'l',
            default_value = "false",
            help = "Generate index file as `lib.rs` instead of `mod.rs`."
        )]
        lib: bool,

        #[arg(
            long,
            value_delimiter = ',',
            help = "Add extra derive macros to generated model struct (comma separated), e.g. `--model-extra-derives 'ts_rs::Ts','CustomDerive'`"
        )]
        model_extra_derives: Vec<String>,

        #[arg(
            long,
            value_delimiter = ',',
            help = r#"Add extra attributes to generated model struct, no need for `#[]` (comma separated), e.g. `--model-extra-attributes 'serde(rename_all = "camelCase")','ts(export)'`"#
        )]
        model_extra_attributes: Vec<String>,

        #[arg(
            long,
            value_delimiter = ',',
            help = "Add extra derive macros to generated enums (comma separated), e.g. `--enum-extra-derives 'ts_rs::Ts','CustomDerive'`"
        )]
        enum_extra_derives: Vec<String>,

        #[arg(
            long,
            value_delimiter = ',',
            help = r#"Add extra attributes to generated enums, no need for `#[]` (comma separated), e.g. `--enum-extra-attributes 'serde(rename_all = "camelCase")','ts(export)'`"#
        )]
        enum_extra_attributes: Vec<String>,

        #[arg(
            long,
            default_value = "false",
            long_help = "Generate helper Enumerations that are used by Seaography."
        )]
        seaography: bool,
    },
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum, Default)]
pub enum DateTimeCrate {
    #[default]
    Chrono,
    Time,
}

/// Use this to build a local, version-controlled `sea-orm-cli` in dependent projects
/// (see [example use case](https://github.com/SeaQL/sea-orm/discussions/1889)).
#[cfg(feature = "codegen")]
pub async fn main() {
    dotenv().ok();

    let cli = Cli::parse();
    let verbose = cli.verbose;

    match cli.command {
        Commands::Generate { command } => {
            run_generate_command(command, verbose)
                .await
                .unwrap_or_else(handle_error);
        }
        Commands::Migrate {
            migration_dir,
            database_schema,
            database_url,
            command,
        } => run_migrate_command(
            command,
            &migration_dir,
            database_schema,
            database_url,
            verbose,
        )
        .unwrap_or_else(handle_error),
    }
}