fraiseql-cli 2.19.1

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
//! PostgreSQL DDL templates for the `fraiseql init` scaffold.
//!
//! The scaffold follows the runtime's contracts exactly, because the runtime
//! executes against what these templates create:
//!
//! - **Read path**: every `v_*` view exposes a `data` JSONB column built with `jsonb_build_object`
//!   — the adapter's only read shape is `SELECT data FROM "<view>"` (#823). Keys are snake_case
//!   **storage keys**: the runtime's canonical mapping (`fraiseql_db::utils::to_snake_case`)
//!   recases the schema's camelCase GraphQL field names onto them at every read site (projection,
//!   order-by, filters).
//! - **Write path**: every `fn_*` mutation function returns the 13-column v2.2 `mutation_response`
//!   row via the `fraiseql.mutation_ok` / `fraiseql.mutation_err` builders that `fraiseql setup`
//!   installs (#569).
//! - **Trinity naming**: `pk_<entity>` (internal), `id` (public UUID), `identifier` (URL slug);
//!   singular `tb_`/`v_` names.
//!
//! FraiseQL is PostgreSQL-only (non-PG backends were removed in v2.15.0,
//! #374), so these templates have no dialect parameter.

/// Generate a single-file schema for the XS size (blog project).
pub(super) fn generate_single_schema_sql() -> String {
    let mut sql = String::with_capacity(8192);
    sql.push_str(
        "-- FraiseQL Blog Schema (PostgreSQL)\n\
         -- Trinity pattern: pk (internal), id (public UUID), identifier (URL slug)\n\
         -- Views expose a `data` JSONB column — the read shape the runtime executes.\n\
         -- Mutation functions require `fraiseql setup` to have been run first\n\
         -- (installs fraiseql.mutation_ok/mutation_err and core.tb_entity_change_log).\n\n",
    );
    for entity in super::ENTITIES {
        let (table, view, functions) = generate_blog_entity_sql(entity);
        sql.push_str(&table);
        sql.push('\n');
        sql.push_str(&view);
        sql.push('\n');
        sql.push_str(&functions);
        sql.push('\n');
    }
    sql.push_str(JUNCTION_TABLE);
    sql
}

/// Generate per-entity SQL split into (table, view, functions) for S/M layouts.
pub(super) fn generate_blog_entity_sql(entity: &str) -> (String, String, String) {
    match entity {
        "author" => (
            ENTITY_AUTHOR_TABLE.to_string(),
            ENTITY_AUTHOR_VIEW.to_string(),
            author_functions(),
        ),
        "post" => (ENTITY_POST_TABLE.to_string(), ENTITY_POST_VIEW.to_string(), post_functions()),
        "comment" => (
            ENTITY_COMMENT_TABLE.to_string(),
            ENTITY_COMMENT_VIEW.to_string(),
            comment_functions(),
        ),
        "tag" => (ENTITY_TAG_TABLE.to_string(), ENTITY_TAG_VIEW.to_string(), tag_functions()),
        _ => (format!("-- Unknown entity: {entity}\n"), String::new(), String::new()),
    }
}

/// The 13-column v2.2 `mutation_response` row type every mutation function
/// returns. Matches `fraiseql.mutation_ok` / `fraiseql.mutation_err` exactly,
/// so function bodies can `RETURN QUERY SELECT * FROM fraiseql.mutation_ok(…)`.
const MUTATION_RESPONSE_COLUMNS: &str = "\
    succeeded BOOLEAN,
    state_changed BOOLEAN,
    error_class TEXT,
    status_detail TEXT,
    http_status SMALLINT,
    message TEXT,
    entity_id UUID,
    entity_type TEXT,
    entity JSONB,
    updated_fields TEXT[],
    cascade JSONB,
    error_detail JSONB,
    metadata JSONB";

const JUNCTION_TABLE: &str = "\
-- Post-Tag junction
CREATE TABLE IF NOT EXISTS tb_post_tag (
    post_id UUID NOT NULL REFERENCES tb_post(id) ON DELETE CASCADE,
    tag_id  UUID NOT NULL REFERENCES tb_tag(id) ON DELETE CASCADE,
    PRIMARY KEY (post_id, tag_id)
);
";

// --- Per-entity PostgreSQL templates ---

const ENTITY_AUTHOR_TABLE: &str = "\
-- Table: author
-- Trinity pattern: pk (internal), id (public UUID), identifier (URL slug)

CREATE TABLE IF NOT EXISTS tb_author (
    pk_author   SERIAL PRIMARY KEY,
    id          UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    identifier  TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL,
    email       TEXT NOT NULL UNIQUE,
    bio         TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_tb_author_email ON tb_author (email);
";

const ENTITY_AUTHOR_VIEW: &str = "\
-- View: author (read-optimized)
-- The runtime reads `SELECT data FROM v_author`; JSONB keys are snake_case
-- storage keys (the runtime maps camelCase GraphQL field names onto them).

CREATE OR REPLACE VIEW v_author AS
SELECT
    pk_author,
    id,
    jsonb_build_object(
        'pk', pk_author,
        'id', id,
        'identifier', identifier,
        'name', name,
        'email', email,
        'bio', bio,
        'created_at', created_at,
        'updated_at', updated_at
    ) AS data
FROM tb_author;
";

const ENTITY_POST_TABLE: &str = "\
-- Table: post
-- Trinity pattern: pk (internal), id (public UUID), identifier (URL slug)

CREATE TABLE IF NOT EXISTS tb_post (
    pk_post     SERIAL PRIMARY KEY,
    id          UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    identifier  TEXT NOT NULL UNIQUE,
    title       TEXT NOT NULL,
    body        TEXT NOT NULL,
    published   BOOLEAN NOT NULL DEFAULT false,
    author_id   UUID NOT NULL REFERENCES tb_author(id),
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_tb_post_author ON tb_post (author_id);
CREATE INDEX IF NOT EXISTS idx_tb_post_published ON tb_post (published) WHERE published = true;
";

const ENTITY_POST_VIEW: &str = "\
-- View: post (read-optimized)
-- The runtime reads `SELECT data FROM v_post`; JSONB keys are snake_case
-- storage keys (the runtime maps camelCase GraphQL field names onto them).

CREATE OR REPLACE VIEW v_post AS
SELECT
    pk_post,
    id,
    jsonb_build_object(
        'pk', pk_post,
        'id', id,
        'identifier', identifier,
        'title', title,
        'body', body,
        'published', published,
        'author_id', author_id,
        'created_at', created_at,
        'updated_at', updated_at
    ) AS data
FROM tb_post;
";

const ENTITY_COMMENT_TABLE: &str = "\
-- Table: comment

CREATE TABLE IF NOT EXISTS tb_comment (
    pk_comment  SERIAL PRIMARY KEY,
    id          UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    body        TEXT NOT NULL,
    author_name TEXT NOT NULL,
    post_id     UUID NOT NULL REFERENCES tb_post(id) ON DELETE CASCADE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_tb_comment_post ON tb_comment (post_id);
";

const ENTITY_COMMENT_VIEW: &str = "\
-- View: comment (read-optimized)
-- The runtime reads `SELECT data FROM v_comment`; JSONB keys are snake_case
-- storage keys (the runtime maps camelCase GraphQL field names onto them).

CREATE OR REPLACE VIEW v_comment AS
SELECT
    pk_comment,
    id,
    jsonb_build_object(
        'pk', pk_comment,
        'id', id,
        'body', body,
        'author_name', author_name,
        'post_id', post_id,
        'created_at', created_at
    ) AS data
FROM tb_comment;
";

const ENTITY_TAG_TABLE: &str = "\
-- Table: tag
-- Trinity pattern: pk (internal), id (public UUID), identifier (URL slug)

CREATE TABLE IF NOT EXISTS tb_tag (
    pk_tag      SERIAL PRIMARY KEY,
    id          UUID NOT NULL DEFAULT gen_random_uuid() UNIQUE,
    identifier  TEXT NOT NULL UNIQUE,
    name        TEXT NOT NULL UNIQUE
);
";

const ENTITY_TAG_VIEW: &str = "\
-- View: tag (read-optimized)
-- The runtime reads `SELECT data FROM v_tag`; JSONB keys are snake_case
-- storage keys (the runtime maps camelCase GraphQL field names onto them).

CREATE OR REPLACE VIEW v_tag AS
SELECT
    pk_tag,
    id,
    jsonb_build_object(
        'pk', pk_tag,
        'id', id,
        'identifier', identifier,
        'name', name
    ) AS data
FROM tb_tag;
";

/// Author create/delete — the v2.2 `mutation_response` contract (#569): the
/// runtime wraps every mutation in a change-log CTE that reads the 13-column
/// row (`r.entity_type`, `r.succeeded`, …) from the function's result. The
/// entity payload is read back from the view so the write path and read path
/// can never disagree about the JSON shape.
fn author_functions() -> String {
    format!(
        "\
-- Mutation functions for author (v2.2 mutation_response contract)
-- Requires `fraiseql setup` (installs fraiseql.mutation_ok/mutation_err).

CREATE OR REPLACE FUNCTION fn_author_create(
    p_identifier TEXT,
    p_name TEXT,
    p_email TEXT,
    p_bio TEXT DEFAULT NULL
) RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_id UUID;
BEGIN
    INSERT INTO tb_author (identifier, name, email, bio)
    VALUES (p_identifier, p_name, p_email, p_bio)
    RETURNING tb_author.id INTO v_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(
        (SELECT data FROM v_author WHERE v_author.id = v_id), v_id, 'Author');
END;
$$;

CREATE OR REPLACE FUNCTION fn_author_delete(p_id UUID)
RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_entity JSONB;
BEGIN
    SELECT data INTO v_entity FROM v_author WHERE v_author.id = p_id;
    IF v_entity IS NULL THEN
        RETURN QUERY SELECT * FROM fraiseql.mutation_err('not_found', 'Author not found');
        RETURN;
    END IF;
    DELETE FROM tb_author WHERE tb_author.id = p_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(v_entity, p_id, 'Author');
END;
$$;
",
        cols = MUTATION_RESPONSE_COLUMNS
    )
}

fn post_functions() -> String {
    format!(
        "\
-- Mutation functions for post (v2.2 mutation_response contract)
-- Requires `fraiseql setup` (installs fraiseql.mutation_ok/mutation_err).

CREATE OR REPLACE FUNCTION fn_post_create(
    p_identifier TEXT,
    p_title TEXT,
    p_body TEXT,
    p_author_id UUID
) RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_id UUID;
BEGIN
    INSERT INTO tb_post (identifier, title, body, author_id)
    VALUES (p_identifier, p_title, p_body, p_author_id)
    RETURNING tb_post.id INTO v_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(
        (SELECT data FROM v_post WHERE v_post.id = v_id), v_id, 'Post');
END;
$$;

CREATE OR REPLACE FUNCTION fn_post_publish(p_id UUID)
RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
BEGIN
    UPDATE tb_post SET published = true, updated_at = now() WHERE tb_post.id = p_id;
    IF NOT FOUND THEN
        RETURN QUERY SELECT * FROM fraiseql.mutation_err('not_found', 'Post not found');
        RETURN;
    END IF;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(
        (SELECT data FROM v_post WHERE v_post.id = p_id), p_id, 'Post', TRUE,
        ARRAY['published', 'updatedAt']);
END;
$$;

CREATE OR REPLACE FUNCTION fn_post_delete(p_id UUID)
RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_entity JSONB;
BEGIN
    SELECT data INTO v_entity FROM v_post WHERE v_post.id = p_id;
    IF v_entity IS NULL THEN
        RETURN QUERY SELECT * FROM fraiseql.mutation_err('not_found', 'Post not found');
        RETURN;
    END IF;
    DELETE FROM tb_post WHERE tb_post.id = p_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(v_entity, p_id, 'Post');
END;
$$;
",
        cols = MUTATION_RESPONSE_COLUMNS
    )
}

fn comment_functions() -> String {
    format!(
        "\
-- Mutation functions for comment (v2.2 mutation_response contract)
-- Requires `fraiseql setup` (installs fraiseql.mutation_ok/mutation_err).

CREATE OR REPLACE FUNCTION fn_comment_create(
    p_body TEXT,
    p_author_name TEXT,
    p_post_id UUID
) RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_id UUID;
BEGIN
    INSERT INTO tb_comment (body, author_name, post_id)
    VALUES (p_body, p_author_name, p_post_id)
    RETURNING tb_comment.id INTO v_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(
        (SELECT data FROM v_comment WHERE v_comment.id = v_id), v_id, 'Comment');
END;
$$;

CREATE OR REPLACE FUNCTION fn_comment_delete(p_id UUID)
RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_entity JSONB;
BEGIN
    SELECT data INTO v_entity FROM v_comment WHERE v_comment.id = p_id;
    IF v_entity IS NULL THEN
        RETURN QUERY SELECT * FROM fraiseql.mutation_err('not_found', 'Comment not found');
        RETURN;
    END IF;
    DELETE FROM tb_comment WHERE tb_comment.id = p_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(v_entity, p_id, 'Comment');
END;
$$;
",
        cols = MUTATION_RESPONSE_COLUMNS
    )
}

fn tag_functions() -> String {
    format!(
        "\
-- Mutation functions for tag (v2.2 mutation_response contract)
-- Requires `fraiseql setup` (installs fraiseql.mutation_ok/mutation_err).

CREATE OR REPLACE FUNCTION fn_tag_create(
    p_identifier TEXT,
    p_name TEXT
) RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_id UUID;
BEGIN
    INSERT INTO tb_tag (identifier, name)
    VALUES (p_identifier, p_name)
    RETURNING tb_tag.id INTO v_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(
        (SELECT data FROM v_tag WHERE v_tag.id = v_id), v_id, 'Tag');
END;
$$;

CREATE OR REPLACE FUNCTION fn_tag_delete(p_id UUID)
RETURNS TABLE(
{cols}
)
LANGUAGE plpgsql AS $$
DECLARE
    v_entity JSONB;
BEGIN
    SELECT data INTO v_entity FROM v_tag WHERE v_tag.id = p_id;
    IF v_entity IS NULL THEN
        RETURN QUERY SELECT * FROM fraiseql.mutation_err('not_found', 'Tag not found');
        RETURN;
    END IF;
    DELETE FROM tb_tag WHERE tb_tag.id = p_id;
    RETURN QUERY SELECT * FROM fraiseql.mutation_ok(v_entity, p_id, 'Tag');
END;
$$;
",
        cols = MUTATION_RESPONSE_COLUMNS
    )
}