diesel_cli 2.3.7

Provides the CLI for the Diesel crate
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
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
use crate::config;
use crate::database::{Backend, InferConnection};
use crate::infer_schema_internals::*;

use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashSet};
use std::fmt::{self, Display, Formatter, Write};
use std::io::Write as IoWrite;
use std::{process, str};

const SCHEMA_HEADER: &str = "// @generated automatically by Diesel CLI.\n";

/// How to sort columns when querying the table schema.
#[derive(Debug, Default, Deserialize, Serialize, Clone, Copy)]
pub enum ColumnSorting {
    /// Order by ordinal position
    #[serde(rename = "ordinal_position")]
    #[default]
    OrdinalPosition,
    /// Order by column name
    #[serde(rename = "name")]
    Name,
}

#[derive(Clone, Copy, Debug, Default)]
pub enum DocConfig {
    DatabaseCommentsFallbackToAutoGeneratedDocComment,
    OnlyDatabaseComments,
    #[default]
    NoDocComments,
}

/// How to group tables in `allow_tables_to_appear_in_same_query!()`.
#[derive(Debug, Default, Deserialize, Serialize, Clone, Copy)]
pub enum AllowTablesToAppearInSameQueryConfig {
    /// Group by foreign key relations
    #[serde(rename = "fk_related_tables")]
    FkRelatedTables,
    /// List all tables in invocation
    #[serde(rename = "all_tables")]
    #[default]
    AllTables,
    /// Don't generate any invocation
    #[serde(rename = "none")]
    None,
}

pub fn run_print_schema<W: IoWrite>(
    connection: &mut InferConnection,
    config: &config::PrintSchema,
    output: &mut W,
) -> Result<(), crate::errors::Error> {
    let schema = output_schema(connection, config)?;

    output
        .write_all(schema.as_bytes())
        .map_err(|e| crate::errors::Error::IoError(e, None))?;
    Ok(())
}

fn common_diesel_types(types: &mut HashSet<&str>) {
    types.insert("Bool");
    types.insert("Integer");
    types.insert("SmallInt");
    types.insert("BigInt");
    types.insert("Binary");
    types.insert("Text");
    types.insert("Double");
    types.insert("Float");
    types.insert("Numeric");
    types.insert("Timestamp");
    types.insert("Date");
    types.insert("Time");

    // hidden type defs
    types.insert("Float4");
    types.insert("Smallint");
    types.insert("Int2");
    types.insert("Int4");
    types.insert("Int8");
    types.insert("Bigint");
    types.insert("Float8");
    types.insert("Decimal");
    types.insert("VarChar");
    types.insert("Varchar");
    types.insert("Char");
    types.insert("Tinytext");
    types.insert("Mediumtext");
    types.insert("Longtext");
    types.insert("Tinyblob");
    types.insert("Blob");
    types.insert("Mediumblob");
    types.insert("Longblob");
    types.insert("Varbinary");
    types.insert("Bit");
}

#[cfg(feature = "postgres")]
fn pg_diesel_types() -> HashSet<&'static str> {
    let mut types = HashSet::new();
    types.insert("Cidr");
    types.insert("Citext");
    types.insert("Inet");
    types.insert("Jsonb");
    types.insert("MacAddr");
    types.insert("MacAddr8");
    types.insert("Money");
    types.insert("Oid");
    types.insert("Range");
    types.insert("Timestamptz");
    types.insert("Uuid");
    types.insert("Json");
    types.insert("PgLsn");
    types.insert("Record");
    types.insert("Interval");

    // hidden type defs
    types.insert("Int4range");
    types.insert("Int8range");
    types.insert("Daterange");
    types.insert("Numrange");
    types.insert("Tsrange");
    types.insert("Tstzrange");
    types.insert("Int4multirange");
    types.insert("Int8multirange");
    types.insert("Datemultirange");
    types.insert("Nummultirange");
    types.insert("Tsmultirange");
    types.insert("Tstzmultirange");
    types.insert("SmallSerial");
    types.insert("BigSerial");
    types.insert("Serial");
    types.insert("Bytea");
    types.insert("Bpchar");
    types.insert("Macaddr");
    types.insert("Macaddr8");

    common_diesel_types(&mut types);
    types
}

#[cfg(feature = "mysql")]
fn mysql_diesel_types() -> HashSet<&'static str> {
    let mut types = HashSet::new();
    common_diesel_types(&mut types);

    types.insert("TinyInt");
    types.insert("Tinyint");
    types.insert("Datetime");
    types.insert("Json");
    types
}

#[cfg(feature = "sqlite")]
fn sqlite_diesel_types() -> HashSet<&'static str> {
    let mut types = HashSet::new();
    common_diesel_types(&mut types);
    types
}

#[tracing::instrument(skip(connection))]
pub fn output_schema(
    connection: &mut InferConnection,
    config: &config::PrintSchema,
) -> Result<String, crate::errors::Error> {
    let table_names = filter_table_names(
        load_table_names(connection, config.schema_name())?,
        &config.filter,
    );

    let foreign_keys = load_foreign_key_constraints(connection, config.schema_name())?;
    let foreign_keys =
        remove_unsafe_foreign_keys_for_codegen(connection, &foreign_keys, &table_names);
    let table_data = table_names
        .into_iter()
        .map(|t| load_table_data(connection, t, config))
        .collect::<Result<Vec<_>, crate::errors::Error>>()?;

    let mut out = String::new();
    writeln!(out, "{SCHEMA_HEADER}")?;

    let backend = Backend::for_connection(connection);

    let columns_custom_types = if config.generate_missing_sql_type_definitions() {
        let diesel_provided_types = match backend {
            #[cfg(feature = "postgres")]
            Backend::Pg => pg_diesel_types(),
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => sqlite_diesel_types(),
            #[cfg(feature = "mysql")]
            Backend::Mysql => mysql_diesel_types(),
        };

        Some(
            table_data
                .iter()
                .map(|t| {
                    t.column_data
                        .iter()
                        .map(|c| {
                            Some(&c.ty)
                                .filter(|ty| !diesel_provided_types.contains(ty.rust_name.as_str()))
                                // Skip types that are that match the regexes in the configuration
                                .filter(|ty| {
                                    !config
                                        .except_custom_type_definitions
                                        .iter()
                                        .any(|rx| rx.is_match(ty.rust_name.as_str()))
                                })
                                .map(|ty| match backend {
                                    #[cfg(feature = "postgres")]
                                    Backend::Pg => ty.clone(),
                                    #[cfg(feature = "sqlite")]
                                    Backend::Sqlite => ty.clone(),
                                    #[cfg(feature = "mysql")]
                                    Backend::Mysql => {
                                        // For MySQL we generate custom types for unknown types that
                                        // are dedicated to the column
                                        use heck::ToUpperCamelCase;

                                        ColumnType {
                                            rust_name: format!(
                                                "{} {} {}",
                                                &t.name.rust_name, &c.rust_name, &ty.rust_name
                                            )
                                            .to_upper_camel_case(),
                                            ..ty.clone()
                                        }
                                    }
                                })
                        })
                        .collect::<Vec<Option<ColumnType>>>()
                })
                .collect::<Vec<_>>(),
        )
    } else {
        None
    };

    let definitions = TableDefinitions {
        tables: table_data,
        fk_constraints: foreign_keys,
        with_docs: config.with_docs,
        allow_tables_to_appear_in_same_query_config: config
            .allow_tables_to_appear_in_same_query_config,
        custom_types_for_tables: columns_custom_types.map(|custom_types_sorted| {
            CustomTypesForTables {
                backend,
                types_overrides_sorted: custom_types_sorted,
                with_docs: match config.with_docs {
                    DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment => true,
                    DocConfig::OnlyDatabaseComments | DocConfig::NoDocComments => false,
                },
                #[cfg(any(feature = "postgres", feature = "mysql"))]
                derives: config.custom_type_derives(),
            }
        }),
        import_types: config.import_types(),
    };

    if let Some(schema_name) = config.schema_name() {
        write!(out, "{}", ModuleDefinition(schema_name, definitions))?;
    } else {
        if let Some(ref custom_types_for_tables) = definitions.custom_types_for_tables {
            write!(
                out,
                "{}",
                CustomTypesForTablesForDisplay {
                    custom_types: custom_types_for_tables,
                    tables: &definitions.tables
                }
            )?;
        }

        write!(out, "{definitions}")?;
    }

    out = match format_schema(&out) {
        Ok(schema) => schema,
        Err(err) => {
            tracing::warn!(
                "Couldn't format schema. Exporting unformatted schema ({:?})",
                err
            );
            out
        }
    };

    if let Some(ref patch_file) = config.patch_file {
        tracing::info!(
            ?patch_file,
            "Found patch file to apply to the generated schema"
        );
        tracing::trace!(?out, "Schema before applying patch file");
        let patch = match std::fs::read_to_string(patch_file) {
            Ok(patch) => patch,
            Err(e) => {
                eprintln!(
                    "Failed to read patch file at {}: {}",
                    patch_file.display(),
                    e
                );
                return Err(crate::errors::Error::IoError(e, Some(patch_file.clone())));
            }
        };
        let patch = diffy::Patch::from_str(&patch)?;

        out = diffy::apply(&out, &patch)?;
    }

    Ok(out)
}

pub fn format_schema(schema: &str) -> Result<String, crate::errors::Error> {
    use crate::errors::Error;
    // Inject schema through rustfmt stdin and get the formatted output
    let mut child = process::Command::new("rustfmt")
        .stdin(process::Stdio::piped())
        .stdout(process::Stdio::piped())
        .stderr(process::Stdio::piped())
        .spawn()
        .map_err(|err| Error::RustFmtFail(format!("Failed to launch child process ({err})")))?;

    {
        let mut stdin = child
            .stdin
            .take()
            .expect("we can always get the stdin from the child process");

        stdin.write_all(schema.as_bytes()).map_err(|err| {
            Error::RustFmtFail(format!("Failed to send schema to rustfmt ({err})"))
        })?;
        // the inner scope makes it so stdin gets dropped here
    }

    let output = child
        .wait_with_output()
        .map_err(|err| Error::RustFmtFail(format!("Couldn't wait for child ({err})")))?;

    // in cases rustfmt isn't installed, it will fail with
    // 'error: 'rustfmt' is not installed for ...'
    // this catches that error
    if !output.status.success() {
        let stderr = String::from_utf8(output.stderr).expect("rustfmt output is valid utf-8");
        return Err(Error::RustFmtFail(format!("rustfmt error ({stderr})")));
    }

    let out = String::from_utf8(output.stdout).expect("rustfmt output is valid utf-8");
    Ok(out)
}

struct CustomTypesForTables {
    backend: Backend,
    // To be zipped with tables then columns
    types_overrides_sorted: Vec<Vec<Option<ColumnType>>>,
    with_docs: bool,
    #[cfg(any(feature = "postgres", feature = "mysql"))]
    derives: Vec<String>,
}

pub struct CustomTypesForTablesForDisplay<'a> {
    custom_types: &'a CustomTypesForTables,
    tables: &'a [TableData],
}

#[allow(clippy::print_in_format_impl)]
impl Display for CustomTypesForTablesForDisplay<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self.custom_types.backend {
            #[cfg(feature = "postgres")]
            Backend::Pg => {
                let _ = &self.tables;
                let mut types_to_generate: Vec<&ColumnType> = self
                    .custom_types
                    .types_overrides_sorted
                    .iter()
                    .flatten()
                    .flatten()
                    .collect();
                if types_to_generate.is_empty() {
                    return Ok(());
                }
                types_to_generate
                    .sort_unstable_by_key(|column_type| column_type.rust_name.as_str());
                // On PG we expect that there may be duplicates because types names are not made
                // specific to the column, unlike MySQL
                types_to_generate.dedup_by_key(|column_type| column_type.rust_name.as_str());

                if self.custom_types.with_docs {
                    writeln!(f, "/// A module containing custom SQL type definitions")?;
                    writeln!(f, "///")?;
                    writeln!(f, "/// (Automatically generated by Diesel.)")?;
                }
                let mut out = PadAdapter::new(f);
                writeln!(out, "pub mod sql_types {{")?;

                for (idx, &ct) in types_to_generate.iter().enumerate() {
                    if idx != 0 {
                        writeln!(out)?;
                    }
                    if self.custom_types.with_docs {
                        if let Some(ref schema) = ct.schema {
                            writeln!(out, "/// The `{}.{}` SQL type", schema, ct.sql_name)?;
                        } else {
                            writeln!(out, "/// The `{}` SQL type", ct.sql_name)?;
                        }
                        writeln!(out, "///")?;
                        writeln!(out, "/// (Automatically generated by Diesel.)")?;
                    }
                    writeln!(out, "#[derive({})]", self.custom_types.derives.join(", "))?;
                    if let Some(ref schema) = ct.schema {
                        writeln!(
                            out,
                            "#[diesel(postgres_type(name = \"{}\", schema = \"{}\"))]",
                            ct.sql_name, schema
                        )?;
                    } else {
                        writeln!(out, "#[diesel(postgres_type(name = \"{}\"))]", ct.sql_name)?;
                    }
                    writeln!(out, "pub struct {};", ct.rust_name)?;
                }

                writeln!(f, "}}\n")?;
                Ok(())
            }
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => {
                let _ = (&f, self.custom_types.with_docs, &self.tables);

                let mut types_to_generate: Vec<&ColumnType> = self
                    .custom_types
                    .types_overrides_sorted
                    .iter()
                    .flatten()
                    .flatten()
                    .collect();
                types_to_generate
                    .sort_unstable_by_key(|column_type| column_type.rust_name.as_str());

                if types_to_generate.is_empty() {
                    return Ok(());
                }
                for t in &types_to_generate {
                    eprintln!("Encountered unknown type for Sqlite: {}", t.sql_name);
                }
                unreachable!(
                    "Diesel only support a closed set of types for Sqlite. \
                     If you ever see this error message please open an \
                     issue at https://github.com/diesel-rs/diesel containing \
                     a dump of your schema definition."
                )
            }
            #[cfg(feature = "mysql")]
            Backend::Mysql => {
                let mut types_to_generate: Vec<(&ColumnType, &TableName, &ColumnDefinition)> = self
                    .custom_types
                    .types_overrides_sorted
                    .iter()
                    .zip(self.tables)
                    .flat_map(|(ct, t)| {
                        ct.iter()
                            .zip(&t.column_data)
                            .map(move |(ct, c)| (ct, c, &t.name))
                    })
                    .filter_map(|(ct, c, t)| ct.as_ref().map(|ct| (ct, t, c)))
                    .collect();
                if types_to_generate.is_empty() {
                    return Ok(());
                }
                types_to_generate.sort_by_key(|(column_type, _, _)| column_type.rust_name.as_str());

                if self.custom_types.with_docs {
                    writeln!(f, "/// A module containing custom SQL type definitions")?;
                    writeln!(f, "///")?;
                    writeln!(f, "/// (Automatically generated by Diesel.)")?;
                }

                let mut out = PadAdapter::new(f);
                writeln!(out, "pub mod sql_types {{")?;

                for (idx, &(custom_type, table, column)) in types_to_generate.iter().enumerate() {
                    if idx != 0 {
                        writeln!(out)?;
                    }

                    if self.custom_types.with_docs {
                        writeln!(
                            out,
                            "/// The `{}` SQL type for the\n\
                             /// [`{tbl}::{col}`](super::{tbl}::{col})) column",
                            custom_type.sql_name,
                            tbl = table.rust_name,
                            col = column.rust_name,
                        )?;
                        writeln!(out, "///")?;
                        writeln!(out, "/// (Automatically generated by Diesel.)")?;
                    }

                    writeln!(out, "#[derive({})]", self.custom_types.derives.join(", "))?;

                    let mysql_name = {
                        let mut c = custom_type.sql_name.chars();

                        match c.next() {
                            None => String::new(),
                            Some(f) => f.to_uppercase().chain(c).collect::<String>(),
                        }
                    };

                    writeln!(out, "#[diesel(mysql_type(name = \"{mysql_name}\"))]")?;
                    writeln!(out, "pub struct {};", custom_type.rust_name)?;
                }

                writeln!(f, "}}\n")?;
                Ok(())
            }
        }
    }
}

struct ModuleDefinition<'a>(&'a str, TableDefinitions<'a>);

impl Display for ModuleDefinition<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        {
            let mut out = PadAdapter::new(f);
            writeln!(out, "pub mod {} {{", self.0)?;
            if let Some(ref custom_types_for_tables) = self.1.custom_types_for_tables {
                write!(
                    out,
                    "{}",
                    CustomTypesForTablesForDisplay {
                        custom_types: custom_types_for_tables,
                        tables: &self.1.tables
                    }
                )?;
            }
            write!(out, "{}", self.1)?;
        }
        writeln!(f, "}}")?;
        Ok(())
    }
}

struct TableDefinitions<'a> {
    tables: Vec<TableData>,
    fk_constraints: Vec<ForeignKeyConstraint>,
    with_docs: DocConfig,
    allow_tables_to_appear_in_same_query_config: AllowTablesToAppearInSameQueryConfig,
    import_types: Option<&'a [String]>,
    custom_types_for_tables: Option<CustomTypesForTables>,
}

impl Display for TableDefinitions<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let mut is_first = true;
        for (table_idx, table) in self.tables.iter().enumerate() {
            if is_first {
                is_first = false;
            } else {
                writeln!(f)?;
            }
            writeln!(
                f,
                "{}",
                TableDefinition {
                    table,
                    with_docs: self.with_docs,
                    import_types: self.import_types,
                    custom_type_overrides: self
                        .custom_types_for_tables
                        .as_ref()
                        .map(|cts| cts.types_overrides_sorted[table_idx].as_slice())
                }
            )?;
        }

        if !self.fk_constraints.is_empty() {
            writeln!(f)?;
        }

        for foreign_key in &self.fk_constraints {
            writeln!(f, "{}", Joinable(foreign_key))?;
        }

        let table_groups = match self.allow_tables_to_appear_in_same_query_config {
            AllowTablesToAppearInSameQueryConfig::FkRelatedTables => {
                foreign_key_table_groups(&self.tables, &self.fk_constraints)
            }
            AllowTablesToAppearInSameQueryConfig::AllTables => {
                vec![self.tables.iter().map(|table| &table.name).collect()]
            }
            AllowTablesToAppearInSameQueryConfig::None => vec![],
        };
        for (table_group_index, table_group) in table_groups
            .into_iter()
            .filter(|table_group| table_group.len() >= 2)
            .enumerate()
        {
            if table_group_index == 0 {
                writeln!(f)?;
            }
            write!(f, "diesel::allow_tables_to_appear_in_same_query!(")?;
            {
                let mut out = PadAdapter::new(f);
                writeln!(out)?;
                for table in table_group {
                    write!(out, "{},", table.rust_name)?;
                }
            }
            writeln!(f, ");")?;
        }

        Ok(())
    }
}

/// Calculates groups of tables that are related by foreign key.
///
/// Given the graph of all tables and their foreign key relations, this returns the set of connected
/// components of that graph.
fn foreign_key_table_groups<'a>(
    tables: &'a [TableData],
    fk_constraints: &'a [ForeignKeyConstraint],
) -> Vec<Vec<&'a TableName>> {
    let mut visited = BTreeSet::new();
    let mut components = vec![];

    // Find connected components in table graph. For the intended purpose of this function, we treat
    // the foreign key relation as being symmetrical, i.e. we are operating on the undirected graph.
    //
    // The algorithm is not optimized and suffers from repeated lookups in the foreign key list, but
    // it should be sufficient for typical table counts from a few dozen up to a few hundred tables.
    for table in tables {
        let name = &table.name;
        if visited.contains(name) {
            // This table is already part of another connected component.
            continue;
        }

        visited.insert(name);
        let mut component = vec![];
        let mut pending = vec![name];

        // Start a depth-first search with the current table name, walking the foreign key relations
        // in both directions.
        while let Some(name) = pending.pop() {
            component.push(name);

            let mut visit = |related_name: &'a TableName| {
                if visited.insert(related_name) {
                    pending.push(related_name);
                }
            };

            // Visit all remaining child tables that have this table as parent.
            for foreign_key in fk_constraints.iter().filter(|fk| fk.parent_table == *name) {
                visit(&foreign_key.child_table);
            }

            // Visit all remaining parent tables that have this table as child.
            for foreign_key in fk_constraints.iter().filter(|fk| fk.child_table == *name) {
                visit(&foreign_key.parent_table);
            }
        }

        // The component contains all tables that are reachable in either direction from the current
        // table. Sort that list by table name to ensure a stable output that does not depend on the
        // algorithm's specific implementation.
        component.sort();

        components.push(component);
    }

    // Sort the list of components to ensure a stable output that does not depend on the algorithm's
    // specific implementation. This sorts the list of components by the name of the first tables in
    // each component.
    components.sort();

    components
}

struct TableDefinition<'a> {
    table: &'a TableData,
    with_docs: DocConfig,
    import_types: Option<&'a [String]>,
    custom_type_overrides: Option<&'a [Option<ColumnType>]>,
}

fn write_doc_comments(out: &mut impl fmt::Write, doc: &str) -> fmt::Result {
    for line in doc.lines() {
        let line = line.trim();
        writeln!(out, "///{}{}", if line.is_empty() { "" } else { " " }, line)?;
    }
    Ok(())
}

impl Display for TableDefinition<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "diesel::table! {{")?;
        {
            let mut out = PadAdapter::new(f);
            writeln!(out)?;

            let mut has_written_import = false;
            if let Some(types) = self.import_types {
                for import in types {
                    writeln!(out, "use {import};")?;
                    has_written_import = true;
                }
            }

            #[cfg(any(feature = "mysql", feature = "postgres"))]
            {
                let mut already_imported_custom_types: HashSet<&str> = HashSet::new();
                for ct in self
                    .custom_type_overrides
                    .iter()
                    .copied()
                    .flatten()
                    .filter_map(|opt| opt.as_ref())
                {
                    if already_imported_custom_types.insert(&ct.rust_name) {
                        if !has_written_import {
                            writeln!(out, "use diesel::sql_types::*;")?;
                        }
                        writeln!(out, "use super::sql_types::{};", ct.rust_name)?;
                        has_written_import = true;
                    }
                }
            }

            #[cfg(not(any(feature = "mysql", feature = "postgres")))]
            let _ = self.custom_type_overrides;

            if has_written_import {
                writeln!(out)?;
            }

            let full_sql_name = self.table.name.full_sql_name();

            match self.with_docs {
                DocConfig::NoDocComments => {}
                DocConfig::OnlyDatabaseComments => {
                    if let Some(comment) = self.table.comment.as_deref() {
                        write_doc_comments(&mut out, comment)?;
                    }
                }
                DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment => {
                    if let Some(comment) = self.table.comment.as_deref() {
                        write_doc_comments(&mut out, comment)?;
                    } else {
                        write_doc_comments(
                            &mut out,
                            &format!(
                                "Representation of the `{full_sql_name}` table.

                                (Automatically generated by Diesel.)",
                            ),
                        )?;
                    }
                }
            }

            if self.table.name.rust_name != self.table.name.sql_name {
                writeln!(out, r#"#[sql_name = "{full_sql_name}"]"#,)?;
            }

            write!(out, "{} (", self.table.name)?;

            for (i, pk) in self.table.primary_key.iter().enumerate() {
                if i != 0 {
                    write!(out, ", ")?;
                }
                write!(out, "{pk}")?;
            }

            write!(
                out,
                ") {}",
                ColumnDefinitions {
                    columns: &self.table.column_data,
                    with_docs: self.with_docs,
                    table_full_sql_name: &full_sql_name,
                    custom_type_overrides: self.custom_type_overrides
                }
            )?;
        }
        write!(f, "}}")?;
        Ok(())
    }
}

struct ColumnDefinitions<'a> {
    columns: &'a [ColumnDefinition],
    with_docs: DocConfig,
    table_full_sql_name: &'a str,
    custom_type_overrides: Option<&'a [Option<ColumnType>]>,
}

impl Display for ColumnDefinitions<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        {
            let mut out = PadAdapter::new(f);
            writeln!(out, "{{")?;
            for (column_idx, column) in self.columns.iter().enumerate() {
                let column_type = self
                    .custom_type_overrides
                    .and_then(|ct| ct[column_idx].as_ref())
                    .unwrap_or(&column.ty);

                match self.with_docs {
                    DocConfig::NoDocComments => {}
                    DocConfig::OnlyDatabaseComments => {
                        if let Some(comment) = column.comment.as_deref() {
                            write_doc_comments(&mut out, comment)?;
                        }
                    }
                    DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment => {
                        if let Some(comment) = column.comment.as_deref() {
                            write_doc_comments(&mut out, comment)?;
                        } else {
                            write_doc_comments(
                                &mut out,
                                &format!(
                                    "The `{}` column of the `{}` table.

                                    Its SQL type is `{}`.

                                    (Automatically generated by Diesel.)",
                                    column.sql_name, self.table_full_sql_name, column_type
                                ),
                            )?;
                        }
                    }
                }

                // Write out attributes
                if column.rust_name != column.sql_name {
                    writeln!(out, r#"#[sql_name = "{}"]"#, column.sql_name)?;
                }
                if let Some(max_length) = column.ty.max_length {
                    writeln!(out, r#"#[max_length = {max_length}]"#)?;
                }

                writeln!(out, "{} -> {},", column.rust_name, column_type)?;
            }
        }
        writeln!(f, "}}")?;
        Ok(())
    }
}

struct Joinable<'a>(&'a ForeignKeyConstraint);

impl Display for Joinable<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let child_table_name = &self.0.child_table.rust_name;

        let parent_table_name = &self.0.parent_table.rust_name;

        write!(
            f,
            "diesel::joinable!({} -> {} ({}));",
            child_table_name, parent_table_name, self.0.foreign_key_columns_rust[0],
        )
    }
}

/// Lifted directly from libcore/fmt/builders.rs
struct PadAdapter<'a, 'b: 'a> {
    fmt: &'a mut Formatter<'b>,
    on_newline: bool,
}

impl<'a, 'b: 'a> PadAdapter<'a, 'b> {
    fn new(fmt: &'a mut Formatter<'b>) -> PadAdapter<'a, 'b> {
        PadAdapter {
            fmt,
            on_newline: false,
        }
    }
}

impl<'a, 'b: 'a> Write for PadAdapter<'a, 'b> {
    fn write_str(&mut self, mut s: &str) -> fmt::Result {
        while !s.is_empty() {
            let on_newline = self.on_newline;

            let split = match s.find('\n') {
                Some(pos) => {
                    self.on_newline = true;
                    pos + 1
                }
                None => {
                    self.on_newline = false;
                    s.len()
                }
            };

            let to_write = &s[..split];
            if on_newline && to_write != "\n" {
                self.fmt.write_str("    ")?;
            }
            self.fmt.write_str(to_write)?;

            s = &s[split..];
        }

        Ok(())
    }
}

impl DocConfig {
    pub const VARIANTS_STR: &'static [&'static str] = &[
        "database-comments-fallback-to-auto-generated-doc-comment",
        "only-database-comments",
        "no-doc-comments",
    ];
}

impl<'de> Deserialize<'de> for DocConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct DocConfigVisitor;
        impl serde::de::Visitor<'_> for DocConfigVisitor {
            type Value = DocConfig;
            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(
                    formatter,
                    "a boolean or one of the following: {:?}",
                    DocConfig::VARIANTS_STR
                )
            }

            fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(match v {
                    true => DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment,
                    false => DocConfig::NoDocComments,
                })
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(match v {
                    "database-comments-fallback-to-auto-generated-doc-comment" => {
                        DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment
                    }
                    "only-database-comments" => DocConfig::OnlyDatabaseComments,
                    "no-doc-comments" => DocConfig::NoDocComments,
                    _ => {
                        return Err(serde::de::Error::unknown_variant(
                            v,
                            DocConfig::VARIANTS_STR,
                        ))
                    }
                })
            }
        }

        deserializer.deserialize_any(DocConfigVisitor)
    }
}

impl str::FromStr for DocConfig {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "database-comments-fallback-to-auto-generated-doc-comment" => {
                DocConfig::DatabaseCommentsFallbackToAutoGeneratedDocComment
            }
            "only-database-comments" => DocConfig::OnlyDatabaseComments,
            "no-doc-comments" => DocConfig::NoDocComments,
            _ => {
                return Err("Unknown variant for doc config, expected one of: \
                    `database-comments-fallback-to-auto-generated-doc-comment`, \
                    `only-database-comments`, \
                    `no-doc-comments`")
            }
        })
    }
}

impl str::FromStr for AllowTablesToAppearInSameQueryConfig {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "fk_related_tables" => AllowTablesToAppearInSameQueryConfig::FkRelatedTables,
            "all_tables" => AllowTablesToAppearInSameQueryConfig::AllTables,
            "none" => AllowTablesToAppearInSameQueryConfig::None,
            _ => {
                return Err(
                    "Unknown variant for `allow_tables_to_appear_in_same_query!` config \
                    mode, expected one of: \
                    `fk_related_tables`, \
                    `all_tables`",
                )
            }
        })
    }
}