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
#[macro_use]
extern crate diesel;

use diesel::prelude::*;
use eyre::{Context, Result};
use std::fmt::Display;

mod raw {
    use diesel::sql_types::*;

    #[derive(QueryableByName)]
    pub struct Table {
        #[sql_type = "Text"]
        pub name: String,
    }

    #[derive(QueryableByName)]
    pub struct Column {
        #[sql_type = "Text"]
        pub name: String,
        #[sql_type = "Text"]
        #[column_name = "type"]
        pub typ: String,
        #[sql_type = "Bool"]
        pub notnull: bool,
        #[sql_type = "Bool"]
        pub pk: bool,
        #[sql_type = "Nullable<Text>"]
        pub dflt_value: Option<String>,
    }

    #[derive(QueryableByName)]
    pub struct ForeignKey {
        #[sql_type = "Text"]
        pub table: String,
        #[sql_type = "Nullable<Text>"]
        pub to: Option<String>,
        #[sql_type = "Text"]
        pub from: String,
    }
}

#[derive(Debug)]
struct Column {
    name: String,
    typ: String,
    nullable: bool,
    default: Option<String>,
    primary: bool,
}

#[derive(Debug)]
struct Table {
    name: String,
    columns: Vec<Column>,
    foreign_keys: Vec<ForeignKey>,
}

#[derive(Debug)]
struct ForeignKey {
    target_table: String,
    target_column: Option<String>,
    source_table: String,
    source_column: String,
}

#[derive(Debug)]
pub struct Schema(Vec<Table>);

impl Schema {
    fn get_tables(db: &SqliteConnection) -> Result<Vec<Table>> {
        let tables: Vec<raw::Table> = diesel::sql_query(
            "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT IN ('sqlite_sequence')",
        )
        .load(db)?;

        tables
            .into_iter()
            .map(|table| {
                Ok(Table {
                    foreign_keys: Self::get_keys(db, &table.name)
                        .wrap_err_with(|| format!("failed to get keys for {}", &table.name))?,
                    columns: Self::get_columns(db, &table.name)
                        .wrap_err_with(|| format!("failed to get columns for {}", &table.name))?,
                    name: table.name,
                })
            })
            .collect()
    }

    fn get_columns(db: &SqliteConnection, table: &str) -> Result<Vec<Column>> {
        let columns: Vec<raw::Column> =
            diesel::sql_query(format!("SELECT * FROM pragma_table_info('{}')", table)).load(db)?;

        Ok(columns
            .into_iter()
            .map(|column| Column {
                name: column.name,
                typ: column.typ,
                nullable: !column.notnull,
                primary: column.pk,
                default: column.dflt_value,
            })
            .collect())
    }

    fn get_keys(db: &SqliteConnection, table: &str) -> Result<Vec<ForeignKey>> {
        let keys: Vec<raw::ForeignKey> = diesel::sql_query(format!(
            "SELECT * FROM pragma_foreign_key_list('{}')",
            table
        ))
        .load(db)?;

        Ok(keys
            .into_iter()
            .map(|key| ForeignKey {
                target_table: key.table,
                target_column: key.to,
                source_table: table.to_owned(),
                source_column: key.from,
            })
            .collect())
    }

    pub fn load(db: &SqliteConnection) -> eyre::Result<Self> {
        Ok(Self(Self::get_tables(db)?))
    }
}

impl Display for Schema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "digraph {{")?;
        writeln!(f, "rankdir=LR;")?;

        for table in &self.0 {
            table.fmt(f)?;
        }

        writeln!(f, "}}")
    }
}

impl Display for Table {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "{} [shape=plaintext label=< <table border='0' cellborder='1' cellspacing='0' cellpadding='5'>
                <tr><td border='0'></td><td colspan='2'><b>{}</b></td></tr>",
            self.name, self.name
        )?;

        for column in &self.columns {
            writeln!(
                f,
                "<tr><td {} width='16'></td><td>{}</td><td port='{}'>{}</td></tr>",
                if column.primary {
                    "bgcolor='#2aa198'"
                } else if column.nullable {
                    "bgcolor='#6c71c4'"
                } else {
                    ""
                },
                column.name,
                column.name,
                column.typ,
            )?;
        }

        writeln!(f, "</table> >]")?;

        for key in &self.foreign_keys {
            key.fmt(f)?;
        }

        Ok(())
    }
}

impl Display for ForeignKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "{}:{} -> {}",
            self.source_table, self.source_column, self.target_table
        )
    }
}