flowscope-cli 0.6.0

Command-line interface for FlowScope SQL lineage analyzer
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
//! Integration tests for serve mode.
//!
//! These tests spawn an actual HTTP server and make real HTTP requests
//! to verify the full request/response cycle.

#![cfg(feature = "serve")]

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use flowscope_cli::server::{build_router, scan_sql_files, state::AppState, state::ServerConfig};
use flowscope_core::{Dialect, FileSource};
use serde_json::{json, Value};
use tempfile::TempDir;
use tokio::sync::RwLock;

/// Find an available port for testing.
fn get_available_port() -> u16 {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    listener.local_addr().unwrap().port()
}

/// Create a test AppState directly without disk I/O.
fn test_state_from_files(config: ServerConfig, files: Vec<FileSource>) -> Arc<AppState> {
    Arc::new(AppState {
        config,
        files: RwLock::new(files),
        schema: RwLock::new(None),
        mtimes: RwLock::new(HashMap::new()),
    })
}

/// Spawn a test server and return the base URL.
async fn spawn_test_server(
    config: ServerConfig,
    files: Vec<FileSource>,
) -> (String, tokio::task::JoinHandle<()>) {
    let port = config.port;
    let state = test_state_from_files(config, files);
    let app = build_router(state, port);

    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();

    let handle = tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    // Give the server a moment to start
    tokio::time::sleep(Duration::from_millis(10)).await;

    (format!("http://127.0.0.1:{}", port), handle)
}

// === Integration test: Server startup and health endpoint ===

#[tokio::test]
async fn server_starts_and_responds_to_health() {
    let port = get_available_port();
    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    let (base_url, server_handle) = spawn_test_server(config, vec![]).await;

    let client = reqwest::Client::new();
    let response = client
        .get(format!("{}/api/health", base_url))
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success());

    let body: Value = response.json().await.unwrap();
    assert_eq!(body["status"], "ok");
    assert!(body["version"].is_string());

    server_handle.abort();
}

// === Integration test: Analyze endpoint with sample SQL ===

#[tokio::test]
async fn analyze_endpoint_processes_complex_query() {
    let port = get_available_port();
    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    let (base_url, server_handle) = spawn_test_server(config, vec![]).await;

    let client = reqwest::Client::new();

    // Test with a complex query involving joins and subqueries
    let response = client
        .post(format!("{}/api/analyze", base_url))
        .json(&json!({
            "sql": r#"
                WITH active_users AS (
                    SELECT user_id, name
                    FROM users
                    WHERE status = 'active'
                )
                SELECT
                    au.name,
                    COUNT(o.id) as order_count,
                    SUM(o.total) as total_spent
                FROM active_users au
                LEFT JOIN orders o ON au.user_id = o.user_id
                GROUP BY au.name
            "#
        }))
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success());

    let body: Value = response.json().await.unwrap();

    // Verify the analysis result structure
    assert!(body["statements"].is_array());
    let statements = body["statements"].as_array().unwrap();
    assert!(!statements.is_empty());

    // The result should contain lineage information (nodes and edges arrays)
    let first_stmt = &statements[0];
    assert!(first_stmt["nodes"].is_array());
    assert!(first_stmt["edges"].is_array());

    server_handle.abort();
}

#[tokio::test]
async fn analyze_endpoint_with_multiple_files() {
    let port = get_available_port();
    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    let files = vec![
        FileSource {
            name: "views/user_summary.sql".to_string(),
            content: "CREATE VIEW user_summary AS SELECT id, name FROM users".to_string(),
        },
        FileSource {
            name: "queries/report.sql".to_string(),
            content: "SELECT * FROM user_summary".to_string(),
        },
    ];

    let (base_url, server_handle) = spawn_test_server(config, files.clone()).await;

    let client = reqwest::Client::new();

    // Analyze with files from state
    let response = client
        .post(format!("{}/api/analyze", base_url))
        .json(&json!({
            "sql": "SELECT name FROM user_summary",
            "files": files
        }))
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success());

    let body: Value = response.json().await.unwrap();
    assert!(body["statements"].is_array());

    server_handle.abort();
}

// === Integration test: File watcher triggers update ===

#[tokio::test]
async fn file_watcher_detects_sql_files() {
    // Create a temp directory with SQL files
    let temp_dir = TempDir::new().unwrap();
    let sql_file = temp_dir.path().join("test.sql");
    std::fs::write(&sql_file, "SELECT 1").unwrap();

    // Verify scan_sql_files works
    let (files, _mtimes) = scan_sql_files(&[temp_dir.path().to_path_buf()]).unwrap();
    assert_eq!(files.len(), 1);
    assert_eq!(files[0].name, "test.sql");
    assert_eq!(files[0].content, "SELECT 1");
}

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

    // Create both SQL and non-SQL files
    std::fs::write(temp_dir.path().join("query.sql"), "SELECT 1").unwrap();
    std::fs::write(temp_dir.path().join("readme.md"), "# Docs").unwrap();
    std::fs::write(temp_dir.path().join("config.json"), "{}").unwrap();

    let (files, _mtimes) = scan_sql_files(&[temp_dir.path().to_path_buf()]).unwrap();

    // Only SQL files should be included
    assert_eq!(files.len(), 1);
    assert_eq!(files[0].name, "query.sql");
}

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

    // Create nested directory structure
    let subdir = temp_dir.path().join("views");
    std::fs::create_dir(&subdir).unwrap();

    std::fs::write(temp_dir.path().join("main.sql"), "SELECT 1").unwrap();
    std::fs::write(subdir.join("user_view.sql"), "SELECT 2").unwrap();

    let (files, _mtimes) = scan_sql_files(&[temp_dir.path().to_path_buf()]).unwrap();

    assert_eq!(files.len(), 2);

    let names: Vec<&str> = files.iter().map(|f| f.name.as_str()).collect();
    assert!(names.contains(&"main.sql"));
    assert!(names.contains(&"views/user_view.sql"));
}

#[tokio::test]
async fn scan_sql_files_prefixes_multiple_watch_dirs() {
    let temp_dir = TempDir::new().unwrap();
    let first_dir = temp_dir.path().join("alpha_project");
    let second_dir = temp_dir.path().join("beta_project");
    std::fs::create_dir_all(first_dir.join("models")).unwrap();
    std::fs::create_dir_all(second_dir.join("models")).unwrap();

    std::fs::write(first_dir.join("models/foo.sql"), "SELECT 1").unwrap();
    std::fs::write(second_dir.join("models/foo.sql"), "SELECT 2").unwrap();

    let (files, _mtimes) = scan_sql_files(&[first_dir.clone(), second_dir.clone()]).unwrap();

    assert_eq!(files.len(), 2);
    let mut names: Vec<String> = files.iter().map(|f| f.name.clone()).collect();
    names.sort();

    let mut expected = vec![
        "alpha_project/models/foo.sql".to_string(),
        "beta_project/models/foo.sql".to_string(),
    ];
    expected.sort();

    assert_eq!(names, expected);
}

#[tokio::test]
async fn scan_sql_files_disambiguates_duplicate_watch_names() {
    let temp_dir = TempDir::new().unwrap();
    let first_dir = temp_dir.path().join("shared");
    let second_dir = temp_dir.path().join("nested").join("shared");
    std::fs::create_dir_all(first_dir.join("models")).unwrap();
    std::fs::create_dir_all(second_dir.join("models")).unwrap();

    std::fs::write(first_dir.join("models/foo.sql"), "SELECT 1").unwrap();
    std::fs::write(second_dir.join("models/foo.sql"), "SELECT 2").unwrap();

    let (files, _mtimes) = scan_sql_files(&[first_dir.clone(), second_dir.clone()]).unwrap();

    assert_eq!(files.len(), 2);
    let mut names: Vec<String> = files.iter().map(|f| f.name.clone()).collect();
    names.sort();

    let mut expected = vec![
        "shared/models/foo.sql".to_string(),
        "shared#2/models/foo.sql".to_string(),
    ];
    expected.sort();

    assert_eq!(names, expected);
}

#[tokio::test]
async fn app_state_reload_updates_files() {
    let temp_dir = TempDir::new().unwrap();
    std::fs::write(temp_dir.path().join("initial.sql"), "SELECT 1").unwrap();

    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![temp_dir.path().to_path_buf()],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port: 3000,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    // Create state with initial files
    let (files, mtimes) = scan_sql_files(&config.watch_dirs).unwrap();
    let state = Arc::new(AppState {
        config,
        files: RwLock::new(files),
        schema: RwLock::new(None),
        mtimes: RwLock::new(mtimes),
    });

    // Verify initial state
    {
        let files = state.files.read().await;
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].name, "initial.sql");
    }

    // Add a new file
    std::fs::write(temp_dir.path().join("new.sql"), "SELECT 2").unwrap();

    // Reload files
    state.reload_files().await.unwrap();

    // Verify updated state
    {
        let files = state.files.read().await;
        assert_eq!(files.len(), 2);
    }
}

// === Export endpoint integration tests ===

#[tokio::test]
async fn export_html_returns_valid_html() {
    let port = get_available_port();
    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    let (base_url, server_handle) = spawn_test_server(config, vec![]).await;

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/api/export/html", base_url))
        .json(&json!({
            "sql": "SELECT id, name FROM users"
        }))
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success());
    assert_eq!(response.headers().get("content-type").unwrap(), "text/html");

    let body = response.text().await.unwrap();
    assert!(body.contains("<!DOCTYPE html>") || body.contains("<html"));

    server_handle.abort();
}

#[tokio::test]
async fn export_csv_returns_zip() {
    let port = get_available_port();
    let config = ServerConfig {
        dialect: Dialect::Generic,
        watch_dirs: vec![],
        static_files: None,
        metadata_url: None,
        metadata_schema: None,
        port,
        open_browser: false,
        schema_path: None,
        #[cfg(feature = "templating")]
        template_config: None,
    };

    let (base_url, server_handle) = spawn_test_server(config, vec![]).await;

    let client = reqwest::Client::new();
    let response = client
        .post(format!("{}/api/export/csv", base_url))
        .json(&json!({
            "sql": "SELECT id FROM users"
        }))
        .send()
        .await
        .unwrap();

    assert!(response.status().is_success());
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "application/zip"
    );

    // Verify we got binary data
    let bytes = response.bytes().await.unwrap();
    assert!(!bytes.is_empty());

    server_handle.abort();
}