fraiseql-cli 2.3.2

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
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
use std::{fs, path::Path, process::Command};

use anyhow::{Context, Result};
use tracing::info;

use super::{InitConfig, Language};

/// Create the language-specific authoring skeleton for the project.
///
/// # Errors
///
/// Propagates any file-system errors from the language-specific skeleton creator.
pub(super) fn create_authoring_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    match config.language {
        Language::Python => create_python_skeleton(project_dir, config),
        Language::TypeScript => create_typescript_skeleton(project_dir, config),
        Language::Rust => create_rust_skeleton(project_dir, config),
        Language::Java => create_java_skeleton(project_dir, config),
        Language::Kotlin => create_kotlin_skeleton(project_dir, config),
        Language::Go => create_go_skeleton(project_dir, config),
        Language::CSharp => create_csharp_skeleton(project_dir, config),
        Language::Swift => create_swift_skeleton(project_dir, config),
        Language::Scala => create_scala_skeleton(project_dir, config),
        Language::Php => create_php_skeleton(project_dir, config),
    }
}

/// Create the Python authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_python_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"""FraiseQL blog schema definition for {name}."""

import fraiseql


@fraiseql.type(sql_source="v_author")
class Author:
    """Blog author with trinity pattern."""

    pk: int
    id: ID
    identifier: str
    name: str
    email: str
    bio: str | None
    created_at: DateTime
    updated_at: DateTime


@fraiseql.type(sql_source="v_post")
class Post:
    """Blog post with trinity pattern."""

    pk: int
    id: ID
    identifier: str
    title: str
    body: str
    published: bool
    author_id: ID
    created_at: DateTime
    updated_at: DateTime


@fraiseql.type(sql_source="v_comment")
class Comment:
    """Comment on a blog post."""

    pk: int
    id: ID
    body: str
    author_name: str
    post_id: ID
    created_at: DateTime


@fraiseql.type(sql_source="v_tag")
class Tag:
    """Categorization tag for posts."""

    pk: int
    id: ID
    identifier: str
    name: str


@fraiseql.query(return_type=Post, return_array=True, sql_source="v_post")
def posts() -> list[Post]:
    """List all published posts."""
    ...


@fraiseql.query(return_type=Post, sql_source="v_post")
def post(*, id: ID) -> Post:
    """Get post by ID."""
    ...


@fraiseql.query(return_type=Author, return_array=True, sql_source="v_author")
def authors() -> list[Author]:
    """List all authors."""
    ...


@fraiseql.query(return_type=Author, sql_source="v_author")
def author(*, id: ID) -> Author:
    """Get author by ID."""
    ...


@fraiseql.query(return_type=Tag, return_array=True, sql_source="v_tag")
def tags() -> list[Tag]:
    """List all tags."""
    ...
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.py"), content).context("Failed to create schema.py")?;
    info!("Created schema/schema.py");
    Ok(())
}

/// Create the TypeScript authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_typescript_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"/**
 * FraiseQL blog schema definition for {name}.
 */

import {{ type_, query }} from "fraiseql";

export const Author = type_("Author", {{
  sqlSource: "v_author",
  fields: {{
    pk: {{ type: "Int", nullable: false }},
    id: {{ type: "ID", nullable: false }},
    identifier: {{ type: "String", nullable: false }},
    name: {{ type: "String", nullable: false }},
    email: {{ type: "String", nullable: false }},
    bio: {{ type: "String", nullable: true }},
    created_at: {{ type: "DateTime", nullable: false }},
    updated_at: {{ type: "DateTime", nullable: false }},
  }},
}});

export const Post = type_("Post", {{
  sqlSource: "v_post",
  fields: {{
    pk: {{ type: "Int", nullable: false }},
    id: {{ type: "ID", nullable: false }},
    identifier: {{ type: "String", nullable: false }},
    title: {{ type: "String", nullable: false }},
    body: {{ type: "String", nullable: false }},
    published: {{ type: "Boolean", nullable: false }},
    author_id: {{ type: "ID", nullable: false }},
    created_at: {{ type: "DateTime", nullable: false }},
    updated_at: {{ type: "DateTime", nullable: false }},
  }},
}});

export const Comment = type_("Comment", {{
  sqlSource: "v_comment",
  fields: {{
    pk: {{ type: "Int", nullable: false }},
    id: {{ type: "ID", nullable: false }},
    body: {{ type: "String", nullable: false }},
    author_name: {{ type: "String", nullable: false }},
    post_id: {{ type: "ID", nullable: false }},
    created_at: {{ type: "DateTime", nullable: false }},
  }},
}});

export const Tag = type_("Tag", {{
  sqlSource: "v_tag",
  fields: {{
    pk: {{ type: "Int", nullable: false }},
    id: {{ type: "ID", nullable: false }},
    identifier: {{ type: "String", nullable: false }},
    name: {{ type: "String", nullable: false }},
  }},
}});

export const posts = query("posts", {{
  returnType: "Post",
  returnArray: true,
  sqlSource: "v_post",
}});

export const post = query("post", {{
  returnType: "Post",
  returnArray: false,
  sqlSource: "v_post",
  args: [{{ name: "id", type: "ID", required: true }}],
}});

export const authors = query("authors", {{
  returnType: "Author",
  returnArray: true,
  sqlSource: "v_author",
}});

export const author = query("author", {{
  returnType: "Author",
  returnArray: false,
  sqlSource: "v_author",
  args: [{{ name: "id", type: "ID", required: true }}],
}});

export const tagsQuery = query("tags", {{
  returnType: "Tag",
  returnArray: true,
  sqlSource: "v_tag",
}});
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.ts"), content).context("Failed to create schema.ts")?;
    info!("Created schema/schema.ts");
    Ok(())
}

/// Create the Rust authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_rust_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"//! FraiseQL blog schema definition for {name}.

use fraiseql::{{type_, query}};

/// Blog author with trinity pattern.
#[type_(sql_source = "v_author")]
pub struct Author {{
    pub pk: i32,
    pub id: ID,
    pub identifier: String,
    pub name: String,
    pub email: String,
    pub bio: Option<String>,
    pub created_at: DateTime,
    pub updated_at: DateTime,
}}

/// Blog post with trinity pattern.
#[type_(sql_source = "v_post")]
pub struct Post {{
    pub pk: i32,
    pub id: ID,
    pub identifier: String,
    pub title: String,
    pub body: String,
    pub published: bool,
    pub author_id: ID,
    pub created_at: DateTime,
    pub updated_at: DateTime,
}}

/// Comment on a blog post.
#[type_(sql_source = "v_comment")]
pub struct Comment {{
    pub pk: i32,
    pub id: ID,
    pub body: String,
    pub author_name: String,
    pub post_id: ID,
    pub created_at: DateTime,
}}

/// Categorization tag for posts.
#[type_(sql_source = "v_tag")]
pub struct Tag {{
    pub pk: i32,
    pub id: ID,
    pub identifier: String,
    pub name: String,
}}

#[query(return_type = "Post", return_array = true, sql_source = "v_post")]
pub fn posts() -> Vec<Post> {{
    panic!("implement resolver")
}}

#[query(return_type = "Post", sql_source = "v_post")]
pub fn post(id: ID) -> Post {{
    panic!("implement resolver")
}}

#[query(return_type = "Author", return_array = true, sql_source = "v_author")]
pub fn authors() -> Vec<Author> {{
    panic!("implement resolver")
}}

#[query(return_type = "Author", sql_source = "v_author")]
pub fn author(id: ID) -> Author {{
    panic!("implement resolver")
}}

#[query(return_type = "Tag", return_array = true, sql_source = "v_tag")]
pub fn tags() -> Vec<Tag> {{
    panic!("implement resolver")
}}
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.rs"), content).context("Failed to create schema.rs")?;
    info!("Created schema/schema.rs");
    Ok(())
}

/// Create the Java authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_java_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

package schema;

import fraiseql.FraiseQL;
import fraiseql.annotations.*;

/// Blog author with trinity pattern.
@Type(sqlSource = "v_author")
public record Author(
    int pk,
    ID id,
    String identifier,
    String name,
    String email,
    @Nullable String bio,
    DateTime createdAt,
    DateTime updatedAt
) {{}}

/// Blog post with trinity pattern.
@Type(sqlSource = "v_post")
public record Post(
    int pk,
    ID id,
    String identifier,
    String title,
    String body,
    boolean published,
    ID authorId,
    DateTime createdAt,
    DateTime updatedAt
) {{}}

/// Comment on a blog post.
@Type(sqlSource = "v_comment")
public record Comment(
    int pk,
    ID id,
    String body,
    String authorName,
    ID postId,
    DateTime createdAt
) {{}}

/// Categorization tag for posts.
@Type(sqlSource = "v_tag")
public record Tag(
    int pk,
    ID id,
    String identifier,
    String name
) {{}}

@Query(returnType = Post.class, returnArray = true, sqlSource = "v_post")
public interface Posts {{}}

@Query(returnType = Post.class, sqlSource = "v_post", args = @Arg(name = "id", type = "ID", required = true))
public interface PostById {{}}

@Query(returnType = Author.class, returnArray = true, sqlSource = "v_author")
public interface Authors {{}}

@Query(returnType = Author.class, sqlSource = "v_author", args = @Arg(name = "id", type = "ID", required = true))
public interface AuthorById {{}}

@Query(returnType = Tag.class, returnArray = true, sqlSource = "v_tag")
public interface Tags {{}}
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.java"), content).context("Failed to create schema.java")?;
    info!("Created schema/schema.java");
    Ok(())
}

/// Create the Kotlin authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_kotlin_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

package schema

import fraiseql.*

/// Blog author with trinity pattern.
@Type(sqlSource = "v_author")
data class Author(
    val pk: Int,
    val id: ID,
    val identifier: String,
    val name: String,
    val email: String,
    val bio: String?,
    val createdAt: DateTime,
    val updatedAt: DateTime,
)

/// Blog post with trinity pattern.
@Type(sqlSource = "v_post")
data class Post(
    val pk: Int,
    val id: ID,
    val identifier: String,
    val title: String,
    val body: String,
    val published: Boolean,
    val authorId: ID,
    val createdAt: DateTime,
    val updatedAt: DateTime,
)

/// Comment on a blog post.
@Type(sqlSource = "v_comment")
data class Comment(
    val pk: Int,
    val id: ID,
    val body: String,
    val authorName: String,
    val postId: ID,
    val createdAt: DateTime,
)

/// Categorization tag for posts.
@Type(sqlSource = "v_tag")
data class Tag(
    val pk: Int,
    val id: ID,
    val identifier: String,
    val name: String,
)

@Query(returnType = Post::class, returnArray = true, sqlSource = "v_post")
fun posts(): List<Post> = TODO("Schema definition only")

@Query(returnType = Post::class, sqlSource = "v_post")
fun post(id: ID): Post = TODO("Schema definition only")

@Query(returnType = Author::class, returnArray = true, sqlSource = "v_author")
fun authors(): List<Author> = TODO("Schema definition only")

@Query(returnType = Author::class, sqlSource = "v_author")
fun author(id: ID): Author = TODO("Schema definition only")

@Query(returnType = Tag::class, returnArray = true, sqlSource = "v_tag")
fun tags(): List<Tag> = TODO("Schema definition only")
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.kt"), content).context("Failed to create schema.kt")?;
    info!("Created schema/schema.kt");
    Ok(())
}

/// Create the Go authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_go_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

package schema

import "fraiseql"

// Author - Blog author with trinity pattern.
// @Type(sqlSource = "v_author")
type Author struct {{
	PK         int      `fraiseql:"pk"`
	ID         ID       `fraiseql:"id"`
	Identifier string   `fraiseql:"identifier"`
	Name       string   `fraiseql:"name"`
	Email      string   `fraiseql:"email"`
	Bio        *string  `fraiseql:"bio"`
	CreatedAt  DateTime `fraiseql:"created_at"`
	UpdatedAt  DateTime `fraiseql:"updated_at"`
}}

// Post - Blog post with trinity pattern.
// @Type(sqlSource = "v_post")
type Post struct {{
	PK         int      `fraiseql:"pk"`
	ID         ID       `fraiseql:"id"`
	Identifier string   `fraiseql:"identifier"`
	Title      string   `fraiseql:"title"`
	Body       string   `fraiseql:"body"`
	Published  bool     `fraiseql:"published"`
	AuthorID   ID       `fraiseql:"author_id"`
	CreatedAt  DateTime `fraiseql:"created_at"`
	UpdatedAt  DateTime `fraiseql:"updated_at"`
}}

// Comment - Comment on a blog post.
// @Type(sqlSource = "v_comment")
type Comment struct {{
	PK         int      `fraiseql:"pk"`
	ID         ID       `fraiseql:"id"`
	Body       string   `fraiseql:"body"`
	AuthorName string   `fraiseql:"author_name"`
	PostID     ID       `fraiseql:"post_id"`
	CreatedAt  DateTime `fraiseql:"created_at"`
}}

// Tag - Categorization tag for posts.
// @Type(sqlSource = "v_tag")
type Tag struct {{
	PK         int    `fraiseql:"pk"`
	ID         ID     `fraiseql:"id"`
	Identifier string `fraiseql:"identifier"`
	Name       string `fraiseql:"name"`
}}

// Queries are registered via fraiseql.RegisterQuery().
func init() {{
	fraiseql.RegisterQuery("posts", fraiseql.QueryDef{{ReturnType: "Post", ReturnArray: true, SQLSource: "v_post"}})
	fraiseql.RegisterQuery("post", fraiseql.QueryDef{{ReturnType: "Post", SQLSource: "v_post", Args: []fraiseql.Arg{{{{Name: "id", Type: "ID", Required: true}}}}}})
	fraiseql.RegisterQuery("authors", fraiseql.QueryDef{{ReturnType: "Author", ReturnArray: true, SQLSource: "v_author"}})
	fraiseql.RegisterQuery("author", fraiseql.QueryDef{{ReturnType: "Author", SQLSource: "v_author", Args: []fraiseql.Arg{{{{Name: "id", Type: "ID", Required: true}}}}}})
	fraiseql.RegisterQuery("tags", fraiseql.QueryDef{{ReturnType: "Tag", ReturnArray: true, SQLSource: "v_tag"}})
}}
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.go"), content).context("Failed to create schema.go")?;
    info!("Created schema/schema.go");
    Ok(())
}

/// Create the C# authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_csharp_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

using FraiseQL;

namespace Schema;

/// Blog author with trinity pattern.
[Type(SqlSource = "v_author")]
public record Author(
    int Pk,
    ID Id,
    string Identifier,
    string Name,
    string Email,
    string? Bio,
    DateTime CreatedAt,
    DateTime UpdatedAt
);

/// Blog post with trinity pattern.
[Type(SqlSource = "v_post")]
public record Post(
    int Pk,
    ID Id,
    string Identifier,
    string Title,
    string Body,
    bool Published,
    ID AuthorId,
    DateTime CreatedAt,
    DateTime UpdatedAt
);

/// Comment on a blog post.
[Type(SqlSource = "v_comment")]
public record Comment(
    int Pk,
    ID Id,
    string Body,
    string AuthorName,
    ID PostId,
    DateTime CreatedAt
);

/// Categorization tag for posts.
[Type(SqlSource = "v_tag")]
public record Tag(
    int Pk,
    ID Id,
    string Identifier,
    string Name
);

[Query(ReturnType = typeof(Post), ReturnArray = true, SqlSource = "v_post")]
public static partial class Posts;

[Query(ReturnType = typeof(Post), SqlSource = "v_post", Arg(Name = "id", Type = "ID", Required = true))]
public static partial class PostById;

[Query(ReturnType = typeof(Author), ReturnArray = true, SqlSource = "v_author")]
public static partial class Authors;

[Query(ReturnType = typeof(Author), SqlSource = "v_author", Arg(Name = "id", Type = "ID", Required = true))]
public static partial class AuthorById;

[Query(ReturnType = typeof(Tag), ReturnArray = true, SqlSource = "v_tag")]
public static partial class Tags;
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.cs"), content).context("Failed to create schema.cs")?;
    info!("Created schema/schema.cs");
    Ok(())
}

/// Create the Swift authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_swift_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

import FraiseQL

/// Blog author with trinity pattern.
@Type(sqlSource: "v_author")
struct Author {{
    let pk: Int
    let id: ID
    let identifier: String
    let name: String
    let email: String
    let bio: String?
    let createdAt: DateTime
    let updatedAt: DateTime
}}

/// Blog post with trinity pattern.
@Type(sqlSource: "v_post")
struct Post {{
    let pk: Int
    let id: ID
    let identifier: String
    let title: String
    let body: String
    let published: Bool
    let authorId: ID
    let createdAt: DateTime
    let updatedAt: DateTime
}}

/// Comment on a blog post.
@Type(sqlSource: "v_comment")
struct Comment {{
    let pk: Int
    let id: ID
    let body: String
    let authorName: String
    let postId: ID
    let createdAt: DateTime
}}

/// Categorization tag for posts.
@Type(sqlSource: "v_tag")
struct Tag {{
    let pk: Int
    let id: ID
    let identifier: String
    let name: String
}}

@Query(returnType: Post.self, returnArray: true, sqlSource: "v_post")
func posts() -> [Post] {{ fatalError("Schema definition only") }}

@Query(returnType: Post.self, sqlSource: "v_post")
func post(id: ID) -> Post {{ fatalError("Schema definition only") }}

@Query(returnType: Author.self, returnArray: true, sqlSource: "v_author")
func authors() -> [Author] {{ fatalError("Schema definition only") }}

@Query(returnType: Author.self, sqlSource: "v_author")
func author(id: ID) -> Author {{ fatalError("Schema definition only") }}

@Query(returnType: Tag.self, returnArray: true, sqlSource: "v_tag")
func tags() -> [Tag] {{ fatalError("Schema definition only") }}
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.swift"), content).context("Failed to create schema.swift")?;
    info!("Created schema/schema.swift");
    Ok(())
}

/// Create the Scala authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_scala_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r#"// FraiseQL blog schema definition for {name}.

package schema

import fraiseql._

/// Blog author with trinity pattern.
@Type(sqlSource = "v_author")
case class Author(
  pk: Int,
  id: ID,
  identifier: String,
  name: String,
  email: String,
  bio: Option[String],
  createdAt: DateTime,
  updatedAt: DateTime
)

/// Blog post with trinity pattern.
@Type(sqlSource = "v_post")
case class Post(
  pk: Int,
  id: ID,
  identifier: String,
  title: String,
  body: String,
  published: Boolean,
  authorId: ID,
  createdAt: DateTime,
  updatedAt: DateTime
)

/// Comment on a blog post.
@Type(sqlSource = "v_comment")
case class Comment(
  pk: Int,
  id: ID,
  body: String,
  authorName: String,
  postId: ID,
  createdAt: DateTime
)

/// Categorization tag for posts.
@Type(sqlSource = "v_tag")
case class Tag(
  pk: Int,
  id: ID,
  identifier: String,
  name: String
)

@Query(returnType = classOf[Post], returnArray = true, sqlSource = "v_post")
def posts(): List[Post] = ???

@Query(returnType = classOf[Post], sqlSource = "v_post")
def post(id: ID): Post = ???

@Query(returnType = classOf[Author], returnArray = true, sqlSource = "v_author")
def authors(): List[Author] = ???

@Query(returnType = classOf[Author], sqlSource = "v_author")
def author(id: ID): Author = ???

@Query(returnType = classOf[Tag], returnArray = true, sqlSource = "v_tag")
def tags(): List[Tag] = ???
"#,
        name = config.project_name,
    );

    fs::write(dir.join("schema.scala"), content).context("Failed to create schema.scala")?;
    info!("Created schema/schema.scala");
    Ok(())
}

/// Create the PHP authoring skeleton under `project_dir/schema/`.
///
/// # Errors
///
/// Returns an error if the schema directory or skeleton files cannot be created.
pub(super) fn create_php_skeleton(project_dir: &Path, config: &InitConfig) -> Result<()> {
    let dir = project_dir.join("schema");
    fs::create_dir_all(&dir).context("Failed to create schema/ directory")?;

    let content = format!(
        r"<?php

declare(strict_types=1);

// FraiseQL blog schema definition for {name}.

use FraiseQL\Attributes\GraphQLType;
use FraiseQL\Attributes\GraphQLField;

/** Blog author with trinity pattern. */
#[GraphQLType(name: 'Author', sqlSource: 'v_author')]
final class Author
{{
    #[GraphQLField(type: 'Int')]
    public int $pk;

    #[GraphQLField(type: 'ID')]
    public string $id;

    #[GraphQLField(type: 'String')]
    public string $identifier;

    #[GraphQLField(type: 'String')]
    public string $name;

    #[GraphQLField(type: 'String')]
    public string $email;

    #[GraphQLField(type: 'String', nullable: true)]
    public ?string $bio;

    #[GraphQLField(type: 'DateTime')]
    public string $createdAt;

    #[GraphQLField(type: 'DateTime')]
    public string $updatedAt;
}}

/** Blog post with trinity pattern. */
#[GraphQLType(name: 'Post', sqlSource: 'v_post')]
final class Post
{{
    #[GraphQLField(type: 'Int')]
    public int $pk;

    #[GraphQLField(type: 'ID')]
    public string $id;

    #[GraphQLField(type: 'String')]
    public string $identifier;

    #[GraphQLField(type: 'String')]
    public string $title;

    #[GraphQLField(type: 'String')]
    public string $body;

    #[GraphQLField(type: 'Boolean')]
    public bool $published;

    #[GraphQLField(type: 'ID')]
    public string $authorId;

    #[GraphQLField(type: 'DateTime')]
    public string $createdAt;

    #[GraphQLField(type: 'DateTime')]
    public string $updatedAt;
}}

/** Comment on a blog post. */
#[GraphQLType(name: 'Comment', sqlSource: 'v_comment')]
final class Comment
{{
    #[GraphQLField(type: 'Int')]
    public int $pk;

    #[GraphQLField(type: 'ID')]
    public string $id;

    #[GraphQLField(type: 'String')]
    public string $body;

    #[GraphQLField(type: 'String')]
    public string $authorName;

    #[GraphQLField(type: 'ID')]
    public string $postId;

    #[GraphQLField(type: 'DateTime')]
    public string $createdAt;
}}

/** Categorization tag for posts. */
#[GraphQLType(name: 'Tag', sqlSource: 'v_tag')]
final class Tag
{{
    #[GraphQLField(type: 'Int')]
    public int $pk;

    #[GraphQLField(type: 'ID')]
    public string $id;

    #[GraphQLField(type: 'String')]
    public string $identifier;

    #[GraphQLField(type: 'String')]
    public string $name;
}}
",
        name = config.project_name,
    );

    fs::write(dir.join("schema.php"), content).context("Failed to create schema/schema.php")?;
    info!("Created schema/schema.php");
    Ok(())
}

/// Initialise a git repository in `project_dir`.
///
/// # Errors
///
/// Returns an error if `git init` cannot be spawned or exits with a non-zero status.
pub(super) fn init_git(project_dir: &Path) -> Result<()> {
    let status = Command::new("git")
        .args(["init"])
        .current_dir(project_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    match status {
        Ok(s) if s.success() => {
            info!("Initialized git repository");
            Ok(())
        },
        Ok(_) => {
            // git init failed but non-fatal
            eprintln!("Warning: git init failed. You can initialize git manually.");
            Ok(())
        },
        Err(_) => {
            eprintln!("Warning: git not found. Skipping repository initialization.");
            Ok(())
        },
    }
}