opensky 0.2.1

Rust client for OpenSky Network Trino database
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
//! SQL query builder for OpenSky Trino database.
//!
//! Note: OpenSky stores timestamps as Unix epoch integers, not SQL TIMESTAMP types.

use crate::types::{QueryParams, RawTable, FLIGHT_COLUMNS, FLIGHTLIST_COLUMNS, RAWDATA_COLUMNS};
use chrono::{NaiveDateTime, Duration, Timelike};

/// The main table for state vector data.
const STATE_VECTORS_TABLE: &str = "minio.osky.state_vectors_data4";

/// The flights table for flight lists and airport filtering.
const FLIGHTS_TABLE: &str = "minio.osky.flights_data4";

/// Build a SQL query for the history() method.
///
/// This generates a SELECT statement against state_vectors_data4,
/// optionally joining with flights_data4 for airport filtering.
pub fn build_history_query(params: &QueryParams) -> String {
    let columns = FLIGHT_COLUMNS.join(", ");

    let has_airport_filter = params.departure_airport.is_some()
        || params.arrival_airport.is_some()
        || params.airport.is_some();

    if has_airport_filter {
        build_airport_join_query(params, &columns)
    } else {
        build_simple_query(params, &columns)
    }
}

/// Build a simple query without airport join.
fn build_simple_query(params: &QueryParams, columns: &str) -> String {
    let mut sql = format!(
        "SELECT {columns}\nFROM {STATE_VECTORS_TABLE}\nWHERE 1=1"
    );

    // Time filters (required for partition pruning)
    // Note: OpenSky stores time/hour as Unix timestamps (integers)
    if let (Some(start), Some(stop)) = (&params.start, &params.stop) {
        let start_ts = datetime_to_unix(start);
        let stop_ts = datetime_to_unix(stop);
        let (start_hour_ts, stop_hour_ts) = compute_hour_bounds_unix(start, stop);

        sql.push_str(&format!("\n  AND time >= {start_ts}"));
        sql.push_str(&format!("\n  AND time <= {stop_ts}"));
        sql.push_str(&format!("\n  AND hour >= {start_hour_ts}"));
        sql.push_str(&format!("\n  AND hour < {stop_hour_ts}"));
    }

    // ICAO24 filter
    if let Some(icao24) = &params.icao24 {
        let icao24_lower = icao24.to_lowercase();
        if icao24_lower.contains('%') || icao24_lower.contains('_') {
            sql.push_str(&format!("\n  AND icao24 LIKE '{}'", escape_sql(&icao24_lower)));
        } else {
            sql.push_str(&format!("\n  AND icao24 = '{}'", escape_sql(&icao24_lower)));
        }
    }

    // Callsign filter
    if let Some(callsign) = &params.callsign {
        if callsign.contains('%') || callsign.contains('_') {
            sql.push_str(&format!("\n  AND callsign LIKE '{}'", escape_sql(callsign)));
        } else {
            sql.push_str(&format!("\n  AND callsign = '{}'", escape_sql(callsign)));
        }
    }

    // Geographic bounds
    if let Some(bounds) = &params.bounds {
        sql.push_str(&format!("\n  AND lon >= {}", bounds.west));
        sql.push_str(&format!("\n  AND lon <= {}", bounds.east));
        sql.push_str(&format!("\n  AND lat >= {}", bounds.south));
        sql.push_str(&format!("\n  AND lat <= {}", bounds.north));
    }

    // Order and limit
    sql.push_str("\nORDER BY time");

    if let Some(limit) = params.limit {
        sql.push_str(&format!("\nLIMIT {limit}"));
    }

    sql
}

/// Build a query with airport join.
fn build_airport_join_query(params: &QueryParams, columns: &str) -> String {
    let (start, stop) = match (&params.start, &params.stop) {
        (Some(s), Some(e)) => (s.as_str(), e.as_str()),
        _ => return build_simple_query(params, columns),
    };

    let start_ts = datetime_to_unix(start);
    let stop_ts = datetime_to_unix(stop);
    let (start_hour_ts, stop_hour_ts) = compute_hour_bounds_unix(start, stop);
    let (start_day_ts, stop_day_ts) = compute_day_bounds_unix(start, stop);

    // Build the flights subquery
    let mut flights_where = vec![
        format!("day >= {start_day_ts}"),
        format!("day <= {stop_day_ts}"),
    ];

    if let Some(icao24) = &params.icao24 {
        flights_where.push(format!("icao24 = '{}'", escape_sql(&icao24.to_lowercase())));
    }
    if let Some(callsign) = &params.callsign {
        flights_where.push(format!("callsign = '{}'", escape_sql(callsign)));
    }
    if let Some(dep) = &params.departure_airport {
        flights_where.push(format!("estdepartureairport = '{}'", escape_sql(dep)));
    }
    if let Some(arr) = &params.arrival_airport {
        flights_where.push(format!("estarrivalairport = '{}'", escape_sql(arr)));
    }
    if let Some(airport) = &params.airport {
        flights_where.push(format!(
            "(estdepartureairport = '{}' OR estarrivalairport = '{}')",
            escape_sql(airport), escape_sql(airport)
        ));
    }

    let flights_subquery = format!(
        r#"SELECT icao24, callsign, firstseen, lastseen
FROM {FLIGHTS_TABLE}
WHERE {}"#,
        flights_where.join("\n  AND ")
    );

    // Build the main query with join
    // Prefix all columns with sv. alias
    let prefixed_columns = columns.split(", ").map(|c| format!("sv.{c}")).collect::<Vec<_>>().join(", ");

    let mut sql = format!(
        r#"SELECT {prefixed_columns}
FROM {STATE_VECTORS_TABLE} sv
JOIN ({flights_subquery}) fl
  ON sv.icao24 = fl.icao24 AND sv.callsign = fl.callsign
WHERE sv.time >= fl.firstseen
  AND sv.time <= fl.lastseen
  AND sv.time >= {start_ts}
  AND sv.time <= {stop_ts}
  AND sv.hour >= {start_hour_ts}
  AND sv.hour < {stop_hour_ts}"#
    );

    // Geographic bounds
    if let Some(bounds) = &params.bounds {
        sql.push_str(&format!("\n  AND sv.lon >= {}", bounds.west));
        sql.push_str(&format!("\n  AND sv.lon <= {}", bounds.east));
        sql.push_str(&format!("\n  AND sv.lat >= {}", bounds.south));
        sql.push_str(&format!("\n  AND sv.lat <= {}", bounds.north));
    }

    sql.push_str("\nORDER BY sv.time");

    if let Some(limit) = params.limit {
        sql.push_str(&format!("\nLIMIT {limit}"));
    }

    sql
}

/// Convert datetime string to Unix timestamp.
fn datetime_to_unix(dt_str: &str) -> i64 {
    let dt = NaiveDateTime::parse_from_str(dt_str, "%Y-%m-%d %H:%M:%S")
        .unwrap_or_else(|_| {
            NaiveDateTime::parse_from_str(&format!("{} 00:00:00", dt_str), "%Y-%m-%d %H:%M:%S")
                .unwrap()
        });
    dt.and_utc().timestamp()
}

/// Compute hour bounds as Unix timestamps for partition pruning.
/// Returns (floor to hour, ceil to hour + 1).
fn compute_hour_bounds_unix(start: &str, stop: &str) -> (i64, i64) {
    let start_dt = NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S")
        .unwrap_or_else(|_| NaiveDateTime::parse_from_str(&format!("{} 00:00:00", start), "%Y-%m-%d %H:%M:%S").unwrap());
    let stop_dt = NaiveDateTime::parse_from_str(stop, "%Y-%m-%d %H:%M:%S")
        .unwrap_or_else(|_| NaiveDateTime::parse_from_str(&format!("{} 23:59:59", stop), "%Y-%m-%d %H:%M:%S").unwrap());

    // Floor start to hour
    let start_hour = start_dt
        .with_minute(0).unwrap()
        .with_second(0).unwrap();

    // Ceil stop to next hour
    let stop_hour = stop_dt
        .with_minute(0).unwrap()
        .with_second(0).unwrap()
        + Duration::hours(1);

    (
        start_hour.and_utc().timestamp(),
        stop_hour.and_utc().timestamp(),
    )
}

/// Compute day bounds as Unix timestamps for flights table.
fn compute_day_bounds_unix(start: &str, stop: &str) -> (i64, i64) {
    let start_dt = NaiveDateTime::parse_from_str(start, "%Y-%m-%d %H:%M:%S")
        .unwrap_or_else(|_| NaiveDateTime::parse_from_str(&format!("{} 00:00:00", start), "%Y-%m-%d %H:%M:%S").unwrap());
    let stop_dt = NaiveDateTime::parse_from_str(stop, "%Y-%m-%d %H:%M:%S")
        .unwrap_or_else(|_| NaiveDateTime::parse_from_str(&format!("{} 23:59:59", stop), "%Y-%m-%d %H:%M:%S").unwrap());

    let start_day = start_dt.date().and_hms_opt(0, 0, 0).unwrap();
    let stop_day = (stop_dt.date() + Duration::days(1)).and_hms_opt(0, 0, 0).unwrap();

    (
        start_day.and_utc().timestamp(),
        stop_day.and_utc().timestamp(),
    )
}

/// Escape single quotes in SQL strings.
fn escape_sql(s: &str) -> String {
    s.replace('\'', "''")
}

/// Build a SQL query for the flightlist() method.
///
/// This generates a SELECT statement against flights_data4.
/// Behavior matches pyopensky: when departure_airport is set, filters by firstseen;
/// otherwise filters by lastseen.
///
/// If only start time is provided (no stop), defaults to end of the same day (23:59:59).
pub fn build_flightlist_query(params: &QueryParams) -> String {
    let columns = FLIGHTLIST_COLUMNS.join(", ");

    let mut sql = format!(
        "SELECT {columns}\nFROM {FLIGHTS_TABLE}\nWHERE 1=1"
    );

    // Time and day bounds (required for partition pruning)
    // If only start is provided, default stop to end of the same day
    let (start_opt, stop_opt) = match (&params.start, &params.stop) {
        (Some(start), Some(stop)) => (Some(start.clone()), Some(stop.clone())),
        (Some(start), None) => {
            // Default stop to end of start day (23:59:59)
            let day = &start[..10]; // Extract YYYY-MM-DD
            (Some(start.clone()), Some(format!("{} 23:59:59", day)))
        }
        _ => (None, None),
    };

    // pyopensky behavior: filter on firstseen if departure_airport is set, else lastseen
    if let (Some(start), Some(stop)) = (start_opt, stop_opt) {
        let start_ts = datetime_to_unix(&start);
        let stop_ts = datetime_to_unix(&stop);
        let (start_day_ts, stop_day_ts) = compute_day_bounds_unix(&start, &stop);

        // Day partition filter
        sql.push_str(&format!("\n  AND day >= {start_day_ts}"));
        sql.push_str(&format!("\n  AND day < {stop_day_ts}"));

        // Time filter: firstseen if departure filter, else lastseen
        if params.departure_airport.is_some() {
            sql.push_str(&format!("\n  AND firstseen >= {start_ts}"));
            sql.push_str(&format!("\n  AND firstseen <= {stop_ts}"));
        } else {
            sql.push_str(&format!("\n  AND lastseen >= {start_ts}"));
            sql.push_str(&format!("\n  AND lastseen <= {stop_ts}"));
        }
    }

    // ICAO24 filter
    if let Some(icao24) = &params.icao24 {
        let icao24_lower = icao24.to_lowercase();
        if icao24_lower.contains('%') || icao24_lower.contains('_') {
            sql.push_str(&format!("\n  AND icao24 LIKE '{}'", escape_sql(&icao24_lower)));
        } else {
            sql.push_str(&format!("\n  AND icao24 = '{}'", escape_sql(&icao24_lower)));
        }
    }

    // Callsign filter
    if let Some(callsign) = &params.callsign {
        if callsign.contains('%') || callsign.contains('_') {
            sql.push_str(&format!("\n  AND callsign LIKE '{}'", escape_sql(callsign)));
        } else {
            sql.push_str(&format!("\n  AND callsign = '{}'", escape_sql(callsign)));
        }
    }

    // Departure airport
    if let Some(dep) = &params.departure_airport {
        sql.push_str(&format!("\n  AND estdepartureairport = '{}'", escape_sql(dep)));
    }

    // Arrival airport
    if let Some(arr) = &params.arrival_airport {
        sql.push_str(&format!("\n  AND estarrivalairport = '{}'", escape_sql(arr)));
    }

    // Either airport
    if let Some(airport) = &params.airport {
        sql.push_str(&format!(
            "\n  AND (estdepartureairport = '{}' OR estarrivalairport = '{}')",
            escape_sql(airport), escape_sql(airport)
        ));
    }

    // Order by firstseen
    sql.push_str("\nORDER BY firstseen");

    if let Some(limit) = params.limit {
        sql.push_str(&format!("\nLIMIT {limit}"));
    }

    sql
}

/// Build a SQL query for the rawdata() method.
///
/// This generates a SELECT statement against raw message tables (e.g., rollcall_replies_data4).
/// Behavior matches pyopensky: when airport filters are set, joins with flights_data4.
pub fn build_rawdata_query(params: &QueryParams, table: RawTable) -> String {
    let table_name = table.table_name();
    let columns = RAWDATA_COLUMNS.join(", ");

    let has_airport_filter = params.departure_airport.is_some()
        || params.arrival_airport.is_some()
        || params.airport.is_some();

    if has_airport_filter {
        build_rawdata_airport_join_query(params, table_name, &columns)
    } else {
        build_rawdata_simple_query(params, table_name, &columns)
    }
}

/// Build a simple raw data query without airport join.
fn build_rawdata_simple_query(params: &QueryParams, table_name: &str, columns: &str) -> String {
    let mut sql = format!(
        "SELECT {columns}\nFROM {table_name}\nWHERE rawmsg IS NOT NULL"
    );

    // Time filters (required for partition pruning)
    // Raw tables use mintime (float) instead of time (int)
    if let (Some(start), Some(stop)) = (&params.start, &params.stop) {
        let start_ts = datetime_to_unix(start);
        let stop_ts = datetime_to_unix(stop);
        let (start_hour_ts, stop_hour_ts) = compute_hour_bounds_unix(start, stop);

        sql.push_str(&format!("\n  AND mintime >= {start_ts}"));
        sql.push_str(&format!("\n  AND mintime <= {stop_ts}"));
        sql.push_str(&format!("\n  AND hour >= {start_hour_ts}"));
        sql.push_str(&format!("\n  AND hour < {stop_hour_ts}"));
    }

    // ICAO24 filter
    if let Some(icao24) = &params.icao24 {
        let icao24_lower = icao24.to_lowercase();
        if icao24_lower.contains('%') || icao24_lower.contains('_') {
            sql.push_str(&format!("\n  AND icao24 LIKE '{}'", escape_sql(&icao24_lower)));
        } else {
            sql.push_str(&format!("\n  AND icao24 = '{}'", escape_sql(&icao24_lower)));
        }
    }

    // Order and limit
    sql.push_str("\nORDER BY mintime");

    if let Some(limit) = params.limit {
        sql.push_str(&format!("\nLIMIT {limit}"));
    }

    sql
}

/// Build a raw data query with airport join.
fn build_rawdata_airport_join_query(params: &QueryParams, table_name: &str, columns: &str) -> String {
    let (start, stop) = match (&params.start, &params.stop) {
        (Some(s), Some(e)) => (s.as_str(), e.as_str()),
        _ => return build_rawdata_simple_query(params, table_name, columns),
    };

    let start_ts = datetime_to_unix(start);
    let stop_ts = datetime_to_unix(stop);
    let (start_hour_ts, stop_hour_ts) = compute_hour_bounds_unix(start, stop);
    let (start_day_ts, stop_day_ts) = compute_day_bounds_unix(start, stop);

    // Build the flights subquery
    let mut flights_where = vec![
        format!("day >= {start_day_ts}"),
        format!("day <= {stop_day_ts}"),
    ];

    if let Some(icao24) = &params.icao24 {
        flights_where.push(format!("icao24 = '{}'", escape_sql(&icao24.to_lowercase())));
    }
    if let Some(dep) = &params.departure_airport {
        flights_where.push(format!("estdepartureairport = '{}'", escape_sql(dep)));
    }
    if let Some(arr) = &params.arrival_airport {
        flights_where.push(format!("estarrivalairport = '{}'", escape_sql(arr)));
    }
    if let Some(airport) = &params.airport {
        flights_where.push(format!(
            "(estdepartureairport = '{}' OR estarrivalairport = '{}')",
            escape_sql(airport), escape_sql(airport)
        ));
    }

    let flights_subquery = format!(
        r#"SELECT icao24, firstseen, lastseen
FROM {FLIGHTS_TABLE}
WHERE {}"#,
        flights_where.join("\n  AND ")
    );

    // Build the main query with join
    // Note: rawdata JOIN is only on icao24 (not callsign like history)
    let prefixed_columns = columns.split(", ").map(|c| format!("raw.{c}")).collect::<Vec<_>>().join(", ");

    let mut sql = format!(
        r#"SELECT {prefixed_columns}
FROM {table_name} raw
JOIN ({flights_subquery}) fl
  ON raw.icao24 = fl.icao24
WHERE raw.mintime >= fl.firstseen
  AND raw.mintime <= fl.lastseen
  AND raw.mintime >= {start_ts}
  AND raw.mintime <= {stop_ts}
  AND raw.hour >= {start_hour_ts}
  AND raw.hour < {stop_hour_ts}
  AND raw.rawmsg IS NOT NULL"#
    );

    sql.push_str("\nORDER BY raw.mintime");

    if let Some(limit) = params.limit {
        sql.push_str(&format!("\nLIMIT {limit}"));
    }

    sql
}

/// Build a preview of the query (for display purposes).
///
/// Uses "history" as the default method name. For other query types,
/// use `build_query_preview_method()`.
pub fn build_query_preview(params: &QueryParams) -> String {
    build_query_preview_method(params, "history")
}

/// Build a preview with a specific method name.
///
/// Method names: "history" (trajectory), "flightlist" (flights), "rawdata" (raw ADS-B)
pub fn build_query_preview_method(params: &QueryParams, method: &str) -> String {
    let mut parts = vec![format!("trino.{}(", method)];

    if let Some(start) = &params.start {
        parts.push(format!("    start=\"{start}\","));
    }
    if let Some(stop) = &params.stop {
        parts.push(format!("    stop=\"{stop}\","));
    }
    if let Some(icao24) = &params.icao24 {
        parts.push(format!("    icao24=\"{icao24}\","));
    }
    if let Some(callsign) = &params.callsign {
        parts.push(format!("    callsign=\"{callsign}\","));
    }
    if let Some(dep) = &params.departure_airport {
        parts.push(format!("    departure_airport=\"{dep}\","));
    }
    if let Some(arr) = &params.arrival_airport {
        parts.push(format!("    arrival_airport=\"{arr}\","));
    }
    if let Some(airport) = &params.airport {
        parts.push(format!("    airport=\"{airport}\","));
    }
    if let Some(bounds) = &params.bounds {
        parts.push(format!(
            "    bounds=({}, {}, {}, {}),",
            bounds.west, bounds.south, bounds.east, bounds.north
        ));
    }
    if let Some(limit) = params.limit {
        parts.push(format!("    limit={limit},"));
    }

    parts.push(")".to_string());
    parts.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_query() {
        let params = QueryParams::new()
            .icao24("485a32")
            .time_range("2025-01-01 10:00:00", "2025-01-01 12:00:00");

        let sql = build_history_query(&params);

        assert!(sql.contains("SELECT time, icao24"));
        assert!(sql.contains("FROM minio.osky.state_vectors_data4"));
        assert!(sql.contains("icao24 = '485a32'"));
        // Check for Unix timestamps (integers)
        assert!(sql.contains("time >= 1735725600"));  // 2025-01-01 10:00:00 UTC
        assert!(sql.contains("hour >= 1735725600"));
    }

    #[test]
    fn test_airport_query() {
        let params = QueryParams::new()
            .time_range("2025-01-01 00:00:00", "2025-01-01 23:59:59")
            .departure("EHAM")
            .arrival("EGLL");

        let sql = build_history_query(&params);

        assert!(sql.contains("JOIN"));
        assert!(sql.contains("flights_data4"));
        assert!(sql.contains("estdepartureairport = 'EHAM'"));
        assert!(sql.contains("estarrivalairport = 'EGLL'"));
    }

    #[test]
    fn test_wildcard_icao24() {
        let params = QueryParams::new()
            .icao24("485%")
            .time_range("2025-01-01 00:00:00", "2025-01-01 23:59:59");

        let sql = build_history_query(&params);

        assert!(sql.contains("icao24 LIKE '485%'"));
    }

    #[test]
    fn test_hour_bounds_unix() {
        let (start, stop) = compute_hour_bounds_unix("2025-01-01 10:30:00", "2025-01-01 12:45:00");

        // 2025-01-01 10:00:00 UTC = 1735725600
        // 2025-01-01 13:00:00 UTC = 1735736400
        assert_eq!(start, 1735725600);
        assert_eq!(stop, 1735736400);
    }

    #[test]
    fn test_datetime_to_unix() {
        // 2024-11-08 10:00:00 UTC = 1731060000
        let ts = datetime_to_unix("2024-11-08 10:00:00");
        assert_eq!(ts, 1731060000);
    }

    #[test]
    fn test_query_preview() {
        let params = QueryParams::new()
            .icao24("485a32")
            .time_range("2025-01-01 10:00:00", "2025-01-01 12:00:00")
            .departure("EHAM");

        let preview = build_query_preview(&params);

        assert!(preview.contains("trino.history("));
        assert!(preview.contains("icao24=\"485a32\""));
        assert!(preview.contains("departure_airport=\"EHAM\""));
    }

    #[test]
    fn test_flightlist_query() {
        let params = QueryParams::new()
            .time_range("2025-01-01 00:00:00", "2025-01-01 23:59:59")
            .departure("EHAM");

        let sql = build_flightlist_query(&params);

        assert!(sql.contains("SELECT icao24, callsign, firstseen, lastseen"));
        assert!(sql.contains("FROM minio.osky.flights_data4"));
        assert!(sql.contains("estdepartureairport = 'EHAM'"));
        assert!(sql.contains("day >="));
        assert!(sql.contains("ORDER BY firstseen"));
    }

    #[test]
    fn test_flightlist_with_airport() {
        let params = QueryParams::new()
            .time_range("2025-01-01 00:00:00", "2025-01-01 23:59:59")
            .departure("EHAM")
            .arrival("EGLL");

        let sql = build_flightlist_query(&params);

        assert!(sql.contains("estdepartureairport = 'EHAM'"));
        assert!(sql.contains("estarrivalairport = 'EGLL'"));
    }

    #[test]
    fn test_rawdata_simple_query() {
        let params = QueryParams::new()
            .icao24("485a32")
            .time_range("2025-01-01 10:00:00", "2025-01-01 12:00:00");

        let sql = build_rawdata_query(&params, RawTable::RollcallReplies);

        assert!(sql.contains("SELECT mintime, rawmsg, icao24"));
        assert!(sql.contains("FROM minio.osky.rollcall_replies_data4"));
        assert!(sql.contains("rawmsg IS NOT NULL"));
        assert!(sql.contains("icao24 = '485a32'"));
        assert!(sql.contains("ORDER BY mintime"));
    }

    #[test]
    fn test_rawdata_position_table() {
        let params = QueryParams::new()
            .icao24("485a32")
            .time_range("2025-01-01 10:00:00", "2025-01-01 12:00:00");

        let sql = build_rawdata_query(&params, RawTable::Position);

        assert!(sql.contains("FROM minio.osky.position_data4"));
    }

    #[test]
    fn test_rawdata_with_airport() {
        let params = QueryParams::new()
            .time_range("2025-01-01 00:00:00", "2025-01-01 23:59:59")
            .departure("EHAM");

        let sql = build_rawdata_query(&params, RawTable::RollcallReplies);

        assert!(sql.contains("JOIN"));
        assert!(sql.contains("flights_data4"));
        assert!(sql.contains("estdepartureairport = 'EHAM'"));
        // rawdata JOIN is only on icao24, not callsign
        assert!(sql.contains("ON raw.icao24 = fl.icao24"));
        assert!(sql.contains("raw.mintime >= fl.firstseen"));
    }

    #[test]
    fn test_flightlist_start_only_defaults_stop() {
        // When only start is provided (no stop), should default stop to end of same day
        let mut params = QueryParams::new();
        params.start = Some("2025-01-15 10:00:00".to_string());
        // Note: no stop time set

        let sql = build_flightlist_query(&params);

        // Should still have day partition filter
        assert!(sql.contains("day >="));
        assert!(sql.contains("day <"));
        // Should have time filter (defaulting to 23:59:59)
        assert!(sql.contains("lastseen >="));
        assert!(sql.contains("lastseen <="));
    }
}