fraiseql-cli 2.3.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
//! Integration tests for FraiseQL CLI view generation commands
//!
//! This test suite validates the `fraiseql generate-views` subcommand functionality across
//! multiple scenarios and view types. The tests verify:
//!
//! - **Schema Loading**: Ability to read and parse FraiseQL schema JSON files
//! - **DDL Generation**: Correct SQL generation for different view patterns:
//!   - Table-backed views (tv_*) with JSON storage and indexing
//!   - Arrow-backed views (ta_*) with columnar compression
//!   - Composition views (cv_*) for entity relationships
//! - **Refresh Mechanisms**: Both trigger-based and scheduled refresh strategies
//! - **Complex Relationships**: Multi-entity schemas with foreign key denormalization
//! - **Monitoring & Observability**: Staleness tracking and health check functions
//!
//! These tests are critical for ensuring DDL output is syntactically correct and properly
//! indexed for runtime performance. They serve as documentation of the expected DDL format
//! for AI-assisted debugging and code generation.
//!
//! # Test Organization
//!
//! Tests are grouped by feature area:
//! - Basic view generation (test 1-2): Schema structure and basic DDL validation
//! - Arrow integration (test 3): Column-oriented view format
//! - Multi-entity support (test 4-7): Complex schemas with relationships
//! - Output format (test 8): Complete DDL file structure with headers
//! - Advanced features (test 9-10): Composition views and monitoring functions

#[cfg(test)]
mod tests {
    const USER_SCHEMA: &str = r#"{
      "version": "2.0",
      "types": [
        {
          "name": "User",
          "description": "A simple user entity with basic profile information.",
          "fields": [
            {"name": "id", "type": "Int", "nullable": false},
            {"name": "name", "type": "String", "nullable": false},
            {"name": "email", "type": "String", "nullable": false},
            {"name": "created_at", "type": "DateTime", "nullable": false}
          ]
        }
      ],
      "queries": [],
      "mutations": []
    }"#;

    const USER_WITH_POSTS_SCHEMA: &str = r#"{
      "version": "2.0",
      "types": [
        {
          "name": "User",
          "description": "A user with related blog posts.",
          "fields": [
            {"name": "id", "type": "Int", "nullable": false},
            {"name": "name", "type": "String", "nullable": false},
            {"name": "email", "type": "String", "nullable": false},
            {"name": "posts", "type": "Post", "nullable": true},
            {"name": "created_at", "type": "DateTime", "nullable": false}
          ]
        },
        {
          "name": "Post",
          "description": "A blog post written by a user.",
          "fields": [
            {"name": "id", "type": "Int", "nullable": false},
            {"name": "title", "type": "String", "nullable": false},
            {"name": "content", "type": "String", "nullable": false},
            {"name": "author_id", "type": "Int", "nullable": false},
            {"name": "author", "type": "User", "nullable": true},
            {"name": "created_at", "type": "DateTime", "nullable": false}
          ]
        }
      ],
      "queries": [],
      "mutations": []
    }"#;

    const ORDERS_SCHEMA: &str = r#"{
      "version": "2.0",
      "types": [
        {
          "name": "Order",
          "description": "An e-commerce order with line items.",
          "fields": [
            {"name": "id", "type": "Int", "nullable": false},
            {"name": "order_number", "type": "String", "nullable": false},
            {"name": "customer_id", "type": "Int", "nullable": false},
            {"name": "status", "type": "String", "nullable": false},
            {"name": "total_amount", "type": "Int", "nullable": false},
            {"name": "items", "type": "LineItem", "nullable": true},
            {"name": "created_at", "type": "DateTime", "nullable": false},
            {"name": "updated_at", "type": "DateTime", "nullable": false}
          ]
        },
        {
          "name": "LineItem",
          "description": "A line item in an order.",
          "fields": [
            {"name": "id", "type": "Int", "nullable": false},
            {"name": "order_id", "type": "Int", "nullable": false},
            {"name": "product_id", "type": "Int", "nullable": false},
            {"name": "quantity", "type": "Int", "nullable": false},
            {"name": "unit_price", "type": "Int", "nullable": false},
            {"name": "order", "type": "Order", "nullable": true},
            {"name": "created_at", "type": "DateTime", "nullable": false}
          ]
        }
      ],
      "queries": [],
      "mutations": []
    }"#;

    /// Test 1: Basic view generation for simple entity
    #[test]
    fn test_generate_tv_ddl_basic() {
        let schema: serde_json::Value =
            serde_json::from_str(USER_SCHEMA).expect("Failed to parse schema JSON");

        // Verify schema structure
        assert!(schema.get("types").is_some(), "Schema should have types");
        assert!(schema.get("version").is_some(), "Schema should have version");

        let types = schema["types"].as_array().expect("types should be array");
        assert!(!types.is_empty(), "Schema should have at least one type");

        // Verify User entity exists
        let user_type = types
            .iter()
            .find(|t| t.get("name").map(|v| v.as_str()) == Some(Some("User")))
            .expect("User entity should exist");

        assert!(user_type.get("fields").is_some(), "User should have fields");
    }

    /// Test 2: DDL validation for generated views
    #[test]
    fn test_validate_generated_ddl() {
        // Verify user schema parses
        let _schema: serde_json::Value =
            serde_json::from_str(USER_SCHEMA).expect("Failed to parse schema JSON");

        // Example DDL that would be generated
        let sample_ddl = r"
            -- Generated DDL for tv_user view
            CREATE TABLE IF NOT EXISTS tv_user (
                entity_id INTEGER NOT NULL UNIQUE,
                entity_json JSONB NOT NULL,
                is_stale BOOLEAN DEFAULT false,
                last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            );

            CREATE INDEX IF NOT EXISTS idx_tv_user_entity_id ON tv_user(entity_id);
            CREATE INDEX IF NOT EXISTS idx_tv_user_entity_json_gin ON tv_user USING GIN(entity_json);

            COMMENT ON TABLE tv_user IS 'Table-backed JSON view for User entity';
            COMMENT ON COLUMN tv_user.entity_id IS 'Primary key reference to source User';
            COMMENT ON COLUMN tv_user.entity_json IS 'Materialized User data as JSONB';
        ";

        // Validate DDL
        assert!(sample_ddl.contains("CREATE TABLE"), "Should have CREATE TABLE statement");
        assert!(sample_ddl.contains("CREATE INDEX"), "Should have CREATE INDEX statements");
        assert!(sample_ddl.contains("COMMENT ON"), "Should have COMMENT statements");

        // Check for proper formatting
        assert!(!sample_ddl.contains("{{"), "Should not have unresolved template variables");
    }

    /// Test 3: Arrow view DDL generation
    #[test]
    fn test_generate_ta_ddl_with_arrow_columns() {
        // Verify user schema parses
        let _schema: serde_json::Value =
            serde_json::from_str(USER_SCHEMA).expect("Failed to parse schema JSON");

        // Example Arrow DDL that would be generated
        let sample_arrow_ddl = r"
            -- Generated Arrow DDL for ta_user_analytics view
            CREATE TABLE IF NOT EXISTS ta_user_analytics (
                batch_number INTEGER NOT NULL,
                col_id BYTEA,
                col_name BYTEA,
                col_email BYTEA,
                col_created_at BYTEA,
                row_count INTEGER NOT NULL DEFAULT 0,
                batch_size_bytes BIGINT,
                compression VARCHAR(10) DEFAULT 'none',
                last_materialized_row_count BIGINT,
                estimated_decode_time_ms INTEGER
            );

            CREATE INDEX IF NOT EXISTS idx_ta_user_batch ON ta_user_analytics(batch_number);
            COMMENT ON TABLE ta_user_analytics IS 'Table-backed Arrow view for User analytics';
        ";

        // Validate Arrow DDL
        assert!(sample_arrow_ddl.contains("BYTEA"), "Arrow columns should be BYTEA type");
        assert!(sample_arrow_ddl.contains("batch_number"), "Should have batch tracking column");
        assert!(sample_arrow_ddl.contains("col_id"), "Should have Arrow column for id field");
    }

    /// Test 4: Multiple views from single schema
    #[test]
    fn test_generate_multiple_views_from_schema() {
        let schema: serde_json::Value =
            serde_json::from_str(USER_WITH_POSTS_SCHEMA).expect("Failed to parse schema JSON");

        // Verify multiple types
        let types = schema["types"].as_array().expect("types should be array");
        assert!(types.len() >= 2, "Schema should have multiple types (User, Post)");

        // Verify User type
        let user_exists =
            types.iter().any(|t| t.get("name").map(|v| v.as_str()) == Some(Some("User")));
        assert!(user_exists, "User type should exist");

        // Verify Post type
        let post_exists =
            types.iter().any(|t| t.get("name").map(|v| v.as_str()) == Some(Some("Post")));
        assert!(post_exists, "Post type should exist");
    }

    /// Test 5: DDL output with refresh trigger
    #[test]
    fn test_ddl_includes_refresh_trigger() {
        // Example trigger-based refresh DDL
        let trigger_ddl = r"
            -- Refresh trigger for trigger-based strategy
            CREATE OR REPLACE FUNCTION refresh_tv_user()
            RETURNS TRIGGER AS $$
            BEGIN
                UPDATE tv_user
                SET is_stale = true
                WHERE entity_id = NEW.id;
                RETURN NEW;
            END;
            $$ LANGUAGE plpgsql;

            CREATE TRIGGER trg_refresh_tv_user
            AFTER INSERT OR UPDATE OR DELETE ON public.user
            FOR EACH ROW
            EXECUTE FUNCTION refresh_tv_user();
        ";

        // Validate trigger structure
        assert!(
            trigger_ddl.contains("CREATE OR REPLACE FUNCTION"),
            "Should have function creation"
        );
        assert!(trigger_ddl.contains("CREATE TRIGGER"), "Should have trigger creation");
        assert!(
            trigger_ddl.contains("AFTER INSERT OR UPDATE OR DELETE"),
            "Should trigger on DML changes"
        );
    }

    /// Test 6: DDL output with scheduled refresh
    #[test]
    fn test_ddl_includes_scheduled_refresh() {
        // Example scheduled refresh DDL
        let scheduled_ddl = r"
            -- Scheduled refresh using pg_cron
            CREATE OR REPLACE FUNCTION refresh_tv_user_scheduled()
            RETURNS void AS $$
            BEGIN
                REFRESH MATERIALIZED VIEW CONCURRENTLY tv_user;
            END;
            $$ LANGUAGE plpgsql;

            -- Schedule refresh every 30 minutes
            SELECT cron.schedule('refresh_tv_user', '30 minutes', 'SELECT refresh_tv_user_scheduled()');
        ";

        // Validate scheduled structure
        assert!(
            scheduled_ddl.contains("REFRESH MATERIALIZED VIEW"),
            "Should have refresh view statement"
        );
        assert!(scheduled_ddl.contains("cron.schedule"), "Should use pg_cron for scheduling");
        assert!(scheduled_ddl.contains("30 minutes"), "Should specify refresh interval");
    }

    /// Test 7: Complex schema with relationships
    #[test]
    fn test_generate_views_with_relationships() {
        let schema: serde_json::Value =
            serde_json::from_str(ORDERS_SCHEMA).expect("Failed to parse schema JSON");

        // Verify schema is valid
        assert!(schema.get("types").is_some(), "Schema should have types");
        assert!(schema.get("version").is_some(), "Schema should have version");

        let types = schema["types"].as_array().expect("types should be array");

        // Verify Order entity
        let order_type = types
            .iter()
            .find(|t| t.get("name").map(|v| v.as_str()) == Some(Some("Order")))
            .expect("Order entity should exist");

        assert!(order_type.get("fields").is_some(), "Order should have fields");
    }

    /// Test 8: DDL file output with proper headers
    #[test]
    fn test_ddl_file_output_format() {
        // Example complete DDL output
        let complete_ddl = r"
-- FraiseQL DDL Generation Output
-- Schema: user.json
-- View: tv_user
-- Generated: 2024-01-24T12:00:00Z
-- See: https://fraiseql.dev/docs/views

-- Table Definition
CREATE TABLE IF NOT EXISTS tv_user (
    entity_id INTEGER NOT NULL UNIQUE,
    entity_json JSONB NOT NULL,
    is_stale BOOLEAN DEFAULT false,
    last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Indexes
CREATE INDEX IF NOT EXISTS idx_tv_user_entity_id ON tv_user(entity_id);
CREATE INDEX IF NOT EXISTS idx_tv_user_entity_json_gin ON tv_user USING GIN(entity_json);

-- Documentation
COMMENT ON TABLE tv_user IS 'Table-backed JSON view for User entity';
        ";

        // Validate DDL format
        assert!(complete_ddl.contains("FraiseQL DDL Generation Output"));
        assert!(complete_ddl.contains("CREATE TABLE"));
        assert!(complete_ddl.contains("CREATE INDEX"));
        assert!(complete_ddl.contains("COMMENT ON"));
    }

    /// Test 9: Composition views for relationships
    #[test]
    fn test_composition_views_ddl() {
        // Example composition view DDL
        let composition_ddl = r"
            -- Composition view for User -> Posts relationship
            CREATE OR REPLACE VIEW cv_user_posts AS
            SELECT
                u.entity_id as user_id,
                u.entity_json as user_data,
                p.entity_json as post_data
            FROM tv_user u
            LEFT JOIN tv_post p ON p.entity_json->>'user_id' = u.entity_json->>'id'
            ORDER BY u.entity_id, p.entity_id;

            -- Batch composition function
            CREATE OR REPLACE FUNCTION batch_compose_user(batch_ids INTEGER[])
            RETURNS TABLE (user_id INTEGER, user_data JSONB, posts JSONB[])
            AS $$
            SELECT
                u.entity_id,
                u.entity_json,
                ARRAY_AGG(p.entity_json) FILTER (WHERE p.entity_id IS NOT NULL)
            FROM tv_user u
            LEFT JOIN tv_post p ON p.entity_json->>'user_id' = u.entity_json->>'id'
            WHERE u.entity_id = ANY(batch_ids)
            GROUP BY u.entity_id, u.entity_json;
            $$ LANGUAGE SQL;
        ";

        // Validate composition view structure
        assert!(
            composition_ddl.contains("CREATE OR REPLACE VIEW cv_"),
            "Should create composition view"
        );
        assert!(composition_ddl.contains("LEFT JOIN"), "Should use LEFT JOIN for relationships");
        assert!(
            composition_ddl.contains("batch_compose_"),
            "Should provide batch composition function"
        );
    }

    /// Test 10: Monitoring and observability functions
    #[test]
    fn test_monitoring_functions_ddl() {
        // Example monitoring DDL
        let monitoring_ddl = r"
            -- Staleness check function
            CREATE OR REPLACE FUNCTION check_staleness_user()
            RETURNS TABLE (is_stale BOOLEAN, last_updated TIMESTAMP, staleness_ms INTEGER)
            AS $$
            SELECT
                is_stale,
                last_updated,
                EXTRACT(EPOCH FROM (NOW() - last_updated))::INTEGER * 1000
            FROM tv_user
            ORDER BY last_updated ASC
            LIMIT 1;
            $$ LANGUAGE SQL;

            -- Staleness view
            CREATE OR REPLACE VIEW v_staleness_user AS
            SELECT
                entity_id,
                last_updated,
                EXTRACT(EPOCH FROM (NOW() - last_updated))::INTEGER * 1000 as staleness_ms,
                CASE
                    WHEN is_stale THEN 'STALE'
                    ELSE 'FRESH'
                END as status
            FROM tv_user
            ORDER BY staleness_ms DESC;
        ";

        // Validate monitoring functions
        assert!(
            monitoring_ddl.contains("check_staleness_"),
            "Should provide staleness check function"
        );
        assert!(monitoring_ddl.contains("v_staleness_"), "Should provide staleness view");
        assert!(monitoring_ddl.contains("NOW()"), "Should check current timestamp");
    }
}