sea_orm_cli/
cli.rs

1use clap::{ArgAction, ArgGroup, Parser, Subcommand, ValueEnum};
2#[cfg(feature = "codegen")]
3use dotenvy::dotenv;
4
5#[cfg(feature = "codegen")]
6use crate::{handle_error, run_generate_command, run_migrate_command};
7
8#[derive(Parser, Debug)]
9#[command(
10    version,
11    author,
12    help_template = r#"{before-help}{name} {version}
13{about-with-newline}
14
15{usage-heading} {usage}
16
17{all-args}{after-help}
18
19AUTHORS:
20    {author}
21"#,
22    about = r#"
23   ____                 ___   ____   __  __        /\
24  / ___|   ___   __ _  / _ \ |  _ \ |  \/  |      {.-}
25  \___ \  / _ \ / _` || | | || |_) || |\/| |     ;_.-'\
26   ___) ||  __/| (_| || |_| ||  _ < | |  | |    {    _.}_
27  |____/  \___| \__,_| \___/ |_| \_\|_|  |_|     \.-' /  `,
28                                                  \  |    /
29  An async & dynamic ORM for Rust                  \ |  ,/
30  ===============================                   \|_/
31
32  Getting Started
33    - Documentation: https://www.sea-ql.org/SeaORM
34    - Tutorial: https://www.sea-ql.org/sea-orm-tutorial
35    - Examples: https://github.com/SeaQL/sea-orm/tree/master/examples
36    - Cookbook: https://www.sea-ql.org/sea-orm-cookbook
37
38  Join our Discord server to chat with others in the SeaQL community!
39    - Invitation: https://discord.com/invite/uCPdDXzbdv
40
41  SeaQL Community Survey 2024
42    - Link: https://sea-ql.org/community-survey
43
44  If you like what we do, consider starring, sharing and contributing!
45"#
46)]
47pub struct Cli {
48    #[arg(global = true, short, long, help = "Show debug messages")]
49    pub verbose: bool,
50
51    #[command(subcommand)]
52    pub command: Commands,
53}
54
55#[derive(Subcommand, PartialEq, Eq, Debug)]
56pub enum Commands {
57    #[command(
58        about = "Codegen related commands",
59        arg_required_else_help = true,
60        display_order = 10
61    )]
62    Generate {
63        #[command(subcommand)]
64        command: GenerateSubcommands,
65    },
66    #[command(about = "Migration related commands", display_order = 20)]
67    Migrate {
68        #[arg(
69            global = true,
70            short = 'd',
71            long,
72            env = "MIGRATION_DIR",
73            help = "Migration script directory.
74If your migrations are in their own crate,
75you can provide the root of that crate.
76If your migrations are in a submodule of your app,
77you should provide the directory of that submodule.",
78            default_value = "./migration"
79        )]
80        migration_dir: String,
81
82        #[arg(
83            global = true,
84            short = 's',
85            long,
86            env = "DATABASE_SCHEMA",
87            long_help = "Database schema\n \
88                        - For MySQL and SQLite, this argument is ignored.\n \
89                        - For PostgreSQL, this argument is optional with default value 'public'.\n"
90        )]
91        database_schema: Option<String>,
92
93        #[arg(
94            global = true,
95            short = 'u',
96            long,
97            env = "DATABASE_URL",
98            help = "Database URL"
99        )]
100        database_url: Option<String>,
101
102        #[command(subcommand)]
103        command: Option<MigrateSubcommands>,
104    },
105}
106
107#[derive(Subcommand, PartialEq, Eq, Debug)]
108pub enum MigrateSubcommands {
109    #[command(about = "Initialize migration directory", display_order = 10)]
110    Init,
111    #[command(about = "Generate a new, empty migration", display_order = 20)]
112    Generate {
113        #[arg(required = true, help = "Name of the new migration")]
114        migration_name: String,
115
116        #[arg(
117            long,
118            default_value = "true",
119            help = "Generate migration file based on Utc time",
120            conflicts_with = "local_time",
121            display_order = 1001
122        )]
123        universal_time: bool,
124
125        #[arg(
126            long,
127            help = "Generate migration file based on Local time",
128            conflicts_with = "universal_time",
129            display_order = 1002
130        )]
131        local_time: bool,
132    },
133    #[command(
134        about = "Drop all tables from the database, then reapply all migrations",
135        display_order = 30
136    )]
137    Fresh,
138    #[command(
139        about = "Rollback all applied migrations, then reapply all migrations",
140        display_order = 40
141    )]
142    Refresh,
143    #[command(about = "Rollback all applied migrations", display_order = 50)]
144    Reset,
145    #[command(about = "Check the status of all migrations", display_order = 60)]
146    Status,
147    #[command(about = "Apply pending migrations", display_order = 70)]
148    Up {
149        #[arg(short, long, help = "Number of pending migrations to apply")]
150        num: Option<u32>,
151    },
152    #[command(about = "Rollback applied migrations", display_order = 80)]
153    Down {
154        #[arg(
155            short,
156            long,
157            default_value = "1",
158            help = "Number of applied migrations to be rolled back",
159            display_order = 90
160        )]
161        num: u32,
162    },
163}
164
165#[derive(Subcommand, PartialEq, Eq, Debug)]
166pub enum GenerateSubcommands {
167    #[command(about = "Generate entity")]
168    #[command(group(ArgGroup::new("formats").args(&["compact_format", "expanded_format", "frontend_format"])))]
169    #[command(group(ArgGroup::new("group-tables").args(&["tables", "include_hidden_tables"])))]
170    Entity {
171        #[arg(long, help = "Generate entity file of compact format")]
172        compact_format: bool,
173
174        #[arg(long, help = "Generate entity file of expanded format")]
175        expanded_format: bool,
176
177        #[arg(long, help = "Generate entity file of frontend format")]
178        frontend_format: bool,
179
180        #[arg(
181            long,
182            help = "Generate entity file for hidden tables (i.e. table name starts with an underscore)"
183        )]
184        include_hidden_tables: bool,
185
186        #[arg(
187            short = 't',
188            long,
189            value_delimiter = ',',
190            help = "Generate entity file for specified tables only (comma separated)"
191        )]
192        tables: Vec<String>,
193
194        #[arg(
195            long,
196            value_delimiter = ',',
197            default_value = "seaql_migrations",
198            help = "Skip generating entity file for specified tables (comma separated)"
199        )]
200        ignore_tables: Vec<String>,
201
202        #[arg(
203            long,
204            default_value = "1",
205            help = "The maximum amount of connections to use when connecting to the database."
206        )]
207        max_connections: u32,
208
209        #[arg(
210            long,
211            default_value = "30",
212            long_help = "Acquire timeout in seconds of the connection used for schema discovery"
213        )]
214        acquire_timeout: u64,
215
216        #[arg(
217            short = 'o',
218            long,
219            default_value = "./",
220            help = "Entity file output directory"
221        )]
222        output_dir: String,
223
224        #[arg(
225            short = 's',
226            long,
227            env = "DATABASE_SCHEMA",
228            long_help = "Database schema\n \
229                        - For MySQL, this argument is ignored.\n \
230                        - For PostgreSQL, this argument is optional with default value 'public'."
231        )]
232        database_schema: Option<String>,
233
234        #[arg(short = 'u', long, env = "DATABASE_URL", help = "Database URL")]
235        database_url: String,
236
237        #[arg(
238            long,
239            default_value = "all",
240            help = "Generate prelude.rs file (all, none, all-allow-unused-imports)"
241        )]
242        with_prelude: String,
243
244        #[arg(
245            long,
246            default_value = "none",
247            help = "Automatically derive serde Serialize / Deserialize traits for the entity (none, \
248                serialize, deserialize, both)"
249        )]
250        with_serde: String,
251
252        #[arg(
253            long,
254            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'"
255        )]
256        serde_skip_deserializing_primary_key: bool,
257
258        #[arg(
259            long,
260            default_value = "false",
261            help = "Opt-in to add skip attributes to hidden columns (i.e. when 'with-serde' enabled and column name starts with an underscore)"
262        )]
263        serde_skip_hidden_column: bool,
264
265        #[arg(
266            long,
267            default_value = "false",
268            long_help = "Automatically derive the Copy trait on generated enums.\n\
269            Enums generated from a database don't have associated data by default, and as such can \
270            derive Copy.
271            "
272        )]
273        with_copy_enums: bool,
274
275        #[arg(
276            long,
277            default_value_t,
278            value_enum,
279            help = "The datetime crate to use for generating entities."
280        )]
281        date_time_crate: DateTimeCrate,
282
283        #[arg(
284            long,
285            short = 'l',
286            default_value = "false",
287            help = "Generate index file as `lib.rs` instead of `mod.rs`."
288        )]
289        lib: bool,
290
291        #[arg(
292            long,
293            value_delimiter = ',',
294            help = "Add extra derive macros to generated model struct (comma separated), e.g. `--model-extra-derives 'ts_rs::Ts','CustomDerive'`"
295        )]
296        model_extra_derives: Vec<String>,
297
298        #[arg(
299            long,
300            value_delimiter = ',',
301            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)'`"#
302        )]
303        model_extra_attributes: Vec<String>,
304
305        #[arg(
306            long,
307            value_delimiter = ',',
308            help = "Add extra derive macros to generated enums (comma separated), e.g. `--enum-extra-derives 'ts_rs::Ts','CustomDerive'`"
309        )]
310        enum_extra_derives: Vec<String>,
311
312        #[arg(
313            long,
314            value_delimiter = ',',
315            help = r#"Add extra attributes to generated enums, no need for `#[]` (comma separated), e.g. `--enum-extra-attributes 'serde(rename_all = "camelCase")','ts(export)'`"#
316        )]
317        enum_extra_attributes: Vec<String>,
318
319        #[arg(
320            long,
321            default_value = "false",
322            long_help = "Generate helper Enumerations that are used by Seaography."
323        )]
324        seaography: bool,
325
326        #[arg(
327            long,
328            default_value = "true",
329            default_missing_value = "true",
330            num_args = 0..=1,
331            require_equals = true,
332            action = ArgAction::Set,
333            long_help = "Generate empty ActiveModelBehavior impls."
334        )]
335        impl_active_model_behavior: bool,
336    },
337}
338
339#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum, Default)]
340pub enum DateTimeCrate {
341    #[default]
342    Chrono,
343    Time,
344}
345
346/// Use this to build a local, version-controlled `sea-orm-cli` in dependent projects
347/// (see [example use case](https://github.com/SeaQL/sea-orm/discussions/1889)).
348#[cfg(feature = "codegen")]
349pub async fn main() {
350    dotenv().ok();
351
352    let cli = Cli::parse();
353    let verbose = cli.verbose;
354
355    match cli.command {
356        Commands::Generate { command } => {
357            run_generate_command(command, verbose)
358                .await
359                .unwrap_or_else(handle_error);
360        }
361        Commands::Migrate {
362            migration_dir,
363            database_schema,
364            database_url,
365            command,
366        } => run_migrate_command(
367            command,
368            &migration_dir,
369            database_schema,
370            database_url,
371            verbose,
372        )
373        .unwrap_or_else(handle_error),
374    }
375}