fraiseql-cli 2.2.0

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
#![allow(clippy::unwrap_used)] // Reason: test/bench code, panics are acceptable
//! Integration tests for TOML-based workflow with all 16 language SDKs
//!
//! This test suite verifies end-to-end compilation for each language:
//! 1. Export types.json from language SDK
//! 2. Create fraiseql.toml with config
//! 3. Run: fraiseql compile fraiseql.toml --types types.json
//! 4. Verify schema.compiled.json contains all features

use std::{fs, process::Command};

use tempfile::TempDir;

#[test]
fn test_toml_workflow_python_sdk() {
    test_sdk_integration(
        "python",
        "User",
        r#"
{
  "types": [
    {
      "name": "User",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "name", "type": "String", "nullable": false}
      ]
    }
  ]
}
"#,
    );
}

#[test]
fn test_toml_workflow_go_sdk() {
    test_sdk_integration(
        "go",
        "Product",
        r#"
{
  "types": [
    {
      "name": "Product",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "price", "type": "Float", "nullable": true}
      ]
    }
  ]
}
"#,
    );
}

#[test]
fn test_toml_workflow_nodejs_sdk() {
    test_sdk_integration(
        "nodejs",
        "Post",
        r#"
{
  "types": [
    {
      "name": "Post",
      "description": "Blog post",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "title", "type": "String", "nullable": false}
      ]
    }
  ]
}
"#,
    );
}

#[test]
fn test_toml_workflow_php_sdk() {
    test_sdk_integration(
        "php",
        "Comment",
        r#"
{
  "types": [
    {
      "name": "Comment",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "text", "type": "String", "nullable": false}
      ]
    }
  ]
}
"#,
    );
}

// Integration test helper
fn test_sdk_integration(sdk_name: &str, type_name: &str, types_json: &str) {
    let temp_dir = TempDir::new().expect("Failed to create temp directory");
    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");

    // 1. Write types.json
    fs::write(&types_path, types_json).expect("Failed to write types.json");

    // 2. Create fraiseql.toml with queries/mutations/security (minimal valid config)
    let toml_config = format!(
        r#"
[schema]
name = "test_schema"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[queries.getItems]
return_type = "{}"
return_array = true
sql_source = "v_{}"

[security]
default_policy = "public"

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#,
        type_name,
        type_name.to_lowercase()
    );

    fs::write(&toml_path, toml_config).expect("Failed to write fraiseql.toml");

    // 3. Run compile command
    // fraiseql compile fraiseql.toml --types types.json --output schema.compiled.json
    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output();

    match output {
        Ok(result) => {
            if !result.status.success() {
                let stderr = String::from_utf8_lossy(&result.stderr);
                let stdout = String::from_utf8_lossy(&result.stdout);
                panic!(
                    "Compilation failed for {}.\nstdout: {}\nstderr: {}",
                    sdk_name, stdout, stderr
                );
            }

            // 4. Verify compiled schema
            let compiled =
                fs::read_to_string(&output_path).expect("Failed to read compiled schema");

            // Check that compiled schema contains types
            assert!(
                compiled.contains("\"types\""),
                "Compiled schema missing types section for {}",
                sdk_name
            );

            // Check that queries are present
            assert!(
                compiled.contains("\"queries\""),
                "Compiled schema missing queries section for {}",
                sdk_name
            );

            // Check that security is present
            assert!(
                compiled.contains("\"security\""),
                "Compiled schema missing security section for {}",
                sdk_name
            );
        },
        Err(e) => {
            panic!("Failed to run fraiseql-cli for {}: {}", sdk_name, e);
        },
    }
}

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

    // types.json from SDK with 2 types
    let types_json = r#"
{
  "types": [
    {
      "name": "User",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "email", "type": "String", "nullable": false}
      ]
    },
    {
      "name": "Post",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "authorId", "type": "ID", "nullable": false}
      ]
    }
  ]
}
"#;

    // fraiseql.toml with queries and mutations
    let toml_config = r#"
[schema]
name = "merged_test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[queries.getUser]
return_type = "User"
return_array = false
sql_source = "v_users"

[queries.getPosts]
return_type = "Post"
return_array = true
sql_source = "v_posts"

[[queries.getUser.args]]
name = "userId"
type = "ID"
required = true

[security]
default_policy = "public"

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#;

    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");

    fs::write(&types_path, types_json).unwrap();
    fs::write(&toml_path, toml_config).unwrap();

    // Compile
    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output()
        .expect("Failed to run compilation");

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        panic!("Compilation failed.\nstdout: {}\nstderr: {}", stdout, stderr);
    }

    // Verify merged result
    let compiled = fs::read_to_string(&output_path).expect("Failed to read compiled schema");

    // Check that both types are in the output
    assert!(compiled.contains("User"), "User type not in compiled schema");
    assert!(compiled.contains("Post"), "Post type not in compiled schema");

    // Check that both queries are in the output
    assert!(compiled.contains("getUser"), "getUser query not in compiled schema");
    assert!(compiled.contains("getPosts"), "getPosts query not in compiled schema");

    // Check that types are arrays, not objects
    let compiled_value: serde_json::Value =
        serde_json::from_str(&compiled).expect("Failed to parse compiled schema as JSON");

    assert!(compiled_value["types"].is_array(), "types should be an array, not object");
    assert!(compiled_value["queries"].is_array(), "queries should be an array, not object");
}

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

    let types_json = r#"
{
  "types": [
    {
      "name": "SecureData",
      "fields": [
        {"name": "id", "type": "ID", "nullable": false},
        {"name": "secret", "type": "String", "nullable": false}
      ]
    }
  ]
}
"#;

    let toml_config = r#"
[schema]
name = "secure_test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]
default_policy = "public"

[[security.rules]]
name = "read_own_data"
rule = "user.id == object.owner_id"
description = "Users can only read their own data"
cacheable = true
cache_ttl_seconds = 300

[[security.policies]]
name = "admin_only"
type = "rbac"
roles = ["admin"]
strategy = "any"
description = "Admins only"
cache_ttl_seconds = 600

[[security.field_auth]]
type_name = "SecureData"
field_name = "secret"
policy = "admin_only"

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#;

    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");

    fs::write(&types_path, types_json).unwrap();
    fs::write(&toml_path, toml_config).unwrap();

    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output()
        .expect("Failed to run compilation");

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        panic!("Compilation failed.\nstdout: {}\nstderr: {}", stdout, stderr);
    }

    let compiled = fs::read_to_string(&output_path).unwrap();
    let compiled_value: serde_json::Value = serde_json::from_str(&compiled).unwrap();

    // Verify security section exists and is properly embedded
    assert!(
        compiled_value.get("security").is_some(),
        "security section missing from compiled schema"
    );

    let security = &compiled_value["security"];
    assert!(
        security.get("default_policy").is_some(),
        "default_policy missing from security config"
    );
    assert!(security.get("rules").is_some(), "rules missing from security config");
    assert!(security.get("policies").is_some(), "policies missing from security config");
}

/// Full CLI compile pipeline with field-level assertions.
///
/// types.json carries `inject` and `cache_ttl_seconds` on a query, and
/// `invalidates_views` on a mutation.  We compile via the CLI binary and then
/// parse the compiled JSON with `CompiledSchema::from_json()` to assert that
/// those fields reach the output unchanged.
#[test]
fn test_field_values_survive_full_cli_pipeline() {
    let temp_dir = TempDir::new().unwrap();

    // types.json in the intermediate format emitted by language SDKs
    let types_json = r#"
{
  "types": [
    {
      "name": "Order",
      "sql_source": "v_order",
      "fields": [
        {"name": "id",     "type": "ID",     "nullable": false},
        {"name": "amount", "type": "Float",  "nullable": false},
        {"name": "status", "type": "String", "nullable": false}
      ]
    }
  ],
  "queries": [
    {
      "name": "orders",
      "return_type": "Order",
      "returns_list": true,
      "nullable": false,
      "sql_source": "v_order",
      "cache_ttl_seconds": 300,
      "inject": {"tenant_id": "jwt:tenant_id"}
    }
  ],
  "mutations": [
    {
      "name": "createOrder",
      "return_type": "Order",
      "sql_source": "fn_create_order",
      "invalidates_views": ["v_order"],
      "inject": {"user_id": "jwt:sub"}
    }
  ]
}
"#;

    let toml_config = r#"
[schema]
name = "field_survival_test"
version = "1.0.0"
database_target = "postgresql"

[database]
url = "postgresql://localhost/test"

[security]
default_policy = "public"

[security.enterprise]
rate_limiting_enabled = false
audit_logging_enabled = false
"#;

    let types_path = temp_dir.path().join("types.json");
    let toml_path = temp_dir.path().join("fraiseql.toml");
    let output_path = temp_dir.path().join("schema.compiled.json");

    fs::write(&types_path, types_json).unwrap();
    fs::write(&toml_path, toml_config).unwrap();

    let cli_path = env!("CARGO_BIN_EXE_fraiseql-cli");
    let output = Command::new(cli_path)
        .args([
            "compile",
            toml_path.to_str().unwrap(),
            "--types",
            types_path.to_str().unwrap(),
            "--output",
            output_path.to_str().unwrap(),
        ])
        .output()
        .expect("Failed to run compilation");

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let stdout = String::from_utf8_lossy(&output.stdout);
        panic!("Compilation failed.\nstdout: {stdout}\nstderr: {stderr}");
    }

    let compiled_json = fs::read_to_string(&output_path).expect("compiled schema missing");
    let schema = fraiseql_core::schema::CompiledSchema::from_json(&compiled_json)
        .expect("compiled schema must parse");

    // Query field survival
    let q = schema.find_query("orders").expect("'orders' query must be present");
    assert_eq!(
        q.sql_source.as_deref(),
        Some("v_order"),
        "query sql_source must survive full CLI pipeline"
    );
    assert_eq!(
        q.cache_ttl_seconds,
        Some(300),
        "cache_ttl_seconds must survive full CLI pipeline"
    );
    assert_eq!(q.inject_params.len(), 1, "inject_params must have one entry");

    // Mutation field survival
    let m = schema
        .find_mutation("createOrder")
        .expect("'createOrder' mutation must be present");
    assert_eq!(
        m.sql_source.as_deref(),
        Some("fn_create_order"),
        "mutation sql_source must survive full CLI pipeline"
    );
    assert_eq!(
        m.invalidates_views,
        vec!["v_order"],
        "invalidates_views must survive full CLI pipeline"
    );
    assert_eq!(m.inject_params.len(), 1, "mutation inject_params must have one entry");
}