cqlite-cli 0.11.0

Command-line interface for CQLite — read Apache Cassandra 5.0 SSTables without a cluster
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
//! Tests for Issue #142: Optional fallback for `-e SELECT` to read-sstable
//!
//! This test suite validates the experimental SELECT fallback feature that routes
//! `-e SELECT` commands to read-sstable when ingestion is unavailable (no schema/data-dir).
//!
//! **IMPORTANT**: This is a TEMPORARY feature (disabled by default) that will be
//! removed in M3 after ingestion stabilizes.
//!
//! Test Coverage:
//! - Flag defaults to false (disabled by default)
//! - Flag can be enabled via CLI flag
//! - Flag can be enabled via environment variable
//! - Fallback only activates when ingestion unavailable
//! - Simple SELECT query parsing works correctly
//! - Warning message appears when fallback is used

#![cfg(all(test, feature = "state_machine"))]
#![allow(clippy::all)]

use assert_cmd::Command;
use std::path::PathBuf;

// ============================================================================
// Helper Functions
// ============================================================================

/// Get test data root directory for fallback tests
fn get_test_data_root() -> PathBuf {
    let root = std::env::var("CQLITE_DATASETS_ROOT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let manifest_dir = env!("CARGO_MANIFEST_DIR");
            PathBuf::from(manifest_dir)
                .parent()
                .expect("Failed to get parent directory")
                .join("test-data/datasets")
        });
    // Check if sstables subdirectory exists (CI convention)
    let sstables_path = root.join("sstables");
    if sstables_path.exists() {
        sstables_path
    } else {
        root
    }
}

/// Get path to simple_table test data
fn get_simple_table_path() -> PathBuf {
    let root = get_test_data_root();
    let table_dir = root
        .join("test_basic")
        .join("simple_table-6aa08200a25111f0a3fef1a551383fb9");

    // Return the Data.db file path
    table_dir.join("nb-1-big-Data.db")
}

/// Get path to schemas directory
fn get_schemas_dir() -> PathBuf {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    PathBuf::from(manifest_dir)
        .parent()
        .expect("Failed to get parent directory")
        .join("test-data/schemas")
}

// ============================================================================
// Test Cases - Flag Behavior
// ============================================================================

#[test]
fn test_fallback_disabled_by_default() {
    // Create command without the flag
    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    // Use a SELECT query without schema/data-dir (ingestion unavailable)
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.arg("-e").arg(&query).arg("--format").arg("json");

    let output = cmd.output().expect("Failed to execute command");

    // Should fail because:
    // 1. Fallback is disabled by default
    // 2. Ingestion is unavailable (no schema/data-dir)
    // 3. Query engine will fail without ingestion
    assert!(
        !output.status.success(),
        "Command should fail when fallback disabled and ingestion unavailable"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should NOT see fallback warning
    assert!(
        !stderr.contains("Using experimental read-sstable fallback"),
        "Should not use fallback when disabled by default"
    );
}

#[test]
fn test_fallback_enabled_with_flag() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    // Should succeed with fallback enabled
    assert!(
        output.status.success(),
        "Command should succeed with fallback enabled. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should see fallback warning
    assert!(
        stderr.contains("Using experimental read-sstable fallback"),
        "Should show fallback warning when enabled. stderr: {}",
        stderr
    );
}

#[test]
fn test_fallback_enabled_with_env() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.env("CQLITE_ENABLE_SELECT_FALLBACK", "true")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    // Should succeed with fallback enabled via env var
    assert!(
        output.status.success(),
        "Command should succeed with fallback enabled via env. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should see fallback warning
    assert!(
        stderr.contains("Using experimental read-sstable fallback"),
        "Should show fallback warning when enabled via env. stderr: {}",
        stderr
    );
}

// ============================================================================
// Test Cases - Conditional Activation
// ============================================================================

#[test]
fn test_fallback_requires_ingestion_unavailable() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    // Use the correct schema file path
    let schema_file = get_schemas_dir().join("basic-types.cql");

    assert!(
        schema_file.exists(),
        "Test requires full SSTable dataset: schema file not found at {}",
        schema_file.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    // Provide schema AND data-dir (ingestion AVAILABLE)
    cmd.arg("--enable-select-fallback")
        .arg("--schema")
        .arg(&schema_file)
        .arg("--dataset")
        .arg("test_basic")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should NOT use fallback because ingestion is available
    // (has both schema and dataset)
    assert!(
        !stderr.contains("Using experimental read-sstable fallback"),
        "Should not use fallback when ingestion is available (schema + dataset provided). stderr: {}",
        stderr
    );
}

#[test]
fn test_fallback_only_for_select_queries() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let query = format!("DESCRIBE TABLE {}", table_path.display());

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should NOT use fallback for non-SELECT queries
    assert!(
        !stderr.contains("Using experimental read-sstable fallback"),
        "Should not use fallback for non-SELECT queries. stderr: {}",
        stderr
    );
}

// ============================================================================
// Test Cases - Query Parsing
// ============================================================================

#[test]
fn test_fallback_simple_select_parsing() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    // Test various SELECT query formats
    let queries = vec![
        format!("SELECT * FROM {}", table_path.display()),
        format!("select * from {}", table_path.display()),
        format!("  SELECT   *   FROM   {}  ", table_path.display()),
        format!("SELECT * FROM {};", table_path.display()),
    ];

    for query in queries {
        let mut test_cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

        test_cmd
            .arg("--enable-select-fallback")
            .arg("-e")
            .arg(&query)
            .arg("--format")
            .arg("json");

        let output = test_cmd.output().expect("Failed to execute command");

        let stderr = String::from_utf8_lossy(&output.stderr);

        // All variants should successfully use fallback
        assert!(
            stderr.contains("Using experimental read-sstable fallback"),
            "Query '{}' should trigger fallback. stderr: {}",
            query,
            stderr
        );

        assert!(
            stderr.contains("Extracted table path"),
            "Query '{}' should extract table path. stderr: {}",
            query,
            stderr
        );
    }
}

#[test]
fn test_fallback_invalid_path_error() {
    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    // Use a path that doesn't exist
    let query = "SELECT * FROM /nonexistent/path/to/table";

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    // Should fail because path doesn't exist
    assert!(
        !output.status.success(),
        "Command should fail when table path doesn't exist"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Should see error about path not existing
    assert!(
        stderr.contains("Table path does not exist")
            || stderr.contains("SELECT fallback failed")
            || stderr.contains("not found"),
        "Should show error about invalid path. stderr: {}",
        stderr
    );
}

// ============================================================================
// Test Cases - Output Format Validation
// ============================================================================

#[test]
fn test_fallback_json_output() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json")
        .arg("--limit")
        .arg("3");

    let output = cmd.output().expect("Failed to execute command");

    assert!(
        output.status.success(),
        "Command should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Filter out log lines and get the actual JSON output
    let json_output: Vec<&str> = stdout
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty()
                && !line.starts_with("📖")
                && !line.starts_with("Displaying")
                && !line.starts_with("")
                && !(line.starts_with('[') && line.contains("202"))
        })
        .collect();

    let json_str = json_output.join("\n");

    // Should be valid JSON
    let parse_result = serde_json::from_str::<serde_json::Value>(&json_str);
    assert!(
        parse_result.is_ok(),
        "Output should be valid JSON. Got: {}",
        json_str
    );
}

#[test]
fn test_fallback_csv_output() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("csv")
        .arg("--limit")
        .arg("3");

    let output = cmd.output().expect("Failed to execute command");

    assert!(
        output.status.success(),
        "Command should succeed. stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);

    // Filter out log lines
    let csv_output: Vec<&str> = stdout
        .lines()
        .filter(|line| {
            let trimmed = line.trim();
            !trimmed.is_empty()
                && !line.starts_with("📖")
                && !line.starts_with("Displaying")
                && !(line.starts_with('[') && line.contains("202"))
        })
        .collect();

    let csv_str = csv_output.join("\n");

    // Should have CSV structure (header + data rows with commas)
    assert!(
        csv_str.contains(','),
        "CSV output should contain commas. Got: {}",
        csv_str
    );

    let lines: Vec<&str> = csv_str.lines().collect();
    assert!(
        lines.len() >= 2,
        "CSV should have at least header + 1 data row. Got {} lines",
        lines.len()
    );
}

// ============================================================================
// Test Cases - Warning Message
// ============================================================================

#[test]
fn test_fallback_warning_message() {
    let table_path = get_simple_table_path();
    assert!(
        table_path.exists(),
        "Test requires full SSTable dataset: test data not found at {}",
        table_path.display()
    );

    let mut cmd = Command::cargo_bin("cqlite").expect("Failed to find cqlite binary");

    let query = format!("SELECT * FROM {}", table_path.display());

    cmd.arg("--enable-select-fallback")
        .arg("-e")
        .arg(&query)
        .arg("--format")
        .arg("json");

    let output = cmd.output().expect("Failed to execute command");

    let stderr = String::from_utf8_lossy(&output.stderr);

    // Verify all required warning elements are present
    assert!(
        stderr.contains("⚠️"),
        "Warning should include warning emoji. stderr: {}",
        stderr
    );

    assert!(
        stderr.contains("experimental"),
        "Warning should mention 'experimental'. stderr: {}",
        stderr
    );

    assert!(
        stderr.contains("read-sstable fallback"),
        "Warning should mention 'read-sstable fallback'. stderr: {}",
        stderr
    );

    assert!(
        stderr.contains("temporary feature"),
        "Warning should mention 'temporary feature'. stderr: {}",
        stderr
    );

    assert!(
        stderr.contains("disabled by default"),
        "Warning should mention 'disabled by default'. stderr: {}",
        stderr
    );
}