prax-orm-cli 0.11.1

CLI tool for the Prax ORM
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
//! Integration tests for the Prax CLI

use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use tempfile::TempDir;

/// Get the prax binary
#[allow(deprecated)]
fn prax_cmd() -> Command {
    Command::cargo_bin("prax").unwrap()
}

#[test]
fn test_help_command() {
    prax_cmd()
        .arg("--help")
        .assert()
        .success()
        .stdout(predicate::str::contains("Prax CLI"))
        .stdout(predicate::str::contains("Usage: prax <COMMAND>"))
        .stdout(predicate::str::contains("init"))
        .stdout(predicate::str::contains("generate"))
        .stdout(predicate::str::contains("migrate"))
        .stdout(predicate::str::contains("db"));
}

#[test]
fn test_version_command() {
    // The workspace version is bumped on every release (see
    // `chore(release): bump workspace to X.Y.Z` commits). Pinning a
    // literal here means this test goes red on every bump; instead
    // read it from the test binary's CARGO_PKG_VERSION so the
    // assertion always reflects the version the CLI actually reports.
    prax_cmd()
        .arg("version")
        .assert()
        .success()
        .stdout(predicate::str::contains("Version"))
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

#[test]
fn test_init_help() {
    prax_cmd()
        .args(["init", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Initialize a new Prax project"))
        .stdout(predicate::str::contains("--provider"));
}

#[test]
fn test_generate_help() {
    prax_cmd()
        .args(["generate", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Generate Rust client code"))
        .stdout(predicate::str::contains("--schema"));
}

#[test]
fn test_migrate_help() {
    prax_cmd()
        .args(["migrate", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("migration commands"))
        .stdout(predicate::str::contains("dev"))
        .stdout(predicate::str::contains("deploy"))
        .stdout(predicate::str::contains("reset"))
        .stdout(predicate::str::contains("status"));
}

#[test]
fn test_db_help() {
    prax_cmd()
        .args(["db", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("database operations"))
        .stdout(predicate::str::contains("push"))
        .stdout(predicate::str::contains("pull"));
}

#[test]
fn test_validate_help() {
    prax_cmd()
        .args(["validate", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("validation"));
}

#[test]
fn test_format_help() {
    prax_cmd()
        .args(["format", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Format schema"));
}

#[test]
fn test_init_creates_project_structure() {
    let temp_dir = TempDir::new().unwrap();
    let project_name = "test_project";

    prax_cmd()
        .current_dir(temp_dir.path())
        .args(["init", project_name, "--yes", "--provider", "postgresql"])
        .assert()
        .success()
        .stdout(predicate::str::contains("initialized successfully"));

    let project_path = temp_dir.path().join(project_name);
    assert!(project_path.exists(), "Project directory should exist");
    // Schema is in prax/ directory
    assert!(
        project_path.join("prax").join("schema.prax").exists(),
        "prax/schema.prax should exist"
    );
    // Config is in project root
    assert!(
        project_path.join("prax.toml").exists(),
        "prax.toml should exist"
    );
    // Migrations are in prax/ directory
    assert!(
        project_path.join("prax").join("migrations").exists(),
        "prax/migrations directory should exist"
    );
    // Note: src directory may not be created immediately, depends on implementation
}

#[test]
fn test_init_with_different_providers() {
    for provider in ["postgresql", "mysql", "sqlite"] {
        let temp_dir = TempDir::new().unwrap();
        let project_name = format!("test_{}", provider);

        prax_cmd()
            .current_dir(temp_dir.path())
            .args(["init", &project_name, "--yes", "--provider", provider])
            .assert()
            .success();

        let config_path = temp_dir.path().join(&project_name).join("prax.toml");
        assert!(config_path.exists());

        let config_content = fs::read_to_string(config_path).unwrap();
        assert!(config_content.contains(provider));
    }
}

#[test]
fn test_validate_with_valid_schema() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("schema.prax");

    let schema_content = r#"
model User {
    id    Int    @id @auto
    name  String
    email String @unique
}
"#;
    fs::write(&schema_path, schema_content).unwrap();

    prax_cmd()
        .args(["validate", "--schema", schema_path.to_str().unwrap()])
        .assert()
        .success()
        .stdout(predicate::str::contains("valid"));
}

#[test]
fn test_validate_with_invalid_schema() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("schema.prax");

    let schema_content = r#"
model User {
    id    Int    @id @auto
    name  String
    email String @unique
    // Missing closing brace
"#;
    fs::write(&schema_path, schema_content).unwrap();

    prax_cmd()
        .args(["validate", "--schema", schema_path.to_str().unwrap()])
        .assert()
        .failure();
}

#[test]
fn test_format_schema() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("schema.prax");

    let schema_content = r#"
datasource db {
  provider = "mysql"
  url = env("DATABASE_URL")
}

model   User{
id Int @id @auto
name String
email String @unique
}
"#;
    fs::write(&schema_path, schema_content).unwrap();

    // Format command should succeed and output the formatted schema
    prax_cmd()
        .args(["format", "--schema", schema_path.to_str().unwrap()])
        .assert()
        .success();

    // Formatting must preserve the declared datasource rather than
    // rewriting it to the old hardcoded postgresql default, and must
    // not inject a generator block the schema never declared.
    let formatted = fs::read_to_string(&schema_path).unwrap();
    assert!(
        formatted.contains("provider = \"mysql\""),
        "format rewrote the datasource provider:\n{formatted}"
    );
    assert!(
        !formatted.contains("postgresql"),
        "format injected a hardcoded postgresql provider:\n{formatted}"
    );
    assert!(
        !formatted.contains("generator client"),
        "format injected a hardcoded generator block:\n{formatted}"
    );
}

#[test]
fn test_generate_missing_schema() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("nonexistent.prax");

    prax_cmd()
        .args(["generate", "--schema", schema_path.to_str().unwrap()])
        .assert()
        .failure();
}

#[test]
fn test_migrate_status_no_config() {
    let temp_dir = TempDir::new().unwrap();

    // Without a prax.toml config, migrate status should fail with an error
    let _result = prax_cmd()
        .current_dir(temp_dir.path())
        .args(["migrate", "status"])
        .assert();

    // It should either fail or report no config found
    // Don't assert on specific error message since implementation may vary
}

#[test]
fn test_invalid_command() {
    prax_cmd()
        .arg("invalid_command")
        .assert()
        .failure()
        .stderr(predicate::str::contains("error"));
}

#[test]
fn test_global_options() {
    // Test --version flag. Same rationale as test_version_command:
    // read the expected version from CARGO_PKG_VERSION so workspace
    // bumps don't require edits to the test literal.
    prax_cmd()
        .arg("--version")
        .assert()
        .success()
        .stdout(predicate::str::contains(env!("CARGO_PKG_VERSION")));
}

/// `prax generate` must emit the trait impls the runtime needs to round-trip
/// rows back into model structs (`FromRow`) and to extract primary key /
/// column values from a model instance (`ModelWithPk`). The per-model
/// operations struct must also be named `Client<E>` so the
/// `prax::client!(...)` macro can find `<snake_name>::Client<E>` by path
/// — same convention as the `#[derive(Model)]` path. Without these the
/// generated code compiles but cannot decode rows or be wired into the
/// `client!` macro, which is the gap this test guards.
#[test]
fn test_generate_emits_runtime_trait_impls_and_client_struct() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("schema.prax");
    let schema_content = r#"
datasource db {
  provider = "postgresql"
  url = "postgres://localhost/test"
}

model User {
  id    Int    @id @auto
  email String @unique
  name  String
}
"#;
    fs::write(&schema_path, schema_content).unwrap();

    let output_dir = temp_dir.path().join("out");
    prax_cmd()
        .args([
            "generate",
            "--schema",
            schema_path.to_str().unwrap(),
            "--output",
            output_dir.to_str().unwrap(),
        ])
        .assert()
        .success();

    let user_module = fs::read_to_string(output_dir.join("user.rs")).expect("user.rs not emitted");

    // FromRow impl present and uses FromColumn to decode each scalar field.
    assert!(
        user_module.contains("impl prax_query::row::FromRow for User"),
        "user.rs missing FromRow impl:\n{user_module}"
    );
    assert!(
        user_module.contains("FromColumn>::from_column(row, \"email\")"),
        "user.rs FromRow does not decode email column:\n{user_module}"
    );

    // ModelWithPk impl present with pk_value and get_column_value.
    assert!(
        user_module.contains("impl prax_query::traits::ModelWithPk for User"),
        "user.rs missing ModelWithPk impl:\n{user_module}"
    );
    assert!(
        user_module.contains("fn pk_value(&self)"),
        "user.rs ModelWithPk missing pk_value:\n{user_module}"
    );
    // prettyplease wraps long signatures; match the function name +
    // first parameter without whitespace-sensitive assertions.
    assert!(
        user_module.contains("fn get_column_value(") && user_module.contains("column: &str"),
        "user.rs ModelWithPk missing get_column_value:\n{user_module}"
    );

    // Operations struct is named `Client<E>` (not `UserOperations<E>`) so
    // `prax::client!` can dispatch via `user::Client::new(...)`.
    assert!(
        user_module.contains("pub struct Client<E: prax_query::QueryEngine>"),
        "user.rs missing per-model Client<E> struct:\n{user_module}"
    );
    assert!(
        !user_module.contains("UserOperations"),
        "user.rs still emits the legacy UserOperations<E> name:\n{user_module}"
    );

    // The top-level client accessor must call `user::Client::new(...)`.
    let mod_rs = fs::read_to_string(output_dir.join("mod.rs")).expect("mod.rs not emitted");
    assert!(
        mod_rs.contains("user::Client::new(self.engine.clone())"),
        "mod.rs accessor not routed through user::Client:\n{mod_rs}"
    );
}

/// Consumer repos run `cargo fmt --check` in CI. Before this change
/// the generator wrote string-concatenated Rust that did not satisfy
/// rustfmt, forcing every consumer to either exclude the generated
/// tree via `rustfmt.toml` or let the fmt drift surface as rework on
/// every PR. Piping through prettyplease gives us:
///
///   1. Parseable output — if `syn::parse_file` rejects the string,
///      a generator bug has landed unformatted Rust (fallback exists
///      but is meant to be unreachable).
///   2. Idempotent formatting — prettyplease is deterministic across
///      rustc versions, so CI can safely gate on its output without
///      a rustfmt-edition lock.
///
/// This test locks both properties by calling the CLI and asserting
/// that every emitted file parses clean and that running prettyplease
/// again produces the same bytes.
#[test]
fn test_generate_emits_prettyplease_formatted_rust() {
    let temp_dir = TempDir::new().unwrap();
    let schema_path = temp_dir.path().join("schema.prax");
    let schema_content = r#"
datasource db {
  provider = "postgresql"
  url = "postgres://localhost/test"
}

model User {
  id    Int    @id @auto
  email String @unique
  name  String
}

model Post {
  id      Int    @id @auto
  title   String
  userId  Int    @map("user_id")
}

enum Role {
  Admin
  Member
}
"#;
    fs::write(&schema_path, schema_content).unwrap();

    let output_dir = temp_dir.path().join("out");
    prax_cmd()
        .args([
            "generate",
            "--schema",
            schema_path.to_str().unwrap(),
            "--output",
            output_dir.to_str().unwrap(),
        ])
        .assert()
        .success();

    // Every emitted .rs must parse as a Rust file and survive a
    // round-trip through prettyplease unchanged. If the assertion
    // fails the generator is emitting shapes syn can't parse or
    // strings prettyplease would re-flow — the whole point of
    // routing through prettyplease is that the output is the
    // canonical form on the first pass.
    let expected_files = [
        "mod.rs",
        "user.rs",
        "post.rs",
        "role.rs",
        "types.rs",
        "filters.rs",
    ];
    for name in expected_files {
        let path = output_dir.join(name);
        let raw = fs::read_to_string(&path)
            .unwrap_or_else(|e| panic!("expected file {} to exist: {}", name, e));
        let parsed = syn::parse_file(&raw)
            .unwrap_or_else(|e| panic!("{} did not parse as Rust:\n{}\nerror: {}", name, raw, e));
        let reformatted = prettyplease::unparse(&parsed);
        assert_eq!(
            raw, reformatted,
            "{} is not prettyplease-stable: the generator emitted a shape \
             prettyplease re-flowed on the second pass",
            name
        );
    }
}

#[test]
fn test_import_prisma_directory_creates_mirrored_prax_directory() {
    let input = TempDir::new().unwrap();
    fs::create_dir_all(input.path().join("models")).unwrap();
    fs::write(
        input.path().join("schema.prisma"),
        r#"datasource db { provider = "postgresql" url = env("X") }"#,
    )
    .unwrap();
    fs::write(
        input.path().join("models/u.prisma"),
        "model U { id Int @id @default(autoincrement()) }",
    )
    .unwrap();

    let output_dir = TempDir::new().unwrap();
    prax_cmd()
        .arg("import")
        .arg("--from")
        .arg("prisma")
        .arg("--input")
        .arg(input.path())
        .arg("--output")
        .arg(output_dir.path())
        .arg("--force")
        .assert()
        .success();

    assert!(output_dir.path().join("schema.prax").exists());
    assert!(output_dir.path().join("models/u.prax").exists());
}