puerto 0.21.0

Puerto — Rust full-stack DDD framework CLI. Scaffolds Clean Architecture projects with auto-wired DI, SQLx support, and zero manual wiring. Formerly puerto-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
use crate::generators::layout::{self, Layer};
use std::path::Path;

use crate::generators::crates::ContextDeps;
use crate::generators::domain::push_reference_imports;
use crate::generators::effective_fields;
use crate::generators::migration::run_create_table_migration;
use crate::generators::naming::{
    entity_ctx, pascal_to_snake, pluralize, to_pascal_case, write_file,
};
use crate::generators::render::{RenderError, render};
use crate::generators::types::{
    FieldCtx, field_ctx, is_enum_vo, is_reference, is_value_object, literal_names_vo, reference_id,
    resolve_type, seed_literal, vo_import_path,
};
use crate::puerto_toml::{Field, ValueObjectDefinition};

// ── SQL helpers ───────────────────────────────────────────────────────────────

fn sql_ddl_col(name: &str, field_type: &str) -> String {
    let mapping = resolve_type(field_type).unwrap();
    let sql_base = match mapping.sql_type {
        "DOUBLE" => "DOUBLE PRECISION",
        other => other,
    };
    if mapping.sql_nullable {
        format!("    {name} {sql_base}")
    } else {
        let suffix = match mapping.sql_type {
            "TEXT[]" | "BIGINT[]" => " NOT NULL DEFAULT '{}'",
            "JSONB" => " NOT NULL DEFAULT '{}'",
            _ => " NOT NULL",
        };
        format!("    {name} {sql_base}{suffix}")
    }
}

fn sql_col_list(eff: &[Field]) -> String {
    let custom: String = eff.iter().map(|f| format!(", {}", f.name)).collect();
    format!("id, creado_en, actualizado_en, borrado, borrado_en{custom}")
}

/// `HashMap<String, String>` maps to a JSONB column. sqlx has no `HashMap` codec: the row field is
/// `sqlx::types::Json<HashMap<…>>` and `query_as!` needs the column's type overridden to match.
const MAP_TYPE: &str = "HashMap<String, String>";

/// The `SELECT` column list — like [`sql_col_list`], with JSONB columns type-overridden.
fn sql_select_list(eff: &[Field]) -> String {
    let custom: String = eff
        .iter()
        .map(|f| {
            if f.field_type == MAP_TYPE {
                // Emitted inside the query's string literal, hence the escaped quotes.
                format!(r#", {name} as \"{name}: Json<{MAP_TYPE}>\""#, name = f.name)
            } else {
                format!(", {}", f.name)
            }
        })
        .collect();
    format!("id, creado_en, actualizado_en, borrado, borrado_en{custom}")
}

fn sql_params_list(n: usize) -> String {
    let custom: String = (6..=n).map(|i| format!(", ${i}")).collect();
    format!("$1, $2, $3, $4, $5{custom}")
}

/// The `WHERE` of the list's page (`first` = 3, after `LIMIT` and `OFFSET`) or of its `COUNT`
/// (`first` = 1): live rows, then one `($n::uuid IS NULL OR field = $n)` per reference (18.4).
fn sql_list_where(eff: &[Field], first: usize) -> String {
    let filters: String = eff
        .iter()
        .filter(|f| is_reference(f))
        .enumerate()
        .map(|(i, f)| {
            let n = first + i;
            format!(" AND (${n}::uuid IS NULL OR {} = ${n})", f.name)
        })
        .collect();
    format!("borrado = false{filters}")
}

fn sql_conflict_set(eff: &[Field]) -> String {
    let custom: String = eff
        .iter()
        .enumerate()
        .map(|(i, f)| format!(", {} = ${}", f.name, 6 + i))
        .collect();
    format!("actualizado_en = $3, borrado = $4, borrado_en = $5{custom}")
}

// ── Dynamic generators ────────────────────────────────────────────────────────

pub fn generate_infra_entity(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<String, RenderError> {
    let eff = effective_fields(fields);

    let mut imports: Vec<String> = vec![];
    if eff.iter().any(|f| f.field_type == MAP_TYPE) {
        imports.push("sqlx::types::Json".to_string());
        imports.push("std::collections::HashMap".to_string());
    }
    for f in eff.iter().filter(|f| is_value_object(f)) {
        let import = vo_import_path(f, snake, shared_vos, false);
        if !imports.contains(&import) {
            imports.push(import);
        }
    }
    push_reference_imports(&mut imports, &eff);

    let mut ctx = entity_ctx(pascal, snake);
    ctx.insert("imports", &imports);
    ctx.insert("fields", &field_ctxs(&eff, pascal, shared_vos));
    render("infrastructure/entity.tera", &ctx)
}

pub fn generate_crud_infra_db_repository(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
    events: bool,
) -> Result<String, RenderError> {
    let mut ctx = pg_crud_ctx(pascal, snake, fields, shared_vos);
    ctx.insert("events", &events);
    render("infrastructure/repository_pg_crud.tera", &ctx)
}

/// `pruebas/siembra.rs` of a Postgres infrastructure crate: `build` and `seed`, for its tests and
/// for those of the contexts that reference it (ADR-0023 § 5).
pub fn generate_pg_seed(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
    events: bool,
) -> Result<String, RenderError> {
    let mut ctx = pg_crud_ctx(pascal, snake, fields, shared_vos);
    ctx.insert("events", &events);
    render("infrastructure/siembra.tera", &ctx)
}

/// `contextos/{snake}/infraestructura/src/unit_of_work.rs`: the upsert the Pg repository has in a project
/// without events, inside a `puerto_sqlx::uow::TransaccionPostgres`.
pub fn generate_pg_unit_of_work(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<String, RenderError> {
    render(
        "infrastructure/unit_of_work_pg.tera",
        &pg_crud_ctx(pascal, snake, fields, shared_vos),
    )
}

/// What the Pg repository and the Pg unit of work render from: the SQL of the entity's table,
/// and the seed its integration tests build.
fn pg_crud_ctx(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    let eff = effective_fields(fields);

    // SQL text stays a Rust computation: the `$n` numbering is index-dependent.
    let mut ctx = seed_ctx(pascal, snake, fields, shared_vos);
    // A row's references must exist: it is seeded with a target seeded first, through the
    // target's own repository tests (transitively, for the target's own references).
    let mut field_ctxs = field_ctxs(&eff, pascal, shared_vos);
    for f in field_ctxs
        .iter_mut()
        .filter(|f| f.is_ref && !f.field_type.starts_with("Option<"))
    {
        f.seed_literal = format!(
            "infra_{}::pruebas::siembra::sembrar(pool).await.id",
            f.ref_target_snake
        );
    }
    ctx.insert("fields", &field_ctxs);
    let table = pluralize(snake);
    let references: Vec<serde_json::Value> = eff
        .iter()
        .filter(|f| is_reference(f))
        .map(|f| {
            serde_json::json!({
                "constraint": foreign_key_name(&table, &f.name),
                "field": f.name,
                "id": reference_id(f),
                "import": crate::generators::types::reference_import(f),
                "optional": f.field_type.starts_with("Option<"),
            })
        })
        .collect();
    ctx.insert("references", &references);
    let mut reference_imports = vec![];
    push_reference_imports(&mut reference_imports, &eff);
    ctx.insert("reference_imports", &reference_imports);
    ctx.insert(
        "seeds_references",
        &eff.iter()
            .any(|f| is_reference(f) && !f.field_type.starts_with("Option<")),
    );
    // The VO the update test sets, when the field it updates is one (the seed's own imports are
    // `pruebas::siembra`'s).
    let update_vo_import = eff
        .iter()
        .find(|f| f.field_type == "String" && !is_value_object(f) && !is_reference(f))
        .is_none()
        .then(|| {
            eff.iter()
                .find(|f| is_value_object(f) && !is_enum_vo(f) && f.field_type == "String")
        })
        .flatten()
        .map(|f| vo_import_path(f, snake, shared_vos, false));
    ctx.insert("update_vo_import", &update_vo_import);
    ctx.insert("all_cols", &sql_col_list(&eff));
    ctx.insert("select_cols", &sql_select_list(&eff));
    ctx.insert("has_map", &eff.iter().any(|f| f.field_type == MAP_TYPE));
    ctx.insert("all_params", &sql_params_list(5 + eff.len()));
    ctx.insert("all_updates", &sql_conflict_set(&eff));
    ctx.insert("page_where", &sql_list_where(&eff, 3));
    ctx.insert("count_where", &sql_list_where(&eff, 1));
    ctx
}

/// The entity's fields and what a repository test needs to build one from their seeds.
fn seed_ctx(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> tera::Context {
    seed_ctx_with(pascal, snake, fields, shared_vos, &[])
}

/// [`seed_ctx`] with more test imports.
fn seed_ctx_with(
    pascal: &str,
    snake: &str,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
    more_test_imports: &[String],
) -> tera::Context {
    let eff = effective_fields(fields);

    // The seed names every plain and enum VO it constructs (`Name::new(…)`, `Status::Active`);
    // Option/Vec VOs are seeded as `None` / `vec![]` and need no import.
    let mut test_imports: Vec<String> = vec![];
    for f in eff.iter().filter(|f| literal_names_vo(f)) {
        let import = vo_import_path(f, snake, shared_vos, false);
        if !test_imports.contains(&import) {
            test_imports.push(import);
        }
    }
    // A `Uuid` field and every `unique` seed draw on `Uuid::new_v4()`; the file itself names no
    // `Uuid` since ids are `{Entity}Id`.
    if eff.iter().any(|f| seed_literal(f).contains("Uuid::")) {
        test_imports.push("uuid::Uuid".to_string());
    }
    for import in more_test_imports {
        if !test_imports.contains(import) {
            test_imports.push(import.clone());
        }
    }

    let mut ctx = entity_ctx(pascal, snake);
    ctx.insert("test_imports", &test_imports);
    ctx.insert("fields", &field_ctxs(&eff, pascal, shared_vos));
    ctx
}

fn field_ctxs(eff: &[Field], pascal: &str, shared_vos: &[ValueObjectDefinition]) -> Vec<FieldCtx> {
    eff.iter()
        .map(|f| field_ctx(f, pascal, shared_vos))
        .collect()
}

/// The name of a reference's foreign key — the one the repository maps back to its field.
fn foreign_key_name(table: &str, field: &str) -> String {
    format!("{table}_{field}_fkey")
}

pub fn create_table_sql(snake: &str, fields: &[Field]) -> String {
    let eff = effective_fields(fields);
    let table = pluralize(snake);
    let custom_cols: String = eff
        .iter()
        .map(|f| match f.references.as_deref() {
            // ADR-0022: the database checks the target exists, under a name the repository maps.
            Some(target) => format!(
                "{} CONSTRAINT {} REFERENCES {} (id),",
                sql_ddl_col(&f.name, &f.field_type),
                foreign_key_name(&table, &f.name),
                pluralize(&pascal_to_snake(target)),
            ),
            None => format!("{},", sql_ddl_col(&f.name, &f.field_type)),
        })
        .collect::<Vec<_>>()
        .join("\n");

    let mut sql = format!(
        "CREATE TABLE {table} (\n    id UUID PRIMARY KEY,\n{custom_cols}\n    creado_en TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n    actualizado_en TIMESTAMPTZ NOT NULL DEFAULT NOW(),\n    borrado BOOLEAN NOT NULL DEFAULT FALSE,\n    borrado_en TIMESTAMPTZ\n);\n",
    );

    // `unique = true` (the `!` suffix in the CLI) is documented as producing a DB constraint but
    // used to stop at puerto.toml. A named index rather than an inline `UNIQUE` on the column:
    // the column definitions stay uniform, and a later migration can drop the constraint by a
    // name it can predict.
    let unique_indexes: String = eff
        .iter()
        .filter(|f| f.unique)
        .map(|f| {
            let name = &f.name;
            // Partial: rows are soft-deleted, and a deleted row must not keep its value taken.
            format!(
                "\nCREATE UNIQUE INDEX {table}_{name}_key ON {table} ({name}) WHERE borrado = false;\n"
            )
        })
        .collect();
    sql.push_str(&unique_indexes);

    // A reference is what its entity is looked up by; a unique one already has its index.
    let reference_indexes: String = eff
        .iter()
        .filter(|f| f.references.is_some() && !f.unique)
        .map(|f| {
            let name = &f.name;
            format!("\nCREATE INDEX {table}_{name}_idx ON {table} ({name});\n")
        })
        .collect();
    sql.push_str(&reference_indexes);
    sql
}

/// The context's infrastructure crate: the in-memory repository, or the Postgres row, repository,
/// unit of work (`events` projects) and test seeds — then its `Cargo.toml` and `lib.rs`.
pub fn write_repository_files(
    pascal: &str,
    snake: &str,
    base: &Path,
    db: bool,
    fields: &[Field],
    shared_vos: &[ValueObjectDefinition],
) -> Result<(), Box<dyn std::error::Error>> {
    let events = crate::puerto_toml::events_enabled(base);
    if db {
        write_file(
            &base.join(layout::infra_file(snake, "fila")),
            &generate_infra_entity(pascal, snake, fields, shared_vos)?,
        )?;
        write_file(
            &base.join(layout::infra_file(snake, "repositorio")),
            &generate_crud_infra_db_repository(pascal, snake, fields, shared_vos, events)?,
        )?;
        let unit_of_work = base.join(layout::infra_file(snake, "unit_of_work"));
        if events {
            write_file(
                &unit_of_work,
                &generate_pg_unit_of_work(pascal, snake, fields, shared_vos)?,
            )?;
        }
        write_file(
            &base.join(layout::infra_file(snake, "pruebas/siembra")),
            &generate_pg_seed(pascal, snake, fields, shared_vos, events)?,
        )?;
    } else {
        write_file(
            &base.join(layout::infra_file(snake, "repositorio")),
            &render(
                "infrastructure/repository_inmemory_crud.tera",
                // A reference is seeded, and filtered by, `CustomerId::generate()`: nothing
                // checks it.
                &seed_ctx_with(pascal, snake, fields, shared_vos, &{
                    let mut imports = vec![];
                    push_reference_imports(&mut imports, &effective_fields(fields));
                    imports
                }),
            )?,
        )?;
    }
    crate::generators::crates::finish(
        base,
        snake,
        Layer::Infrastructure,
        &ContextDeps::read(base, fields),
    )
}

pub fn run_generate_repository(name: &str, base: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let config = crate::puerto_toml::read(base)?;
    let pascal = to_pascal_case(name);
    let snake = pascal_to_snake(&pascal);

    if !config.entity.iter().any(|e| e.name == pascal) {
        return Err(format!(
            "{pascal} not found in puerto.toml. Run `puerto generar dominio {pascal}` first."
        )
        .into());
    }

    let db = config.project.db;
    let shared_vos = config.value_object.clone();
    let fields = config
        .entity
        .iter()
        .find(|e| e.name == pascal)
        .map(|e| e.fields.clone())
        .unwrap_or_default();

    write_repository_files(&pascal, &snake, base, db, &fields, &shared_vos)?;

    if db {
        run_create_table_migration(&snake, base, &create_table_sql(&snake, &fields))?;
    }

    let repo_label = if db {
        format!("Repositorio{pascal}Postgres")
    } else {
        format!("Repositorio{pascal}EnMemoria")
    };
    println!(
        "✓ {}/ — {repo_label}",
        layout::crate_dir(&snake, Layer::Infrastructure)
    );
    println!();
    println!("  Next: puerto generar presentacion {pascal}");
    Ok(())
}