dsync 0.0.17

Generate rust structs & query functions from diesel schema files.
Documentation
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
use indoc::indoc;
use inflector::Inflector;

use crate::parser::{ParsedTableMacro, FILE_SIGNATURE};
use crate::{GenerationConfig, TableOptions};

#[derive(Clone, Copy, PartialEq, Eq)]
enum StructType {
    /// Variant for the `Read` struct which can be queried and has all properties
    Read,
    /// Variant for a `Update*` struct, which has all properties wrapped in [`Option<>`]
    Update,
    /// Variant for a `Create` struct, which only has all the properties which are not autogenerated
    Create,
}

impl StructType {
    /// Get the prefix for the current [StructType]
    ///
    /// Example: `UpdateTodos`
    pub fn prefix(&self) -> &'static str {
        match self {
            StructType::Read => "",
            StructType::Update => "Update",
            StructType::Create => "Create",
        }
    }

    /// Get the suffix for the current [StructType]
    ///
    /// Example: `TodosForm`
    pub fn suffix(&self) -> &'static str {
        match self {
            StructType::Read => "",
            StructType::Update => "",
            StructType::Create => "",
        }
    }

    /// Format a struct with all prefix- and suffixes
    ///
    /// Example: `UpdateTodos`
    pub fn format(&self, name: &'_ str) -> String {
        format!(
            "{struct_prefix}{struct_name}{struct_suffix}",
            struct_prefix = self.prefix(),
            struct_name = name,
            struct_suffix = self.suffix()
        )
    }
}

struct Struct<'a> {
    /// Struct name (like `UpdateTodos`)
    identifier: String,
    /// Type of the Struct
    ty: StructType,
    /// Parsed table reference
    table: &'a ParsedTableMacro,
    /// Generation options specific for the current table
    opts: TableOptions<'a>,
    /// Global generation options
    config: &'a GenerationConfig<'a>,
    /// Storage for the finished generated code
    rendered_code: Option<String>,
    /// Cache for if this struct even has any fields
    has_fields: Option<bool>, // note: this is only correctly set after a call to render() which gets called in Struct::new()
}

#[derive(Debug, Clone)]
pub struct StructField {
    /// Name for the field
    // TODO: should this be a Ident instead of a string?
    pub name: String,
    /// Rust type of the final field
    pub base_type: String,

    pub is_optional: bool,
}

impl<'a> Struct<'a> {
    /// Create a new instance
    pub fn new(
        ty: StructType,
        table: &'a ParsedTableMacro,
        config: &'a GenerationConfig<'_>,
    ) -> Self {
        let mut obj = Self {
            identifier: ty.format(table.struct_name.as_str()),
            opts: config.table(&table.name.to_string()),
            table,
            ty,
            config,
            rendered_code: None,
            has_fields: None,
        };
        obj.render();
        obj
    }

    /// Get the rendered code, or a empty string
    pub fn code(&self) -> &str {
        self.rendered_code.as_deref().unwrap_or_default()
    }

    /// Get if the current struct has fields
    ///
    /// Currently panics if [`render`](#render) has not been called yet
    pub fn has_fields(&self) -> bool {
        self.has_fields.unwrap()
    }

    fn attr_tsync(&self) -> &'static str {
        #[cfg(feature = "tsync")]
        match self.opts.get_tsync() {
            true => "#[tsync::tsync]\n",
            false => "",
        }
        #[cfg(not(feature = "tsync"))]
        ""
    }

    /// Assemble all derives for the struct
    fn attr_derive(&self) -> String {
        format!("#[derive(Debug, {derive_serde}Clone, Queryable, Insertable{derive_aschangeset}{derive_identifiable}{derive_associations}{derive_selectable}{derive_default})]",
                derive_selectable = match self.ty {
                    StructType::Read => { ", Selectable" }
                    _ => { "" }
                },
                derive_associations = match self.ty {
                    StructType::Read => {
                        if !self.table.foreign_keys.is_empty() { ", Associations" } else { "" }
                    }
                    _ => { "" }
                },
                derive_identifiable = match self.ty {
                    StructType::Read => {
                        if !self.table.foreign_keys.is_empty() { ", Identifiable" } else { "" }
                    }
                    _ => { "" }
                },
                derive_aschangeset = if self.fields().iter().all(|f| self.table.primary_key_column_names().contains(&f.name)) {""} else { ", AsChangeset" },
                derive_default = match self.ty {
                    StructType::Update => { ", Default" }
                    _ => { "" }
                },
                derive_serde = if self.config.table(&self.table.name.to_string()).get_serde() {
                    "Serialize, Deserialize, "
                } else { "" }
        )
    }

    /// Assemble all fields the struct will have
    fn fields(&self) -> Vec<StructField> {
        self.table
            .columns
            .iter()
            .filter(|c| {
                let is_autogenerated = self
                    .opts
                    .autogenerated_columns
                    .as_deref()
                    .unwrap_or_default()
                    .contains(&c.name.to_string().as_str());

                match self.ty {
                    StructType::Read => true,
                    StructType::Update => {
                        let is_pk = self.table.primary_key_columns.contains(&c.name);

                        !is_pk
                    }
                    StructType::Create => !is_autogenerated,
                }
            })
            .map(|c| {
                let name = c.name.to_string();
                let base_type = if c.is_unsigned {
                    c.ty.replace('i', "u")
                } else {
                    c.ty.clone()
                };
                let base_type = if c.is_nullable {
                    format!("Option<{}>", base_type)
                } else {
                    base_type
                };
                let mut is_optional = false;

                let is_pk = self
                    .table
                    .primary_key_columns
                    .iter()
                    .any(|pk| pk.to_string().eq(name.as_str()));
                let is_autogenerated = self
                    .opts
                    .autogenerated_columns
                    .as_deref()
                    .unwrap_or_default()
                    .contains(&c.name.to_string().as_str());
                // let is_fk = table.foreign_keys.iter().any(|fk| fk.1.to_string().eq(field_name.as_str()));

                match self.ty {
                    StructType::Read => {}
                    StructType::Update => {
                        // all non-key fields should be optional in Form structs (to allow partial updates)
                        is_optional = !is_pk || (is_pk && is_autogenerated);
                    }
                    StructType::Create => {}
                }

                StructField {
                    name,
                    base_type,
                    is_optional,
                }
            })
            .collect()
    }

    /// Render the full struct
    fn render(&mut self) {
        let ty = self.ty;
        let table = &self.table;
        let _opts = self.config.table(table.name.to_string().as_str());

        let primary_keys: Vec<String> = table.primary_key_column_names();

        let belongs_to = table
            .foreign_keys
            .iter()
            .map(|fk| {
                format!(
                    ", belongs_to({foreign_table_name}, foreign_key={join_column})",
                    foreign_table_name = fk.0.to_string().to_pascal_case().to_singular(),
                    join_column = fk.1
                )
            })
            .collect::<Vec<String>>()
            .join(" ");

        let struct_code = format!(
            indoc! {r#"
            {tsync_attr}{derive_attr}
            #[diesel(table_name={table_name}{primary_key}{belongs_to})]
            pub struct {struct_name} {{
            $COLUMNS$
            }}
        "#},
            tsync_attr = self.attr_tsync(),
            derive_attr = self.attr_derive(),
            table_name = table.name,
            struct_name = ty.format(table.struct_name.as_str()),
            primary_key = if ty != StructType::Read {
                "".to_string()
            } else {
                format!(", primary_key({})", primary_keys.join(","))
            },
            belongs_to = if ty != StructType::Read {
                "".to_string()
            } else {
                belongs_to
            }
        );

        let fields = self.fields();
        let mut lines = vec![];
        for f in fields.iter() {
            let field_name = &f.name;
            let field_type = if f.is_optional {
                format!("Option<{}>", f.base_type)
            } else {
                f.base_type.clone()
            };

            lines.push(format!(r#"    pub {field_name}: {field_type},"#));
        }

        if fields.is_empty() {
            self.has_fields = Some(false);
            self.rendered_code = Some("".to_string());
        } else {
            self.has_fields = Some(true);
            self.rendered_code = Some(struct_code.replace("$COLUMNS$", &lines.join("\n")));
        }
    }
}

/// Generate all functions (insides of the `impl StuctName { here }`)
fn build_table_fns(
    table: &ParsedTableMacro,
    config: &GenerationConfig,
    create_struct: Struct,
    update_struct: Struct,
) -> String {
    let table_options = config.table(&table.name.to_string());

    let primary_column_name_and_type: Vec<(String, String)> = table
        .primary_key_columns
        .iter()
        .map(|pk| {
            let col = table
                .columns
                .iter()
                .find(|it| it.name.to_string().eq(pk.to_string().as_str()))
                .expect("Primary key column doesn't exist in table");

            (col.name.to_string(), col.ty.to_string())
        })
        .collect();

    let item_id_params = primary_column_name_and_type
        .iter()
        .map(|name_and_type| {
            format!(
                "param_{name}: {ty}",
                name = name_and_type.0,
                ty = name_and_type.1
            )
        })
        .collect::<Vec<String>>()
        .join(", ");
    let item_id_filters = primary_column_name_and_type
        .iter()
        .map(|name_and_type| {
            format!(
                "filter({name}.eq(param_{name}))",
                name = name_and_type.0.to_string()
            )
        })
        .collect::<Vec<String>>()
        .join(".");

    // template variables
    let table_name = table.name.to_string();
    #[cfg(feature = "tsync")]
    let tsync = match table_options.get_tsync() {
        true => "#[tsync::tsync]",
        false => "",
    };
    #[cfg(not(feature = "tsync"))]
    let tsync = "";
    #[cfg(feature = "async")]
    let async_keyword = if table_options.get_async() {
        " async"
    } else {
        ""
    };
    #[cfg(not(feature = "async"))]
    let async_keyword = "";
    #[cfg(feature = "async")]
    let await_keyword = if table_options.get_async() {
        ".await"
    } else {
        ""
    };
    #[cfg(not(feature = "async"))]
    let await_keyword = "";
    let struct_name = &table.struct_name;
    let schema_path = &config.schema_path;
    let create_struct_identifier = &create_struct.identifier;
    let update_struct_identifier = &update_struct.identifier;
    let item_id_params = item_id_params;
    let item_id_filters = item_id_filters;

    let mut buffer = String::new();

    buffer.push_str(&format!(
        r##"{tsync}
#[derive(Debug, {serde_derive})]
pub struct PaginationResult<T> {{
    pub items: Vec<T>,
    pub total_items: i64,
    /// 0-based index
    pub page: i64,
    pub page_size: i64,
    pub num_pages: i64,
}}
"##,
        serde_derive = if table_options.get_serde() {
            "Serialize"
        } else {
            ""
        }
    ));

    buffer.push_str(&format!(
        r##"
impl {struct_name} {{
"##
    ));

    if create_struct.has_fields() {
        buffer.push_str(&format!(
            r##"
    pub{async_keyword} fn create(db: &mut ConnectionType, item: &{create_struct_identifier}) -> QueryResult<Self> {{
        use {schema_path}{table_name}::dsl::*;

        insert_into({table_name}).values(item).get_result::<Self>(db){await_keyword}
    }}
"##
        ));
    } else {
        buffer.push_str(&format!(
            r##"
    pub{async_keyword} fn create(db: &mut ConnectionType) -> QueryResult<Self> {{
        use {schema_path}{table_name}::dsl::*;

        insert_into({table_name}).default_values().get_result::<Self>(db){await_keyword}
    }}
"##
        ));
    }

    buffer.push_str(&format!(
        r##"
    pub{async_keyword} fn read(db: &mut ConnectionType, {item_id_params}) -> QueryResult<Self> {{
        use {schema_path}{table_name}::dsl::*;

        {table_name}.{item_id_filters}.first::<Self>(db){await_keyword}
    }}
"##
    ));

    buffer.push_str(&format!(r##"
    /// Paginates through the table where page is a 0-based index (i.e. page 0 is the first page)
    pub{async_keyword} fn paginate(db: &mut ConnectionType, page: i64, page_size: i64) -> QueryResult<PaginationResult<Self>> {{
        use {schema_path}{table_name}::dsl::*;

        let page_size = if page_size < 1 {{ 1 }} else {{ page_size }};
        let total_items = {table_name}.count().get_result(db){await_keyword}?;
        let items = {table_name}.limit(page_size).offset(page * page_size).load::<Self>(db){await_keyword}?;

        Ok(PaginationResult {{
            items,
            total_items,
            page,
            page_size,
            /* ceiling division of integers */
            num_pages: total_items / page_size + i64::from(total_items % page_size != 0)
        }})
    }}
"##));

    // TODO: If primary key columns are attached to the form struct (not optionally)
    // then don't require item_id_params (otherwise it'll be duplicated)

    // if has_update_struct {
    if update_struct.has_fields() {
        // It's possible we have a form struct with all primary keys (for example, for a join table).
        // In this scenario, we also have to check whether there are any updatable columns for which
        // we should generate an update() method.

        buffer.push_str(&format!(r##"
    pub{async_keyword} fn update(db: &mut ConnectionType, {item_id_params}, item: &{update_struct_identifier}) -> QueryResult<Self> {{
        use {schema_path}{table_name}::dsl::*;

        diesel::update({table_name}.{item_id_filters}).set(item).get_result(db){await_keyword}
    }}
"##));
    }

    buffer.push_str(&format!(
        r##"
    pub{async_keyword} fn delete(db: &mut ConnectionType, {item_id_params}) -> QueryResult<usize> {{
        use {schema_path}{table_name}::dsl::*;

        diesel::delete({table_name}.{item_id_filters}).execute(db){await_keyword}
    }}
"##
    ));

    buffer.push_str(
        r##"
}"##,
    );

    buffer
}

/// Generate all imports for the struct file that are required
fn build_imports(table: &ParsedTableMacro, config: &GenerationConfig) -> String {
    let table_options = config.table(&table.name.to_string());
    let belongs_imports = table
        .foreign_keys
        .iter()
        .map(|fk| {
            format!(
                "use {model_path}{foreign_table_name_model}::{singular_struct_name};",
                foreign_table_name_model = fk.0.to_string().to_snake_case().to_lowercase(),
                singular_struct_name = fk.0.to_string().to_pascal_case().to_singular(),
                model_path = config.model_path
            )
        })
        .collect::<Vec<String>>()
        .join("\n");
    #[cfg(feature = "async")]
    let async_imports = if table_options.get_async() {
        "\nuse diesel_async::RunQueryDsl;"
    } else {
        ""
    };
    #[cfg(not(feature = "async"))]
    let async_imports = "";

    let mut schema_path = config.schema_path.clone();
    schema_path.push('*');

    let serde_imports = if table_options.get_serde() {
        "use serde::{Deserialize, Serialize};"
    } else {
        ""
    };

    let fns_imports = if table_options.get_fns() {
        "\nuse diesel::QueryResult;"
    } else {
        ""
    };

    let connection_type_alias = if table_options.get_fns() {
        format!(
            "\ntype ConnectionType = {connection_type};",
            connection_type = config.connection_type,
        )
    } else {
        "".to_string()
    };

    format!(
        indoc! {"
        use crate::diesel::*;
        use {schema_path};{fns_imports}
        {serde_imports}{async_imports}
        {belongs_imports}
        {connection_type_alias}
    "},
        belongs_imports = belongs_imports,
        async_imports = async_imports,
        schema_path = schema_path,
        serde_imports = serde_imports,
        fns_imports = fns_imports,
        connection_type_alias = connection_type_alias,
    )
    .trim_end()
    .to_string()
}

/// Generate a full file for a given diesel table
pub fn generate_for_table(table: ParsedTableMacro, config: &GenerationConfig) -> String {
    let table_options = config.table(&table.name.to_string());
    // first, we generate struct code
    let read_struct = Struct::new(StructType::Read, &table, config);
    let update_struct = Struct::new(StructType::Update, &table, config);
    let create_struct = Struct::new(StructType::Create, &table, config);

    let mut structs = String::new();
    structs.push_str(read_struct.code());
    structs.push('\n');
    structs.push_str(create_struct.code());
    structs.push('\n');
    structs.push_str(update_struct.code());

    let functions = if table_options.get_fns() {
        build_table_fns(&table, config, create_struct, update_struct)
    } else {
        "".to_string()
    };
    let imports = build_imports(&table, config);

    format!("{FILE_SIGNATURE}\n\n{imports}\n\n{structs}\n{functions}")
}