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
use std::collections::HashMap;

use heck::{ToSnekCase, ToUpperCamelCase};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};

use crate::{client::Client, pragma, value::Value};

#[derive(Clone)]
struct Column {
    name: String,
    typ: String,
    pk: bool,
    notnull: bool,
}

/// Generate rust bindings for a SQLite schema.
/// Use this in your `build.rs` file.
pub fn generate(client: Client) -> String {
    let mut output = TokenStream::new();
    output.extend(quote! {
        use rust_query::{value::{Db, Value}, Builder, HasId, Table, insert::{Reader, Writable}};
    });

    let tables = client.new_query(|q| {
        let table = q.flat_table(pragma::TableList);
        q.filter(table.schema.eq("main"));
        q.filter(table.r#type.eq("table"));
        q.filter(table.name.eq("sqlite_schema").not());
        q.into_vec(u32::MAX, |row| row.get(&table.name))
    });

    for table in &tables {
        let mut columns = client.new_query(|q| {
            let table = q.flat_table(pragma::TableInfo(table.to_owned()));

            q.into_vec(u32::MAX, |row| Column {
                name: row.get(table.name),
                typ: row.get(table.r#type),
                pk: row.get(table.pk) != 0,
                notnull: row.get(table.notnull) != 0,
            })
        });

        let fks: HashMap<_, _> = client
            .new_query(|q| {
                let fk = q.flat_table(pragma::ForeignKeyList(table.to_owned()));
                q.into_vec(u32::MAX, |row| {
                    // we just assume that the to column is the primary key..
                    (row.get(fk.from), row.get(fk.table))
                })
            })
            .into_iter()
            .collect();

        let mut ids = columns.iter().filter(|x| x.pk);
        let mut has_id = ids.next().cloned();
        if ids.next().is_some() {
            has_id = None;
        }

        let make_field = |name: &str| {
            let mut normalized = &*name.to_snek_case();
            if fks.contains_key(name) {
                normalized = normalized.trim_end_matches("_id");
            }
            format_ident!("{normalized}")
        };

        let make_generic = |name: &str| {
            let mut normalized = &*name.to_upper_camel_case();
            if fks.contains_key(name) {
                normalized = normalized.trim_end_matches("Id");
            }
            format_ident!("_{normalized}")
        };

        let make_type = |col: &Column| {
            let mut typ = match col.typ.as_str() {
                "INTEGER" => {
                    if let Some(other) = fks.get(&col.name) {
                        let other_ident = format_ident!("{}", other.to_upper_camel_case());
                        other_ident.to_token_stream()
                    } else {
                        quote!(i64)
                    }
                }
                "TEXT" => quote!(String),
                "REAL" => quote!(f64),
                _ => return None,
            };
            if !col.notnull {
                typ = quote!(Option<#typ>);
            }
            Some(typ)
        };

        // we only care about columns that are not a unique id and for which we know the type
        columns.retain(|col| {
            if has_id.is_some() && col.pk {
                return false;
            }
            if make_type(col).is_none() {
                return false;
            }
            true
        });

        let defs = columns.iter().map(|col| {
            let ident = make_field(&col.name);
            let generic = make_generic(&col.name);
            quote!(pub #ident: #generic)
        });

        let typs = columns.iter().map(|col| {
            let typ = make_type(col).unwrap();
            quote!(Db<'t, #typ>)
        });

        let generics = columns.iter().map(|col| {
            let generic = make_generic(&col.name);
            quote!(#generic)
        });

        let generics_defs = columns.iter().map(|col| {
            let generic = make_generic(&col.name);
            quote!(#generic)
        });

        let read_bounds = columns.iter().map(|col| {
            let typ = make_type(col).unwrap();
            let generic = make_generic(&col.name);
            quote!(#generic: Value<'t, Typ=#typ>)
        });

        let inits = columns.iter().map(|col| {
            let ident = make_field(&col.name);
            let name: &String = &col.name;
            quote!(#ident: f.col(#name))
        });

        let reads = columns.iter().map(|col| {
            let ident = make_field(&col.name);
            let name: &String = &col.name;
            quote!(f.col(#name, self.#ident))
        });

        let table_ident = format_ident!("{}", table.to_upper_camel_case());
        let dummy_ident = format_ident!("{}Dummy", table.to_upper_camel_case());

        let has_id = has_id.as_ref().map(|col| {
            let name: &String = &col.name;
            quote!(
                impl HasId for #table_ident {
                    const ID: &'static str = #name;
                    const NAME: &'static str = #table;
                }
            )
        });

        output.extend(quote! {
            pub struct #table_ident;

            pub struct #dummy_ident<#(#generics_defs),*> {
                #(#defs,)*
            }

            impl Table for #table_ident {
                type Dummy<'t> = #dummy_ident<#(#typs),*>;

                fn name(&self) -> String {
                    #table.to_owned()
                }

                fn build(f: Builder<'_>) -> Self::Dummy<'_> {
                    #dummy_ident {
                        #(#inits,)*
                    }
                }
            }

            impl<'t, #(#read_bounds),*> Writable<'t> for #dummy_ident<#(#generics),*> {
                type T = #table_ident;
                fn read(self, f: Reader<'t>) {
                    #(#reads;)*
                }
            }

            #has_id
        })
    }

    output.to_string()
}