autumn-cli 0.8.0

CLI tool for the Autumn web framework
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
//! Scaffold support for declarative counter caches (issue #1325).
//!
//! `autumn generate scaffold comment body:text post:references --belongs-to Post
//! --counter-cache` adds, on top of the ordinary `--belongs-to` scaffold:
//!
//! 1. `#[belongs_to(Post, counter_cache)]` on the generated child model, which
//!    is what makes `PgCommentRepository` maintain the column; and
//! 2. a migration adding `comment_count BIGINT NOT NULL DEFAULT 0` to the
//!    parent's table, with a `DROP COLUMN` down.
//!
//! `NOT NULL DEFAULT 0` is load-bearing rather than tidy: the maintenance is
//! `SET c = c + 1`, and `NULL + 1` is `NULL`.
//!
//! The parent's `src/schema.rs` block and model struct also need the column, but
//! both are files this invocation does not own and neither has a marker-delimited
//! revert. Rather than make `autumn destroy scaffold` unable to take them back
//! out, the plan surfaces the two exact lines to paste as a warning.

use std::path::Path;

use crate::generate::emit::Plan;

/// The parent column a counter-cached child maintains, matching `#[model]`'s
/// convention: `{snake(child)}_count` — deliberately singular, mirroring
/// `#[votable(aggregate = count)]`'s `{name}_count`.
#[must_use]
pub fn counter_column_for(child_snake: &str) -> String {
    format!("{child_snake}_count")
}

/// `up.sql` adding the counter column to the parent table.
#[must_use]
pub fn up_sql(parent_plural: &str, column: &str) -> String {
    format!("ALTER TABLE {parent_plural} ADD COLUMN {column} BIGINT NOT NULL DEFAULT 0;\n")
}

/// `down.sql` removing it again.
#[must_use]
pub fn down_sql(parent_plural: &str, column: &str) -> String {
    format!("ALTER TABLE {parent_plural} DROP COLUMN {column};\n")
}

/// The migration directory name, e.g.
/// `202604270000001_add_comment_count_to_posts`.
///
/// Diesel takes the prefix as the migration **version**, and the scaffold has
/// already claimed `{timestamp}` for its own `{timestamp}_create_{table}`. Two
/// directories sharing a version cannot both be recorded in
/// `__diesel_schema_migrations`, so one of the two schema changes would silently
/// never apply.
#[must_use]
pub fn migration_dir_name(timestamp: &str, column: &str, parent_plural: &str) -> String {
    format!(
        "{}_add_{column}_to_{parent_plural}",
        next_migration_version(timestamp)
    )
}

/// The version to run this migration at: `{timestamp}` with a `1` appended.
///
/// The obvious choice — `timestamp + 1` — is wrong in a way that only shows up
/// later: it *reserves* the version a scaffold run one second afterwards would
/// naturally take, so that run's `{timestamp}_create_{table}` collides with this
/// directory and one of the two never applies. The bug lands in a different
/// invocation than the one that caused it.
///
/// Appending a digit instead never consumes a wall-clock version. Diesel's
/// `MigrationVersion` is `Ord` over the raw string, so lexicographic ordering is
/// what matters, and a suffixed version sorts exactly where it should:
///
/// * after its own scaffold (`20260427000000` is a prefix of
///   `202604270000001`, and a prefix sorts first), so the parent column is added
///   after the child table exists; and
/// * before the next second's scaffold — `{timestamp}` and `{timestamp + 1}`
///   first differ at some index inside the timestamp, where the later one is
///   greater, and the appended digit sits beyond that index.
///
/// It also needs no knowledge of the timestamp's format, so a non-numeric one
/// (tests, a stubbed clock) is handled by the same single code path.
fn next_migration_version(timestamp: &str) -> String {
    format!("{timestamp}1")
}

/// Push the counter-cache migration's `up.sql`/`down.sql` onto `plan`.
///
/// `plan` already carries the child's model/migration/schema actions; this adds
/// the parent-side column. The child model's `#[belongs_to(..., counter_cache)]`
/// attribute is added separately, by rewriting the model file the plan is about
/// to create (see [`add_counter_cache_to_model_source`]).
///
/// Pushed on a **revert** plan too, and that is load-bearing: `Plan::revert`
/// discovers the migration directories it may remove from the plan's `Create`
/// actions under `migrations/`, so omitting these two would leave the
/// `*_add_{column}_to_{parents}` directory behind after `autumn destroy
/// scaffold`, where a later `migrate` run would then alter a parent table whose
/// child scaffold no longer exists. Only the follow-up warning is
/// generate-only — see [`push_counter_cache_warning`].
pub fn push_counter_cache_migration(
    plan: &mut Plan,
    project_root: &Path,
    timestamp: &str,
    child_snake: &str,
    parent_plural: &str,
) {
    let column = counter_column_for(child_snake);
    let dir =
        project_root
            .join("migrations")
            .join(migration_dir_name(timestamp, &column, parent_plural));
    plan.create(dir.join("up.sql"), up_sql(parent_plural, &column));
    plan.create(dir.join("down.sql"), down_sql(parent_plural, &column));
}

/// The two lines the author has to add by hand, surfaced as a plan warning.
///
/// The parent's `src/schema.rs` block and model struct need the column, but both
/// are files this invocation does not own and neither has a marker-delimited
/// revert — editing them would make `autumn destroy scaffold` unable to take
/// them back out.
pub fn push_counter_cache_warning(
    plan: &mut Plan,
    child_snake: &str,
    parent_pascal: &str,
    parent_plural: &str,
) {
    let column = counter_column_for(child_snake);
    plan.warn(format!(
        "--counter-cache: `{parent_plural}.{column}` is added by the generated \
         migration, but the parent's Rust side is a file this scaffold does not \
         own, so it is left to you (two lines, both required before the app \
         compiles):\n  \
         src/schema.rs, inside `diesel::table! {{ {parent_plural} (id) {{ … }} }}`:\n    \
         {column} -> Int8,\n  \
         the `{parent_pascal}` model struct:\n    \
         #[default]\n    pub {column}: i64,\n  \
         Then run `{child_snake}s.recompute_counter_caches()` once if \
         `{parent_plural}` already has rows."
    ));
}

/// `#[autumn_web::model]` is always the first attribute `render_model_file`
/// emits, and rustc applies stacked attribute macros top-down — so anything
/// below `#[model]` reaches its expansion as an inert helper attribute, while
/// anything above it rustc tries to resolve as a standalone macro and fails
/// with "cannot find attribute `belongs_to` in this scope" (issue #2431).
const MODEL_ATTR: &str = "#[autumn_web::model]\n";

/// Insert `counter_cache` into the child model source's `#[belongs_to(...)]`
/// attribute, adding the attribute (and the `use` imports its expansion
/// needs) when the scaffold did not emit one.
///
/// Returns `source` unchanged when the attribute is already counter-cached, so
/// re-running the scaffold over its own output is idempotent.
#[must_use]
pub fn add_counter_cache_to_model_source(
    source: &str,
    pascal_name: &str,
    parent_pascal: &str,
    parent_snake: &str,
    parent_plural: &str,
) -> String {
    let existing = format!("#[belongs_to({parent_pascal}");
    if let Some(start) = source.find(&existing) {
        // An attribute for this parent is already present. Leave it alone if it
        // already opts in; otherwise add the key before the closing paren.
        let Some(end_rel) = source[start..].find(")]") else {
            return source.to_owned();
        };
        let end = start + end_rel;
        if source[start..end].contains("counter_cache") {
            return source.to_owned();
        }
        let mut out = String::with_capacity(source.len() + 16);
        out.push_str(&source[..end]);
        out.push_str(", counter_cache");
        out.push_str(&source[end..]);
        return out;
    }

    // No `belongs_to` on the generated model (the flat scaffold does not emit
    // one): add the whole attribute right after `#[autumn_web::model]`.
    // Anchoring on that literal line, rather than "whatever attribute line
    // sits closest to the struct," is what keeps this correct once other
    // struct-level attributes (`#[commentable]`, `#[searchable]`,
    // `#[shard_key]`) are also stacked between it and `pub struct` — a prior
    // version walked back to the wrong end of that stack and landed the new
    // attribute above `#[model]` on every real scaffold.
    let needle = format!("pub struct {pascal_name} ");
    let Some(struct_at) = source.find(&needle) else {
        return source.to_owned();
    };
    let insert_at = source[..struct_at]
        .find(MODEL_ATTR)
        .map_or(struct_at, |i| i + MODEL_ATTR.len());
    let mut out = String::with_capacity(source.len() + 48);
    out.push_str(&source[..insert_at]);
    out.push_str("#[belongs_to(");
    out.push_str(parent_pascal);
    out.push_str(", counter_cache)]\n");
    out.push_str(&source[insert_at..]);
    add_belongs_to_imports(&out, parent_pascal, parent_snake, parent_plural)
}

/// `#[belongs_to(Parent, ...)]` is not just consumed by `#[model]`'s own
/// expansion — the eager-loading codegen it drives emits real references to
/// the target type (`Preloaded<Parent>`, `<Parent as Preloadable>::Spec`, …)
/// and its Diesel schema module (`parents::table`, `parents::id`, …). The
/// flat scaffold's OWN table is already imported (`use
/// crate::schema::{table};`, from `render_model_file`), but nothing before
/// `--counter-cache` ever put an attribute-driven association on a model, so
/// the PARENT's type and schema module were never in scope — `cargo check`
/// fails with "cannot find type `Parent`" / "unresolved module `parents`"
/// otherwise. Both imports are added right next to the child's own, matching
/// the `use crate::schema::{table};` convention already there.
fn add_belongs_to_imports(
    source: &str,
    parent_pascal: &str,
    parent_snake: &str,
    parent_plural: &str,
) -> String {
    let schema_import = format!("use crate::schema::{parent_plural};\n");
    let model_import = format!("use crate::models::{parent_snake}::{parent_pascal};\n");
    // Idempotent: a `--force` re-run over output that already carries these
    // (e.g. this same model belongs to two parents, or was regenerated)
    // must not stack duplicate `use` lines.
    if source.contains(&schema_import) && source.contains(&model_import) {
        return source.to_owned();
    }
    let own_schema_import = "use crate::schema::";
    let Some(own_start) = source.find(own_schema_import) else {
        // Defensive: `render_model_file` always emits this line, but if a
        // hand-edited model dropped it, fall back to just above `#[model]`
        // rather than silently skipping imports the generated code needs.
        // Guarded the same way as the normal path below, so this stays
        // idempotent even if only one of the two imports is already there.
        let mut prefix = String::new();
        if !source.contains(&schema_import) {
            prefix.push_str(&schema_import);
        }
        if !source.contains(&model_import) {
            prefix.push_str(&model_import);
        }
        return source.replacen(MODEL_ATTR, &format!("{prefix}{MODEL_ATTR}"), 1);
    };
    let Some(line_end_rel) = source[own_start..].find('\n') else {
        return source.to_owned();
    };
    let insert_at = own_start + line_end_rel + 1;
    let mut out = String::with_capacity(source.len() + schema_import.len() + model_import.len());
    out.push_str(&source[..insert_at]);
    if !source.contains(&schema_import) {
        out.push_str(&schema_import);
    }
    if !source.contains(&model_import) {
        out.push_str(&model_import);
    }
    out.push_str(&source[insert_at..]);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_migration_is_not_null_with_a_zero_default() {
        let up = up_sql("posts", "comment_count");
        assert!(up.contains("ALTER TABLE posts ADD COLUMN comment_count BIGINT"));
        assert!(up.contains("NOT NULL"), "up.sql: {up}");
        assert!(up.contains("DEFAULT 0"), "up.sql: {up}");
        assert_eq!(
            down_sql("posts", "comment_count"),
            "ALTER TABLE posts DROP COLUMN comment_count;\n"
        );
    }

    #[test]
    fn the_column_name_follows_the_singular_convention() {
        assert_eq!(counter_column_for("comment"), "comment_count");
        assert_eq!(counter_column_for("blog_post"), "blog_post_count");
    }

    #[test]
    fn the_migration_dir_names_both_sides() {
        assert_eq!(
            migration_dir_name("20260427000000", "comment_count", "posts"),
            "202604270000001_add_comment_count_to_posts"
        );
    }

    #[test]
    fn the_counter_migration_gets_its_own_diesel_version() {
        // Diesel keys `__diesel_schema_migrations` on the prefix, so sharing the
        // scaffold's `{timestamp}_create_{table}` version would mean one of the
        // two schema changes never applies.
        let scaffold_version = "20260427000000";
        let dir = migration_dir_name(scaffold_version, "comment_count", "posts");
        let version = dir.split('_').next().expect("a version prefix");
        assert_ne!(version, scaffold_version);
        assert!(
            version > scaffold_version,
            "the parent column is added after the child table exists"
        );
    }

    #[test]
    fn the_counter_version_does_not_claim_a_later_scaffolds_timestamp() {
        // `timestamp + 1` would reserve the version a scaffold run one second
        // later takes for its own create-table migration, breaking *that* run.
        let this_second = "20260427000000";
        let next_second = "20260427000001";
        let ours = next_migration_version(this_second);
        assert_ne!(ours, next_second);
        assert!(ours.as_str() > this_second, "sorts after its own scaffold");
        assert!(
            ours.as_str() < next_second,
            "and before the next second's scaffold"
        );
        // Including across a carry in the timestamp's minute field.
        assert!(next_migration_version("20260427005959").as_str() < "20260427010000");
    }

    #[test]
    fn a_non_numeric_timestamp_still_gets_a_distinct_version() {
        assert_eq!(next_migration_version("not-a-number"), "not-a-number1");
    }

    #[test]
    fn the_attribute_is_added_above_the_struct_when_absent() {
        let src = "#[autumn_web::model]\npub struct Comment {\n    pub id: i64,\n}\n";
        let out = add_counter_cache_to_model_source(src, "Comment", "Post", "post", "posts");
        assert!(
            out.contains(
                "#[autumn_web::model]\n#[belongs_to(Post, counter_cache)]\npub struct Comment"
            ),
            "{out}"
        );
    }

    #[test]
    fn an_existing_attribute_gains_the_key_and_is_idempotent() {
        let src = "#[autumn_web::model]\n#[belongs_to(Post)]\npub struct Comment {\n}\n";
        let once = add_counter_cache_to_model_source(src, "Comment", "Post", "post", "posts");
        assert!(
            once.contains("#[belongs_to(Post, counter_cache)]"),
            "{once}"
        );
        let twice = add_counter_cache_to_model_source(&once, "Comment", "Post", "post", "posts");
        assert_eq!(once, twice, "re-running the scaffold must not stack keys");
    }

    /// Issue #2431: `#[belongs_to(Post, ...)]` is not just a marker for
    /// `#[model]` to notice — the eager-loading codegen it drives references
    /// `Post` (the type) and `posts` (the Diesel schema module) directly, and
    /// neither was ever imported into the child's model file before
    /// `--counter-cache` put the first attribute-driven association on a
    /// generated model. Without both imports `cargo check` fails with
    /// "cannot find type `Post`" / "unresolved module `posts`" even once the
    /// attribute sits in the right place.
    #[test]
    fn the_parent_type_and_schema_module_are_imported() {
        let src = "use crate::schema::comments;\n\n#[autumn_web::model]\npub struct Comment {\n}\n";
        let out = add_counter_cache_to_model_source(src, "Comment", "Post", "post", "posts");
        assert!(
            out.contains("use crate::schema::posts;\n"),
            "the parent's schema module must be imported: {out}"
        );
        assert!(
            out.contains("use crate::models::post::Post;\n"),
            "the parent's model type must be imported: {out}"
        );
        // Re-running must not stack duplicate `use` lines.
        let twice = add_counter_cache_to_model_source(&out, "Comment", "Post", "post", "posts");
        assert_eq!(
            twice.matches("use crate::schema::posts;").count(),
            1,
            "{twice}"
        );
        assert_eq!(
            twice.matches("use crate::models::post::Post;").count(),
            1,
            "{twice}"
        );
    }

    /// Issue #2431: the real scaffold output is never as bare as the fixture
    /// above — `render_model_file` always puts a blank line (the `use
    /// crate::schema::...;` line, then an empty line) between the doc header
    /// and `#[autumn_web::model]`. That blank line is what the old
    /// `rfind("\n#[")` walk-back latched onto: it found the newline
    /// immediately before `#[autumn_web::model]` itself and inserted the new
    /// attribute there, landing it ABOVE `#[model]` instead of below it —
    /// which is exactly the `cannot find attribute belongs_to in this scope`
    /// build break from the issue. `#[belongs_to]` is a helper attribute
    /// `#[model]`'s own expansion understands; rustc only accepts it below
    /// `#[model]`, never above.
    #[test]
    fn the_attribute_lands_below_model_even_with_a_leading_use_statement() {
        let src = "//! Generated by `autumn generate`.\n\
                    //!\n\
                    //! Edit this file freely.\n\n\
                    use crate::schema::comments;\n\n\
                    #[autumn_web::model]\n\
                    pub struct Comment {\n    \
                        #[id]\n    pub id: i64,\n\
                    }\n";
        let out = add_counter_cache_to_model_source(src, "Comment", "Post", "post", "posts");
        let model_pos = out
            .find("#[autumn_web::model]")
            .expect("model attribute kept");
        let belongs_to_pos = out
            .find("#[belongs_to(Post, counter_cache)]")
            .expect("belongs_to attribute added");
        assert!(
            model_pos < belongs_to_pos,
            "#[belongs_to] must sit below #[autumn_web::model], not above it (rustc \
             resolves helper attributes top-down): {out}"
        );
        assert!(
            out.contains(
                "#[autumn_web::model]\n#[belongs_to(Post, counter_cache)]\npub struct Comment"
            ),
            "{out}"
        );
    }

    /// A model carrying other struct-level attributes (`#[searchable]` here,
    /// standing in for `#[commentable]`/`#[shard_key]` too) must still get
    /// `#[belongs_to]` below `#[model]` — order among those other helper
    /// attributes doesn't matter to the macro (it looks each one up by
    /// ident), so anchoring on `#[autumn_web::model]` itself must not
    /// disturb them.
    #[test]
    fn the_attribute_lands_below_model_when_other_struct_attributes_follow_it() {
        let src = "use crate::schema::comments;\n\n\
                    #[autumn_web::model]\n\
                    #[searchable(language = \"english\")]\n\
                    pub struct Comment {\n    \
                        #[id]\n    pub id: i64,\n\
                    }\n";
        let out = add_counter_cache_to_model_source(src, "Comment", "Post", "post", "posts");
        assert!(
            out.contains(
                "#[autumn_web::model]\n#[belongs_to(Post, counter_cache)]\n#[searchable(language = \"english\")]\npub struct Comment"
            ),
            "{out}"
        );
    }
}