tideorm-cli 0.10.0

Command-line interface for TideORM
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
//! Configuration module for TideORM CLI
//!
//! Handles loading and parsing of tideorm.toml configuration files.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// TideORM CLI Configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TideConfig {
    /// Project configuration
    #[serde(default)]
    pub project: ProjectConfig,

    /// Database configuration
    #[serde(default)]
    pub database: DatabaseConfig,

    /// Paths configuration
    #[serde(default)]
    pub paths: PathsConfig,

    /// Migration configuration
    #[serde(default)]
    pub migration: MigrationConfig,

    /// Seeder configuration
    #[serde(default)]
    pub seeder: SeederConfig,

    /// Model generation configuration
    #[serde(default)]
    pub model: ModelGenConfig,
}

/// Project configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
    /// Project name
    #[serde(default = "default_project_name")]
    pub name: String,

    /// Environment (development, production, test)
    #[serde(default = "default_environment")]
    pub environment: String,

    /// Environment file used for variable expansion
    #[serde(default = "default_env_file")]
    pub env_file: String,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        Self {
            name: default_project_name(),
            environment: default_environment(),
            env_file: default_env_file(),
        }
    }
}

fn default_project_name() -> String {
    "tideorm-project".to_string()
}

fn default_environment() -> String {
    std::env::var("TIDEORM_ENV").unwrap_or_else(|_| "development".to_string())
}

fn default_env_file() -> String {
    ".env".to_string()
}

/// Database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    /// Database driver (postgres, mysql, sqlite)
    #[serde(default = "default_driver")]
    pub driver: String,

    /// Database host
    #[serde(default = "default_host")]
    pub host: String,

    /// Database port
    #[serde(default)]
    pub port: Option<u16>,

    /// Database name
    #[serde(default)]
    pub database: Option<String>,

    /// Database username
    #[serde(default)]
    pub username: Option<String>,

    /// Database password
    #[serde(default)]
    pub password: Option<String>,

    /// Connection URL (overrides individual settings)
    #[serde(default)]
    pub url: Option<String>,

    /// SQLite database path
    #[serde(default)]
    pub sqlite_path: Option<String>,

    /// Connection pool size
    #[serde(default = "default_pool_size")]
    pub pool_size: u32,

    /// Connection timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout: u64,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            driver: default_driver(),
            host: default_host(),
            port: None,
            database: None,
            username: None,
            password: None,
            url: None,
            sqlite_path: None,
            pool_size: default_pool_size(),
            timeout: default_timeout(),
        }
    }
}

fn default_driver() -> String {
    "postgres".to_string()
}

fn default_host() -> String {
    "localhost".to_string()
}

fn default_pool_size() -> u32 {
    5
}

fn default_timeout() -> u64 {
    30
}

impl DatabaseConfig {
    /// Build connection URL from configuration
    ///
    /// This never fails: a driver the CLI does not recognise is rendered with its own name
    /// as the URL scheme so that read-only callers (`tideorm config`) keep working, and the
    /// driver is reported by whoever tries to open a connection. Use
    /// [`DatabaseConfig::try_connection_url`] to surface the unsupported driver directly.
    pub fn connection_url(&self) -> String {
        self.try_connection_url()
            .unwrap_or_else(|_| self.server_connection_url(&self.driver, None, ""))
    }

    /// Build connection URL from configuration, rejecting unsupported drivers.
    pub fn try_connection_url(&self) -> Result<String, String> {
        if let Some(url) = &self.url {
            // Replace environment variables in URL
            return Ok(self.expand_env_vars(url));
        }

        if self.driver == "sqlite" {
            let path = self.sqlite_path.as_deref().unwrap_or("database.db");
            return Ok(sqlite_connection_url(path));
        }

        match driver_url_defaults(&self.driver) {
            Some((scheme, port, user)) => Ok(self.server_connection_url(scheme, Some(port), user)),
            None => Err(format!("Unsupported database driver: {}", self.driver)),
        }
    }

    /// Render `scheme://user[:password]@host[:port]/database`.
    ///
    /// The credentials are percent-encoded: a password containing `@`, `:`, `/` or `#`
    /// would otherwise close the userinfo component early and corrupt the URL.
    fn server_connection_url(
        &self,
        scheme: &str,
        default_port: Option<u16>,
        default_user: &str,
    ) -> String {
        let user = self.username.as_deref().unwrap_or(default_user);
        let password = self.password.as_deref().unwrap_or("");
        let database = self.database.as_deref().unwrap_or("tideorm");
        let authority = match self.port.or(default_port) {
            Some(port) => format!("{}:{}", self.host, port),
            None => self.host.clone(),
        };

        let userinfo = userinfo_prefix(user, password);

        format!("{}://{}{}/{}", scheme, userinfo, authority, database)
    }

    /// Expand environment variables in a string
    fn expand_env_vars(&self, s: &str) -> String {
        expand_env_vars_with_sources(s, &HashMap::new())
    }

    fn resolve_with_env(&mut self, env_values: &HashMap<String, String>) {
        // Everything downstream matches on "postgres" and "mysql", so the
        // aliases are folded here; MariaDB takes MySQL's DDL.
        self.driver = match expand_env_vars_with_sources(&self.driver, env_values).as_str() {
            "postgresql" => "postgres".to_string(),
            "mariadb" => "mysql".to_string(),
            driver => driver.to_string(),
        };
        self.host = expand_env_vars_with_sources(&self.host, env_values);
        self.database = self
            .database
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, env_values));
        self.username = self
            .username
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, env_values));
        self.password = self
            .password
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, env_values));
        self.sqlite_path = self
            .sqlite_path
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, env_values));

        self.url = match &self.url {
            Some(value) => Some(expand_env_vars_with_sources(value, env_values)),
            None => lookup_env("DATABASE_URL", env_values),
        };

        if let Some(url) = self.url.clone() {
            self.apply_connection_url(&url);
        }
    }

    fn apply_connection_url(&mut self, url: &str) {
        let normalized = expand_env_vars_with_sources(url, &HashMap::new());

        if let Some(path) = normalized.strip_prefix("sqlite:///") {
            self.driver = "sqlite".to_string();
            self.sqlite_path = Some(path.to_string());
            self.host.clear();
            self.port = None;
            self.database = None;
            self.username = None;
            self.password = None;
            self.url = Some(normalized);
            return;
        }

        if let Some(path) = normalized.strip_prefix("sqlite://") {
            self.driver = "sqlite".to_string();
            self.sqlite_path = Some(path.to_string());
            self.host.clear();
            self.port = None;
            self.database = None;
            self.username = None;
            self.password = None;
            self.url = Some(normalized);
            return;
        }

        let pattern = regex::Regex::new(
            r"^(?P<driver>[a-zA-Z0-9+]+)://(?:(?P<username>[^:/?#@]+)(?::(?P<password>[^@/?#]*))?@)?(?P<host>\[[^\]]+\]|[^:/?#]+)?(?::(?P<port>\d+))?(?:/(?P<database>[^?#]+))?",
        )
        .unwrap();

        if let Some(captures) = pattern.captures(&normalized) {
            let driver = captures
                .name("driver")
                .map(|value| value.as_str())
                .unwrap_or("postgres");
            self.driver = match driver {
                "postgresql" => "postgres".to_string(),
                other => other.to_string(),
            };
            self.host = captures
                .name("host")
                .map(|value| value.as_str().trim_matches(['[', ']']).to_string())
                .unwrap_or_else(default_host);
            self.port = captures
                .name("port")
                .and_then(|value| value.as_str().parse::<u16>().ok());
            self.database = captures
                .name("database")
                .map(|value| value.as_str().to_string());
            self.username = captures
                .name("username")
                .map(|value| value.as_str().to_string());
            self.password = captures
                .name("password")
                .map(|value| value.as_str().to_string());
            self.sqlite_path = None;
            self.url = Some(normalized);
        }
    }
}

/// Connection-URL defaults (scheme, port, username) for the drivers the CLI can build a
/// URL for.
///
/// MariaDB speaks the MySQL wire protocol and has no scheme of its own, so it maps onto
/// MySQL's defaults rather than being rejected.
fn driver_url_defaults(driver: &str) -> Option<(&'static str, u16, &'static str)> {
    match driver {
        "postgres" | "postgresql" => Some(("postgres", 5432, "postgres")),
        "mysql" | "mariadb" => Some(("mysql", 3306, "root")),
        _ => None,
    }
}

/// Render the `user[:password]@` prefix of a URL authority, or nothing when there are no
/// credentials to carry.
fn userinfo_prefix(username: &str, password: &str) -> String {
    if username.is_empty() && password.is_empty() {
        return String::new();
    }

    let username = encode_userinfo(username);
    if password.is_empty() {
        format!("{}@", username)
    } else {
        format!("{}:{}@", username, encode_userinfo(password))
    }
}

/// Percent-encode a URL userinfo component (a username or a password).
///
/// Everything outside the RFC 3986 unreserved set is escaped, so credentials containing
/// `@`, `:`, `/` or `#` survive a round trip through a connection URL instead of
/// truncating it. Consumers (sqlx, and therefore SeaORM) percent-decode userinfo, so the
/// original value is what reaches the server.
pub(crate) fn encode_userinfo(value: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";

    let mut encoded = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(byte as char);
            }
            _ => {
                encoded.push('%');
                encoded.push(HEX[usize::from(byte >> 4)] as char);
                encoded.push(HEX[usize::from(byte & 0x0f)] as char);
            }
        }
    }

    encoded
}

/// Resolve the project environment, letting `TIDEORM_ENV` win.
///
/// Production guards are only useful when they can be switched on without editing a
/// checked-in file, so an explicit `TIDEORM_ENV` (process environment or env file)
/// overrides whatever `tideorm.toml` declares. Scaffolds emit
/// `environment = "${TIDEORM_ENV}"`, which resolves to the development default when the
/// variable is unset instead of leaking the placeholder through.
fn resolve_environment(raw: &str, env_values: &HashMap<String, String>) -> String {
    if let Some(environment) = lookup_env("TIDEORM_ENV", env_values) {
        let environment = environment.trim();
        if !environment.is_empty() {
            return environment.to_string();
        }
    }

    let expanded = expand_env_vars_with_sources(raw, env_values);
    let expanded = expanded.trim();
    if expanded.is_empty() || expanded.starts_with('$') {
        return "development".to_string();
    }

    expanded.to_string()
}

fn expand_env_vars_with_sources(s: &str, env_values: &HashMap<String, String>) -> String {
    let mut result = s.to_string();
    let re = regex::Regex::new(r"\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)").unwrap();

    for cap in re.captures_iter(s) {
        let var_name = cap.get(1).or_else(|| cap.get(2)).unwrap().as_str();
        if let Some(value) = lookup_env(var_name, env_values) {
            result = result.replace(cap.get(0).unwrap().as_str(), &value);
        }
    }

    result
}

fn lookup_env(name: &str, env_values: &HashMap<String, String>) -> Option<String> {
    std::env::var(name)
        .ok()
        .or_else(|| env_values.get(name).cloned())
}

fn load_env_file(
    config_dir: &Path,
    env_file_name: &str,
) -> Result<HashMap<String, String>, String> {
    let env_path = config_dir.join(env_file_name);
    if !env_path.exists() {
        return Ok(HashMap::new());
    }

    let content = std::fs::read_to_string(&env_path)
        .map_err(|error| format!("Failed to read env file {}: {}", env_path.display(), error))?;

    let mut values = HashMap::new();
    for raw_line in content.lines() {
        let line = raw_line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }

        let line = line.strip_prefix("export ").unwrap_or(line);
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };

        let key = key.trim();
        if key.is_empty() {
            continue;
        }

        let value = parse_env_value(value.trim());
        values.insert(key.to_string(), value);
    }

    Ok(values)
}

fn parse_env_value(value: &str) -> String {
    let mut parsed = value.trim().to_string();
    if parsed.len() >= 2 {
        let quoted_with_double = parsed.starts_with('"') && parsed.ends_with('"');
        let quoted_with_single = parsed.starts_with('\'') && parsed.ends_with('\'');
        if quoted_with_double || quoted_with_single {
            parsed = parsed[1..parsed.len() - 1].to_string();
        }
    }

    parsed
}

fn sqlite_connection_url(path: &str) -> String {
    let normalized = path.replace('\\', "/");
    let bytes = normalized.as_bytes();
    let is_windows_absolute = bytes.len() >= 3 && bytes[1] == b':' && bytes[2] == b'/';

    if is_windows_absolute {
        format!("sqlite:///{}", normalized)
    } else {
        format!("sqlite://{}", normalized)
    }
}

/// Paths configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathsConfig {
    /// Models directory
    #[serde(default = "default_models_path")]
    pub models: String,

    /// Migrations directory
    #[serde(default = "default_migrations_path")]
    pub migrations: String,

    /// Seeders directory
    #[serde(default = "default_seeders_path")]
    pub seeders: String,

    /// Factories directory
    #[serde(default = "default_factories_path")]
    pub factories: String,

    /// Config file that exports TideORM configuration
    #[serde(default = "default_config_file")]
    pub config_file: String,
}

impl Default for PathsConfig {
    fn default() -> Self {
        Self {
            models: default_models_path(),
            migrations: default_migrations_path(),
            seeders: default_seeders_path(),
            factories: default_factories_path(),
            config_file: default_config_file(),
        }
    }
}

fn default_models_path() -> String {
    "src/models".to_string()
}

fn default_migrations_path() -> String {
    "src/migrations".to_string()
}

fn default_seeders_path() -> String {
    "src/seeders".to_string()
}

fn default_factories_path() -> String {
    "src/factories".to_string()
}

fn default_config_file() -> String {
    "src/config.rs".to_string()
}

/// Migration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationConfig {
    /// Migration table name
    #[serde(default = "default_migration_table")]
    pub table: String,

    /// Use timestamps in migration names
    #[serde(default = "default_true")]
    pub timestamps: bool,

    /// Migration file template
    #[serde(default)]
    pub template: Option<String>,
}

impl Default for MigrationConfig {
    fn default() -> Self {
        Self {
            table: default_migration_table(),
            timestamps: true,
            template: None,
        }
    }
}

fn default_migration_table() -> String {
    "_migrations".to_string()
}

fn default_true() -> bool {
    true
}

/// Seeder configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SeederConfig {
    /// Seeder file template
    #[serde(default)]
    pub template: Option<String>,
}

/// Model generation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelGenConfig {
    /// Default timestamps (created_at, updated_at)
    #[serde(default = "default_true")]
    pub timestamps: bool,

    /// Default soft deletes
    #[serde(default)]
    pub soft_deletes: bool,

    /// Default tokenization
    #[serde(default)]
    pub tokenize: bool,

    /// Model file template
    #[serde(default)]
    pub template: Option<String>,

    /// Primary key field name
    #[serde(default = "default_primary_key")]
    pub primary_key: String,

    /// Primary key type
    #[serde(default = "default_primary_key_type")]
    pub primary_key_type: String,
}

impl Default for ModelGenConfig {
    fn default() -> Self {
        Self {
            timestamps: true,
            soft_deletes: false,
            tokenize: false,
            template: None,
            primary_key: default_primary_key(),
            primary_key_type: default_primary_key_type(),
        }
    }
}

fn default_primary_key() -> String {
    "id".to_string()
}

fn default_primary_key_type() -> String {
    "i64".to_string()
}

impl TideConfig {
    /// Load configuration from a file
    pub fn load(path: &str) -> Result<Self, String> {
        let path = Path::new(path);

        if !path.exists() {
            return Err(format!(
                "Configuration file not found: {}. Run 'tideorm init' to create one.",
                path.display()
            ));
        }

        let content = std::fs::read_to_string(path)
            .map_err(|e| format!("Failed to read config file: {}", e))?;

        let mut config: Self =
            toml::from_str(&content).map_err(|e| format!("Failed to parse config file: {}", e))?;

        let env_values = load_env_file(
            path.parent().unwrap_or_else(|| Path::new(".")),
            &config.project.env_file,
        )?;

        config.project.name = expand_env_vars_with_sources(&config.project.name, &env_values);
        config.project.environment = resolve_environment(&config.project.environment, &env_values);
        config.project.env_file =
            expand_env_vars_with_sources(&config.project.env_file, &env_values);
        config.paths.models = expand_env_vars_with_sources(&config.paths.models, &env_values);
        config.paths.migrations =
            expand_env_vars_with_sources(&config.paths.migrations, &env_values);
        config.paths.seeders = expand_env_vars_with_sources(&config.paths.seeders, &env_values);
        config.paths.factories = expand_env_vars_with_sources(&config.paths.factories, &env_values);
        config.paths.config_file =
            expand_env_vars_with_sources(&config.paths.config_file, &env_values);
        config.migration.table = expand_env_vars_with_sources(&config.migration.table, &env_values);
        config.migration.template = config
            .migration
            .template
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, &env_values));
        config.seeder.template = config
            .seeder
            .template
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, &env_values));
        config.model.template = config
            .model
            .template
            .as_ref()
            .map(|value| expand_env_vars_with_sources(value, &env_values));
        config.model.primary_key =
            expand_env_vars_with_sources(&config.model.primary_key, &env_values);
        config.model.primary_key_type =
            expand_env_vars_with_sources(&config.model.primary_key_type, &env_values);
        config.database.resolve_with_env(&env_values);

        Ok(config)
    }

    /// Load configuration, falling back to defaults only when the file does not exist.
    ///
    /// A missing `tideorm.toml` is a legitimate "no project configuration" state for the
    /// commands that only generate files, so it yields [`TideConfig::default`]. A file that
    /// exists but cannot be read or parsed is always an error: silently replacing it with
    /// the built-in (Postgres) defaults would emit code for the wrong backend into the
    /// wrong directories.
    pub fn load_or_default(path: &str) -> Result<Self, String> {
        if Path::new(path).exists() {
            Self::load(path)
        } else {
            Ok(Self::default())
        }
    }

    /// Check if running in production
    pub fn is_production(&self) -> bool {
        self.project.environment == "production"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_default_config() {
        let config = TideConfig::default();
        assert_eq!(config.database.driver, "postgres");
        assert_eq!(config.paths.models, "src/models");
    }

    #[test]
    fn test_connection_url_postgres() {
        let config = DatabaseConfig {
            driver: "postgres".to_string(),
            username: Some("user".to_string()),
            password: Some("pass".to_string()),
            database: Some("mydb".to_string()),
            ..Default::default()
        };

        let url = config.connection_url();
        assert!(url.starts_with("postgres://"));
        assert!(url.contains("user"));
        assert!(url.contains("mydb"));
    }

    #[test]
    fn test_connection_url_sqlite() {
        let config = DatabaseConfig {
            driver: "sqlite".to_string(),
            sqlite_path: Some("test.db".to_string()),
            ..Default::default()
        };

        let url = config.connection_url();
        assert_eq!(url, "sqlite://test.db");
    }

    #[test]
    fn test_connection_url_sqlite_windows_absolute_path() {
        let config = DatabaseConfig {
            driver: "sqlite".to_string(),
            sqlite_path: Some("C:\\Users\\alice\\project\\data.db".to_string()),
            ..Default::default()
        };

        let url = config.connection_url();
        assert_eq!(url, "sqlite:///C:/Users/alice/project/data.db");
    }

    #[test]
    fn test_load_uses_database_url_from_dotenv() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");
        let env_path = fixture.path().join(".env");

        fs::write(
            &config_path,
            r#"[project]
name = "demo"

[database]
driver = "postgres"
host = "localhost"
port = 5432
database = "tideorm_db"
username = "postgres"
password = ""
"#,
        )
        .unwrap();
        fs::write(
            &env_path,
            "DATABASE_URL=postgres://postgres:postgres@localhost:5432/test_tide_ormx\n",
        )
        .unwrap();

        let config = TideConfig::load(config_path.to_str().unwrap()).unwrap();

        assert_eq!(
            config.database.url.as_deref(),
            Some("postgres://postgres:postgres@localhost:5432/test_tide_ormx")
        );
        assert_eq!(config.database.driver, "postgres");
        assert_eq!(config.database.host, "localhost");
        assert_eq!(config.database.port, Some(5432));
        assert_eq!(config.database.database.as_deref(), Some("test_tide_ormx"));
        assert_eq!(config.database.username.as_deref(), Some("postgres"));
        assert_eq!(config.database.password.as_deref(), Some("postgres"));
    }

    #[test]
    fn test_load_expands_database_url_placeholder_from_dotenv() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");
        let env_path = fixture.path().join(".env");

        fs::write(
            &config_path,
            r#"[database]
driver = "postgres"
url = "${DATABASE_URL}"
"#,
        )
        .unwrap();
        fs::write(
            &env_path,
            "DATABASE_URL=postgres://postgres:secret@db.example.com:5433/app_db\n",
        )
        .unwrap();

        let config = TideConfig::load(config_path.to_str().unwrap()).unwrap();

        assert_eq!(
            config.database.connection_url(),
            "postgres://postgres:secret@db.example.com:5433/app_db"
        );
        assert_eq!(config.database.host, "db.example.com");
        assert_eq!(config.database.port, Some(5433));
        assert_eq!(config.database.database.as_deref(), Some("app_db"));
        assert_eq!(config.database.username.as_deref(), Some("postgres"));
    }

    #[test]
    fn test_connection_url_percent_encodes_credentials() {
        let config = DatabaseConfig {
            driver: "postgres".to_string(),
            username: Some("a@b".to_string()),
            password: Some("p@ss:w/rd#1".to_string()),
            database: Some("mydb".to_string()),
            ..Default::default()
        };

        assert_eq!(
            config.connection_url(),
            "postgres://a%40b:p%40ss%3Aw%2Frd%231@localhost:5432/mydb"
        );
    }

    #[test]
    fn test_connection_url_supports_mariadb() {
        let config = DatabaseConfig {
            driver: "mariadb".to_string(),
            database: Some("shop".to_string()),
            ..Default::default()
        };

        let url = config.connection_url();
        assert_eq!(url, "mysql://root@localhost:3306/shop");
    }

    #[test]
    fn test_connection_url_does_not_panic_on_unknown_driver() {
        let config = DatabaseConfig {
            driver: "oracle".to_string(),
            database: Some("app".to_string()),
            ..Default::default()
        };

        assert!(config.try_connection_url().is_err());
        assert_eq!(config.connection_url(), "oracle://localhost/app");
    }

    #[test]
    fn resolve_environment_prefers_tideorm_env() {
        let mut env_values = HashMap::new();
        env_values.insert("TIDEORM_ENV".to_string(), "production".to_string());
        let resolved = resolve_environment("development", &env_values);

        assert_eq!(resolved, "production");
    }

    #[test]
    fn resolve_environment_falls_back_for_unresolved_placeholder() {
        assert_eq!(
            resolve_environment("${TIDEORM_ENV}", &HashMap::new()),
            default_environment()
        );
    }

    #[test]
    fn test_load_environment_placeholder_enables_production_guards() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");

        fs::write(
            &config_path,
            r#"[project]
name = "demo"
environment = "${TIDEORM_ENV}"

[database]
driver = "sqlite"
sqlite_path = "app.db"
"#,
        )
        .unwrap();
        fs::write(fixture.path().join(".env"), "TIDEORM_ENV=production\n").unwrap();

        let config = TideConfig::load(config_path.to_str().unwrap()).unwrap();

        assert_eq!(config.project.environment, "production");
        assert!(config.is_production());
    }

    #[test]
    fn test_load_or_default_reports_broken_config() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");
        fs::write(&config_path, "this is not = valid toml [\n").unwrap();

        let path = config_path.to_str().unwrap();
        assert!(TideConfig::load_or_default(path).is_err());

        let absent = fixture.path().join("missing.toml");
        let absent = absent.to_str().unwrap();
        assert!(TideConfig::load_or_default(absent).is_ok());
    }

    #[test]
    fn test_load_or_default_does_not_fall_back_to_postgres_for_a_broken_config() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");
        fs::write(
            &config_path,
            "[database]\ndriver = \"sqlite\"\nsqlite_path = \n",
        )
        .unwrap();

        let error = TideConfig::load_or_default(config_path.to_str().unwrap())
            .expect_err("a config file that exists but cannot be parsed must be reported");
        assert!(error.contains("Failed to parse config file"), "{}", error);
    }

    #[test]
    fn test_load_uses_custom_env_file_name() {
        let fixture = TempDir::new().unwrap();
        let config_path = fixture.path().join("tideorm.toml");
        let env_path = fixture.path().join(".env.local");

        fs::write(
            &config_path,
            r#"[project]
name = "demo"
env_file = ".env.local"

[database]
driver = "postgres"
"#,
        )
        .unwrap();
        fs::write(
            &env_path,
            "DATABASE_URL=postgres://postgres:postgres@localhost:5432/custom_env_db\n",
        )
        .unwrap();

        let config = TideConfig::load(config_path.to_str().unwrap()).unwrap();
        assert_eq!(config.project.env_file, ".env.local");
        assert_eq!(config.database.database.as_deref(), Some("custom_env_db"));
    }
}