Skip to main content

polyglot_sql/
openlineage.rs

1//! OpenLineage-compatible payload generation.
2//!
3//! This module only builds OpenLineage JSON-compatible structures from SQL
4//! analysis. It deliberately does not implement transports, clients, retries,
5//! buffering, or runtime lifecycle management.
6
7use crate::dialects::{Dialect, DialectType};
8use crate::expressions::*;
9use crate::lineage::{self, LineageNode, SetOperator};
10use crate::schema::Schema;
11use crate::scope::SourceKind;
12use crate::traversal::{contains_aggregate, ExpressionWalk};
13use crate::{mapping_schema_from_validation_schema_with_dialect, Error, Result, ValidationSchema};
14use serde::de::{self, Deserializer};
15use serde::{Deserialize, Serialize};
16use serde_json::{json, Value};
17use std::collections::{BTreeMap, BTreeSet, HashSet};
18
19pub const OPENLINEAGE_SCHEMA_URL: &str = "https://openlineage.io/spec/2-0-2/OpenLineage.json";
20pub const COLUMN_LINEAGE_FACET_SCHEMA_URL: &str =
21    "https://openlineage.io/spec/facets/1-2-0/ColumnLineageDatasetFacet.json";
22pub const SQL_JOB_FACET_SCHEMA_URL: &str =
23    "https://openlineage.io/spec/facets/1-1-0/SQLJobFacet.json";
24pub const JOB_TYPE_JOB_FACET_SCHEMA_URL: &str =
25    "https://openlineage.io/spec/facets/2-0-3/JobTypeJobFacet.json";
26pub const SCHEMA_DATASET_FACET_SCHEMA_URL: &str =
27    "https://openlineage.io/spec/facets/1-2-0/SchemaDatasetFacet.json";
28
29/// Dataset identity in OpenLineage (`namespace`, `name`).
30#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
31#[serde(rename_all = "camelCase")]
32pub struct OpenLineageDatasetId {
33    pub namespace: String,
34    pub name: String,
35}
36
37impl OpenLineageDatasetId {
38    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
39        Self {
40            namespace: namespace.into(),
41            name: name.into(),
42        }
43    }
44}
45
46/// Options shared by OpenLineage payload generation helpers.
47#[derive(Debug, Clone, Serialize, Deserialize, Default)]
48#[serde(rename_all = "camelCase", default)]
49pub struct OpenLineageOptions {
50    #[serde(deserialize_with = "deserialize_dialect_type")]
51    pub dialect: DialectType,
52    pub producer: String,
53    pub dataset_namespace: Option<String>,
54    pub dataset_mappings: BTreeMap<String, OpenLineageDatasetId>,
55    pub output_dataset: Option<OpenLineageDatasetId>,
56    pub schema: Option<ValidationSchema>,
57    pub job_namespace: Option<String>,
58    pub job_name: Option<String>,
59    pub event_time: Option<String>,
60    pub run_id: Option<String>,
61    pub event_type: Option<OpenLineageRunEventType>,
62}
63
64/// OpenLineage run event type.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
67pub enum OpenLineageRunEventType {
68    Start,
69    Running,
70    Complete,
71    Abort,
72    Fail,
73    Other,
74}
75
76/// Non-fatal issue encountered while generating OpenLineage output.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "camelCase")]
79pub struct OpenLineageWarning {
80    pub code: String,
81    pub message: String,
82}
83
84impl OpenLineageWarning {
85    fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
86        Self {
87            code: code.into(),
88            message: message.into(),
89        }
90    }
91}
92
93#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
94#[serde(rename_all = "camelCase")]
95pub struct OpenLineageColumnLineageResult {
96    pub facet: ColumnLineageDatasetFacet,
97    pub inputs: Vec<OpenLineageDataset>,
98    pub outputs: Vec<OpenLineageDataset>,
99    pub warnings: Vec<OpenLineageWarning>,
100}
101
102#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
103#[serde(rename_all = "camelCase")]
104pub struct OpenLineageEventResult {
105    pub event: Value,
106    pub warnings: Vec<OpenLineageWarning>,
107}
108
109#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110pub struct OpenLineageDataset {
111    pub namespace: String,
112    pub name: String,
113    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
114    pub facets: BTreeMap<String, Value>,
115}
116
117impl std::convert::From<OpenLineageDatasetId> for OpenLineageDataset {
118    fn from(id: OpenLineageDatasetId) -> Self {
119        Self {
120            namespace: id.namespace,
121            name: id.name,
122            facets: BTreeMap::new(),
123        }
124    }
125}
126
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
128pub struct ColumnLineageDatasetFacet {
129    #[serde(rename = "_producer")]
130    pub producer: String,
131    #[serde(rename = "_schemaURL")]
132    pub schema_url: String,
133    pub fields: BTreeMap<String, ColumnLineageField>,
134}
135
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138pub struct ColumnLineageField {
139    pub input_fields: Vec<OpenLineageInputField>,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
143#[serde(rename_all = "camelCase")]
144pub struct OpenLineageInputField {
145    pub namespace: String,
146    pub name: String,
147    pub field: String,
148    #[serde(skip_serializing_if = "Vec::is_empty", default)]
149    pub transformations: Vec<OpenLineageTransformation>,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
153pub struct OpenLineageTransformation {
154    #[serde(rename = "type")]
155    pub type_: String,
156    pub subtype: String,
157    #[serde(skip_serializing_if = "Option::is_none")]
158    pub description: Option<String>,
159    #[serde(skip_serializing_if = "Option::is_none")]
160    pub masking: Option<bool>,
161}
162
163#[derive(Debug, Clone)]
164struct StatementAnalysis {
165    query: Expression,
166    inputs: Vec<OpenLineageDatasetId>,
167    output: OpenLineageDatasetId,
168    output_column_names: Vec<String>,
169}
170
171#[derive(Debug, Clone)]
172struct OutputField {
173    name: String,
174    lineage_name: String,
175    expression: Option<Expression>,
176    star_source_table: Option<String>,
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
180struct TerminalField {
181    table: String,
182    field: String,
183    dependency: TerminalDependency,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
187enum TerminalDependency {
188    Direct,
189    Filter,
190}
191
192/// Produce a standalone OpenLineage columnLineage facet plus inferred datasets.
193pub fn openlineage_column_lineage(
194    sql: &str,
195    options: &OpenLineageOptions,
196) -> Result<OpenLineageColumnLineageResult> {
197    validate_common_options(options)?;
198
199    let mut warnings = Vec::new();
200    let schema_mapping = options
201        .schema
202        .as_ref()
203        .map(|schema| mapping_schema_from_validation_schema_with_dialect(schema, options.dialect));
204    let dialect = Dialect::get(options.dialect);
205    let mut expressions = dialect.parse(sql)?;
206    if expressions.len() != 1 {
207        return Err(Error::parse(
208            format!(
209                "OpenLineage generation expects exactly one statement, found {}",
210                expressions.len()
211            ),
212            0,
213            0,
214            0,
215            0,
216        ));
217    }
218
219    let expr = expressions.remove(0);
220    let analysis = analyze_statement(&expr, options, &mut warnings)?;
221    let mut output_fields = output_fields_for_query(
222        &analysis.query,
223        schema_mapping.as_ref().map(|s| s as &dyn Schema),
224        options.dialect,
225        &mut warnings,
226    )?;
227    apply_output_column_names(
228        &mut output_fields,
229        &analysis.output_column_names,
230        &mut warnings,
231    );
232
233    let mut fields = BTreeMap::new();
234    for output_field in output_fields {
235        if fields.contains_key(&output_field.name) {
236            warnings.push(OpenLineageWarning::new(
237                "W_DUPLICATE_OUTPUT_FIELD",
238                format!(
239                    "Duplicate output field '{}' was merged in the OpenLineage fields map",
240                    output_field.name
241                ),
242            ));
243        }
244
245        let input_fields = input_fields_for_output(
246            &analysis.query,
247            &output_field,
248            options,
249            schema_mapping.as_ref().map(|s| s as &dyn Schema),
250            &mut warnings,
251        )?;
252
253        fields.insert(output_field.name, ColumnLineageField { input_fields });
254    }
255
256    let mut outputs = vec![OpenLineageDataset::from(analysis.output.clone())];
257    attach_output_facets(&mut outputs[0], &analysis.output, options, &fields)?;
258
259    Ok(OpenLineageColumnLineageResult {
260        facet: ColumnLineageDatasetFacet {
261            producer: options.producer.clone(),
262            schema_url: COLUMN_LINEAGE_FACET_SCHEMA_URL.to_string(),
263            fields,
264        },
265        inputs: analysis
266            .inputs
267            .into_iter()
268            .map(OpenLineageDataset::from)
269            .collect(),
270        outputs,
271        warnings,
272    })
273}
274
275/// Produce an OpenLineage JobEvent as JSON.
276pub fn openlineage_job_event(
277    sql: &str,
278    options: &OpenLineageOptions,
279) -> Result<OpenLineageEventResult> {
280    let job_namespace = required_option(&options.job_namespace, "jobNamespace")?;
281    let job_name = required_option(&options.job_name, "jobName")?;
282    let event_time = required_option(&options.event_time, "eventTime")?;
283
284    let result = openlineage_column_lineage(sql, options)?;
285    let event = json!({
286        "eventTime": event_time,
287        "producer": options.producer,
288        "schemaURL": OPENLINEAGE_SCHEMA_URL,
289        "job": {
290            "namespace": job_namespace,
291            "name": job_name,
292            "facets": job_facets(sql, options),
293        },
294        "inputs": result.inputs,
295        "outputs": result.outputs,
296    });
297
298    Ok(OpenLineageEventResult {
299        event,
300        warnings: result.warnings,
301    })
302}
303
304/// Produce an OpenLineage RunEvent as JSON.
305pub fn openlineage_run_event(
306    sql: &str,
307    options: &OpenLineageOptions,
308) -> Result<OpenLineageEventResult> {
309    let job_namespace = required_option(&options.job_namespace, "jobNamespace")?;
310    let job_name = required_option(&options.job_name, "jobName")?;
311    let event_time = required_option(&options.event_time, "eventTime")?;
312    let run_id = required_option(&options.run_id, "runId")?;
313    let event_type = options
314        .event_type
315        .ok_or_else(|| Error::parse("Missing required option: eventType", 0, 0, 0, 0))?;
316
317    let result = openlineage_column_lineage(sql, options)?;
318    let event = json!({
319        "eventTime": event_time,
320        "eventType": event_type,
321        "producer": options.producer,
322        "schemaURL": OPENLINEAGE_SCHEMA_URL,
323        "run": {
324            "runId": run_id,
325            "facets": {},
326        },
327        "job": {
328            "namespace": job_namespace,
329            "name": job_name,
330            "facets": job_facets(sql, options),
331        },
332        "inputs": result.inputs,
333        "outputs": result.outputs,
334    });
335
336    Ok(OpenLineageEventResult {
337        event,
338        warnings: result.warnings,
339    })
340}
341
342fn validate_common_options(options: &OpenLineageOptions) -> Result<()> {
343    if options.producer.trim().is_empty() {
344        return Err(Error::parse(
345            "Missing required option: producer",
346            0,
347            0,
348            0,
349            0,
350        ));
351    }
352    Ok(())
353}
354
355fn required_option(value: &Option<String>, name: &str) -> Result<String> {
356    match value.as_ref().filter(|v| !v.trim().is_empty()) {
357        Some(value) => Ok(value.clone()),
358        None => Err(Error::parse(
359            format!("Missing required option: {name}"),
360            0,
361            0,
362            0,
363            0,
364        )),
365    }
366}
367
368fn analyze_statement(
369    expr: &Expression,
370    options: &OpenLineageOptions,
371    warnings: &mut Vec<OpenLineageWarning>,
372) -> Result<StatementAnalysis> {
373    match expr {
374        Expression::Prepare(prepare) => analyze_statement(&prepare.statement, options, warnings),
375        Expression::Select(select) => {
376            let output = if let Some(into) = &select.into {
377                dataset_from_expression(&into.this, options)?
378            } else {
379                options.output_dataset.clone().ok_or_else(|| {
380                    Error::parse(
381                        "OpenLineage outputDataset is required for SELECT statements without SELECT INTO",
382                        0,
383                        0,
384                        0,
385                        0,
386                    )
387                })?
388            };
389            Ok(StatementAnalysis {
390                query: expr.clone(),
391                inputs: collect_input_datasets(expr, options, Some(&output), warnings)?,
392                output,
393                output_column_names: Vec::new(),
394            })
395        }
396        Expression::Union(_) | Expression::Intersect(_) | Expression::Except(_) => {
397            let output = options.output_dataset.clone().ok_or_else(|| {
398                Error::parse(
399                    "OpenLineage outputDataset is required for set-operation queries",
400                    0,
401                    0,
402                    0,
403                    0,
404                )
405            })?;
406            Ok(StatementAnalysis {
407                query: expr.clone(),
408                inputs: collect_input_datasets(expr, options, Some(&output), warnings)?,
409                output,
410                output_column_names: Vec::new(),
411            })
412        }
413        Expression::Insert(insert) => {
414            let output = dataset_from_table_ref(&insert.table, options)?;
415            let query = insert.query.clone().ok_or_else(|| {
416                Error::unsupported(
417                    "OpenLineage column lineage for INSERT without query",
418                    options.dialect.to_string(),
419                )
420            })?;
421            Ok(StatementAnalysis {
422                inputs: collect_input_datasets(&query, options, Some(&output), warnings)?,
423                query,
424                output,
425                output_column_names: insert.columns.iter().map(|col| col.name.clone()).collect(),
426            })
427        }
428        Expression::CreateTable(create) => {
429            let output = dataset_from_table_ref(&create.name, options)?;
430            let query = create.as_select.clone().ok_or_else(|| {
431                Error::unsupported(
432                    "OpenLineage column lineage for CREATE TABLE without AS SELECT",
433                    options.dialect.to_string(),
434                )
435            })?;
436            Ok(StatementAnalysis {
437                inputs: collect_input_datasets(&query, options, Some(&output), warnings)?,
438                query,
439                output,
440                output_column_names: create
441                    .columns
442                    .iter()
443                    .map(|col| col.name.name.clone())
444                    .collect(),
445            })
446        }
447        _ => Err(Error::unsupported(
448            format!("OpenLineage generation for {}", expr.variant_name()),
449            options.dialect.to_string(),
450        )),
451    }
452}
453
454fn output_fields_for_query(
455    query: &Expression,
456    schema: Option<&dyn Schema>,
457    dialect: DialectType,
458    warnings: &mut Vec<OpenLineageWarning>,
459) -> Result<Vec<OutputField>> {
460    let select = leftmost_select(query).ok_or_else(|| {
461        Error::unsupported(
462            "OpenLineage output field extraction for non-SELECT query",
463            dialect.to_string(),
464        )
465    })?;
466
467    let mut fields = Vec::new();
468    for (idx, expr) in select.expressions.iter().enumerate() {
469        if is_star_expr(expr) {
470            expand_star_output_fields(select, expr, schema, warnings, &mut fields);
471            continue;
472        }
473
474        let name = output_name(expr).unwrap_or_else(|| format!("_{idx}"));
475        fields.push(OutputField {
476            lineage_name: name.clone(),
477            name,
478            expression: Some(expr.clone()),
479            star_source_table: None,
480        });
481    }
482    Ok(fields)
483}
484
485fn apply_output_column_names(
486    fields: &mut [OutputField],
487    output_column_names: &[String],
488    warnings: &mut Vec<OpenLineageWarning>,
489) {
490    if output_column_names.is_empty() {
491        return;
492    }
493    if output_column_names.len() != fields.len() {
494        warnings.push(OpenLineageWarning::new(
495            "W_OUTPUT_COLUMN_COUNT_MISMATCH",
496            format!(
497                "Target column count ({}) does not match projected column count ({})",
498                output_column_names.len(),
499                fields.len()
500            ),
501        ));
502        return;
503    }
504    for (field, output_name) in fields.iter_mut().zip(output_column_names) {
505        field.name = output_name.clone();
506    }
507}
508
509fn input_fields_for_output(
510    query: &Expression,
511    output_field: &OutputField,
512    options: &OpenLineageOptions,
513    schema: Option<&dyn Schema>,
514    warnings: &mut Vec<OpenLineageWarning>,
515) -> Result<Vec<OpenLineageInputField>> {
516    if let Some(table) = &output_field.star_source_table {
517        return terminal_fields_to_openlineage(
518            vec![TerminalField {
519                table: table.clone(),
520                field: output_field.lineage_name.clone(),
521                dependency: TerminalDependency::Direct,
522            }],
523            "IDENTITY",
524            Some(format!("SELECT {}", output_field.lineage_name)),
525            options,
526            warnings,
527        );
528    }
529
530    let lineage_result = if let Some(schema) = schema {
531        lineage::lineage_with_schema(
532            &output_field.lineage_name,
533            query,
534            Some(schema),
535            Some(options.dialect),
536            false,
537        )
538    } else {
539        lineage::lineage(
540            &output_field.lineage_name,
541            query,
542            Some(options.dialect),
543            false,
544        )
545    };
546
547    let node = match lineage_result {
548        Ok(node) => node,
549        Err(err) => {
550            warnings.push(OpenLineageWarning::new(
551                "W_UNRESOLVED_OUTPUT_FIELD",
552                format!(
553                    "Could not resolve lineage for output field '{}': {}",
554                    output_field.name, err
555                ),
556            ));
557            return Ok(Vec::new());
558        }
559    };
560
561    let mut terminals = BTreeSet::new();
562    collect_terminal_fields(&node, TerminalDependency::Direct, &mut terminals);
563    let terminals: Vec<TerminalField> = terminals.into_iter().collect();
564
565    if terminals.is_empty() {
566        if has_virtual_terminal(&node) {
567            return Ok(Vec::new());
568        }
569        warnings.push(OpenLineageWarning::new(
570            "W_EMPTY_FIELD_LINEAGE",
571            format!(
572                "No input fields were found for output field '{}'",
573                output_field.name
574            ),
575        ));
576        return Ok(Vec::new());
577    }
578
579    let subtype = transformation_subtype(output_field.expression.as_ref(), &terminals);
580    let description = output_field
581        .expression
582        .as_ref()
583        .and_then(|expr| transformation_description(expr, options.dialect));
584
585    terminal_fields_to_openlineage(terminals, subtype, description, options, warnings)
586}
587
588fn transformation_description(expr: &Expression, dialect: DialectType) -> Option<String> {
589    #[cfg(feature = "generate")]
590    {
591        Some(expr.sql_for(dialect))
592    }
593
594    #[cfg(not(feature = "generate"))]
595    {
596        let _ = (expr, dialect);
597        None
598    }
599}
600
601fn terminal_fields_to_openlineage(
602    terminals: Vec<TerminalField>,
603    subtype: &str,
604    description: Option<String>,
605    options: &OpenLineageOptions,
606    warnings: &mut Vec<OpenLineageWarning>,
607) -> Result<Vec<OpenLineageInputField>> {
608    let mut grouped =
609        BTreeMap::<(String, String, String), BTreeSet<OpenLineageTransformation>>::new();
610    for terminal in terminals {
611        let dataset = dataset_from_table_name(&terminal.table, options).map_err(|err| {
612            warnings.push(OpenLineageWarning::new(
613                "W_UNRESOLVED_DATASET",
614                format!(
615                    "Could not map table '{}' to an OpenLineage dataset: {}",
616                    terminal.table, err
617                ),
618            ));
619            err
620        })?;
621        let (type_, transformation_subtype) = match terminal.dependency {
622            TerminalDependency::Direct => ("DIRECT", subtype),
623            TerminalDependency::Filter => ("INDIRECT", "FILTER"),
624        };
625        grouped
626            .entry((dataset.namespace, dataset.name, terminal.field))
627            .or_default()
628            .insert(OpenLineageTransformation {
629                type_: type_.to_string(),
630                subtype: transformation_subtype.to_string(),
631                description: description.clone(),
632                masking: Some(false),
633            });
634    }
635    Ok(grouped
636        .into_iter()
637        .map(
638            |((namespace, name, field), transformations)| OpenLineageInputField {
639                namespace,
640                name,
641                field,
642                transformations: transformations.into_iter().collect(),
643            },
644        )
645        .collect())
646}
647
648fn transformation_subtype(expr: Option<&Expression>, terminals: &[TerminalField]) -> &'static str {
649    let Some(expr) = expr else {
650        return "TRANSFORMATION";
651    };
652    let unaliased = unalias(expr);
653    if expression_contains_aggregate(unaliased) {
654        return "AGGREGATION";
655    }
656    let distinct_fields = terminals
657        .iter()
658        .map(|terminal| (&terminal.table, &terminal.field))
659        .collect::<BTreeSet<_>>();
660    if distinct_fields.len() == 1 {
661        if let Expression::Column(col) = unaliased {
662            if col.name.name == terminals[0].field {
663                return "IDENTITY";
664            }
665        }
666    }
667    "TRANSFORMATION"
668}
669
670fn collect_terminal_fields(
671    node: &LineageNode,
672    inherited_dependency: TerminalDependency,
673    terminals: &mut BTreeSet<TerminalField>,
674) {
675    let dependency = if inherited_dependency == TerminalDependency::Filter
676        || matches!(
677            node.set_branch,
678            Some(branch)
679                if branch.ordinal == 1
680                    && matches!(branch.operator, SetOperator::Intersect | SetOperator::Except)
681        ) {
682        TerminalDependency::Filter
683    } else {
684        TerminalDependency::Direct
685    };
686
687    if node.downstream.is_empty() {
688        if node.source_kind == SourceKind::Virtual {
689            return;
690        }
691        if let Expression::Column(column) = &node.expression {
692            let table = if !node.source_name.is_empty() {
693                Some(node.source_name.clone())
694            } else if let Expression::Table(table) = &node.source {
695                Some(table_ref_qualified_name(table))
696            } else {
697                column.table.as_ref().map(|t| t.name.clone())
698            };
699            if let Some(table) = table.filter(|t| !t.is_empty()) {
700                terminals.insert(TerminalField {
701                    table,
702                    field: column.name.name.clone(),
703                    dependency,
704                });
705            }
706        }
707        return;
708    }
709
710    for child in &node.downstream {
711        collect_terminal_fields(child, dependency, terminals);
712    }
713}
714
715fn has_virtual_terminal(node: &LineageNode) -> bool {
716    if node.downstream.is_empty() {
717        return node.source_kind == SourceKind::Virtual;
718    }
719    node.downstream.iter().any(has_virtual_terminal)
720}
721
722fn expression_contains_aggregate(expr: &Expression) -> bool {
723    contains_aggregate(expr)
724}
725
726fn collect_input_datasets(
727    expr: &Expression,
728    options: &OpenLineageOptions,
729    output: Option<&OpenLineageDatasetId>,
730    warnings: &mut Vec<OpenLineageWarning>,
731) -> Result<Vec<OpenLineageDatasetId>> {
732    let cte_aliases = collect_cte_aliases(expr, options.dialect);
733    let mut seen = BTreeSet::new();
734    let mut result = Vec::new();
735
736    for table in expr.dfs().filter_map(|node| match node {
737        Expression::Table(table) => Some(table),
738        _ => None,
739    }) {
740        let qname = table_ref_qualified_name(table);
741        let normalized = normalize_identifier(&table.name.name, options.dialect, true);
742        if cte_aliases.contains(&normalized) {
743            continue;
744        }
745        if output
746            .map(|out| out.name == qname || out.name == table.name.name)
747            .unwrap_or(false)
748        {
749            continue;
750        }
751        match dataset_from_table_name(&qname, options) {
752            Ok(dataset) => {
753                if seen.insert((dataset.namespace.clone(), dataset.name.clone())) {
754                    result.push(dataset);
755                }
756            }
757            Err(err) => warnings.push(OpenLineageWarning::new(
758                "W_UNRESOLVED_DATASET",
759                format!("Could not map input table '{qname}': {err}"),
760            )),
761        }
762    }
763
764    Ok(result)
765}
766
767fn attach_output_facets(
768    output: &mut OpenLineageDataset,
769    output_id: &OpenLineageDatasetId,
770    options: &OpenLineageOptions,
771    fields: &BTreeMap<String, ColumnLineageField>,
772) -> Result<()> {
773    let column_lineage = ColumnLineageDatasetFacet {
774        producer: options.producer.clone(),
775        schema_url: COLUMN_LINEAGE_FACET_SCHEMA_URL.to_string(),
776        fields: fields.clone(),
777    };
778    output.facets.insert(
779        "columnLineage".to_string(),
780        serde_json::to_value(column_lineage).map_err(openlineage_serialization_error)?,
781    );
782
783    if let Some(schema_facet) = schema_facet_for_dataset(output_id, options) {
784        output.facets.insert(
785            "schema".to_string(),
786            serde_json::to_value(schema_facet).map_err(openlineage_serialization_error)?,
787        );
788    }
789
790    Ok(())
791}
792
793fn job_facets(sql: &str, options: &OpenLineageOptions) -> Value {
794    json!({
795        "sql": {
796            "_producer": options.producer,
797            "_schemaURL": SQL_JOB_FACET_SCHEMA_URL,
798            "query": sql,
799            "dialect": options.dialect.to_string(),
800        },
801        "jobType": {
802            "_producer": options.producer,
803            "_schemaURL": JOB_TYPE_JOB_FACET_SCHEMA_URL,
804            "processingType": "BATCH",
805            "integration": "POLYGLOT_SQL",
806            "jobType": "QUERY",
807        }
808    })
809}
810
811#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
812struct SchemaDatasetFacet {
813    #[serde(rename = "_producer")]
814    producer: String,
815    #[serde(rename = "_schemaURL")]
816    schema_url: String,
817    fields: Vec<SchemaDatasetFacetField>,
818}
819
820#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
821struct SchemaDatasetFacetField {
822    name: String,
823    #[serde(skip_serializing_if = "String::is_empty", default)]
824    #[serde(rename = "type")]
825    data_type: String,
826    #[serde(skip_serializing_if = "Option::is_none")]
827    ordinal_position: Option<usize>,
828}
829
830fn schema_facet_for_dataset(
831    output: &OpenLineageDatasetId,
832    options: &OpenLineageOptions,
833) -> Option<SchemaDatasetFacet> {
834    let schema = options.schema.as_ref()?;
835    let table = schema.tables.iter().find(|table| {
836        let qname = if let Some(schema_name) = &table.schema {
837            format!("{}.{}", schema_name, table.name)
838        } else {
839            table.name.clone()
840        };
841        output.name == table.name || output.name == qname
842    })?;
843
844    Some(SchemaDatasetFacet {
845        producer: options.producer.clone(),
846        schema_url: SCHEMA_DATASET_FACET_SCHEMA_URL.to_string(),
847        fields: table
848            .columns
849            .iter()
850            .enumerate()
851            .map(|(idx, col)| SchemaDatasetFacetField {
852                name: col.name.clone(),
853                data_type: col.data_type.clone(),
854                ordinal_position: Some(idx + 1),
855            })
856            .collect(),
857    })
858}
859
860fn expand_star_output_fields(
861    select: &Select,
862    star_expr: &Expression,
863    schema: Option<&dyn Schema>,
864    warnings: &mut Vec<OpenLineageWarning>,
865    fields: &mut Vec<OutputField>,
866) {
867    let Some(schema) = schema else {
868        warnings.push(OpenLineageWarning::new(
869            "W_STAR_WITHOUT_SCHEMA",
870            "SELECT * cannot be expanded into OpenLineage column lineage without schema metadata",
871        ));
872        return;
873    };
874
875    let qualifier = star_qualifier(star_expr);
876    let sources = select_source_tables(select);
877    for (alias, qname) in sources {
878        if qualifier
879            .as_ref()
880            .map(|q| q != &alias && q != &qname)
881            .unwrap_or(false)
882        {
883            continue;
884        }
885        match schema.column_names(&qname) {
886            Ok(columns) => {
887                for name in columns {
888                    fields.push(OutputField {
889                        lineage_name: name.clone(),
890                        name,
891                        expression: None,
892                        star_source_table: Some(qname.clone()),
893                    });
894                }
895            }
896            Err(err) => warnings.push(OpenLineageWarning::new(
897                "W_STAR_SCHEMA_LOOKUP_FAILED",
898                format!("Could not expand SELECT * for table '{}': {}", qname, err),
899            )),
900        }
901    }
902}
903
904fn select_source_tables(select: &Select) -> Vec<(String, String)> {
905    let mut result = Vec::new();
906    if let Some(from) = &select.from {
907        for expr in &from.expressions {
908            collect_source_table(expr, &mut result);
909        }
910    }
911    for join in &select.joins {
912        collect_source_table(&join.this, &mut result);
913    }
914    result
915}
916
917fn collect_source_table(expr: &Expression, result: &mut Vec<(String, String)>) {
918    match expr {
919        Expression::Table(table) => {
920            let qname = table_ref_qualified_name(table);
921            let alias = table
922                .alias
923                .as_ref()
924                .map(|a| a.name.clone())
925                .unwrap_or_else(|| table.name.name.clone());
926            result.push((alias, qname));
927        }
928        Expression::Alias(alias) => collect_source_table(&alias.this, result),
929        Expression::Paren(paren) => collect_source_table(&paren.this, result),
930        _ => {}
931    }
932}
933
934fn leftmost_select(expr: &Expression) -> Option<&Select> {
935    match expr {
936        Expression::Prepare(prepare) => leftmost_select(&prepare.statement),
937        Expression::Select(select) => Some(select),
938        Expression::Union(union) => leftmost_select(&union.left),
939        Expression::Intersect(intersect) => leftmost_select(&intersect.left),
940        Expression::Except(except) => leftmost_select(&except.left),
941        Expression::Subquery(subquery) => leftmost_select(&subquery.this),
942        _ => None,
943    }
944}
945
946fn output_name(expr: &Expression) -> Option<String> {
947    match expr {
948        Expression::Alias(alias) => Some(alias.alias.name.clone()),
949        Expression::Column(col) => Some(col.name.name.clone()),
950        Expression::Identifier(id) => Some(id.name.clone()),
951        Expression::Annotated(a) => output_name(&a.this),
952        _ => None,
953    }
954}
955
956fn unalias(expr: &Expression) -> &Expression {
957    match expr {
958        Expression::Alias(alias) => &alias.this,
959        Expression::Annotated(a) => unalias(&a.this),
960        _ => expr,
961    }
962}
963
964fn is_star_expr(expr: &Expression) -> bool {
965    matches!(expr, Expression::Star(_))
966        || matches!(expr, Expression::Column(col) if col.name.name == "*")
967}
968
969fn star_qualifier(expr: &Expression) -> Option<String> {
970    match expr {
971        Expression::Star(star) => star.table.as_ref().map(|t| t.name.clone()),
972        Expression::Column(col) if col.name.name == "*" => {
973            col.table.as_ref().map(|t| t.name.clone())
974        }
975        _ => None,
976    }
977}
978
979fn dataset_from_expression(
980    expr: &Expression,
981    options: &OpenLineageOptions,
982) -> Result<OpenLineageDatasetId> {
983    match expr {
984        Expression::Table(table) => dataset_from_table_ref(table, options),
985        Expression::Identifier(id) => dataset_from_table_name(&id.name, options),
986        _ => Err(Error::unsupported(
987            "OpenLineage dataset extraction from non-table expression",
988            options.dialect.to_string(),
989        )),
990    }
991}
992
993fn dataset_from_table_ref(
994    table: &TableRef,
995    options: &OpenLineageOptions,
996) -> Result<OpenLineageDatasetId> {
997    dataset_from_table_name(&table_ref_qualified_name(table), options)
998}
999
1000fn dataset_from_table_name(
1001    table_name: &str,
1002    options: &OpenLineageOptions,
1003) -> Result<OpenLineageDatasetId> {
1004    if let Some(mapped) = options.dataset_mappings.get(table_name) {
1005        return Ok(mapped.clone());
1006    }
1007    let namespace = options.dataset_namespace.as_ref().ok_or_else(|| {
1008        Error::parse(
1009            format!(
1010                "Missing datasetNamespace or explicit dataset mapping for table '{}'",
1011                table_name
1012            ),
1013            0,
1014            0,
1015            0,
1016            0,
1017        )
1018    })?;
1019    Ok(OpenLineageDatasetId::new(namespace, table_name))
1020}
1021
1022fn table_ref_qualified_name(table: &TableRef) -> String {
1023    let mut parts = Vec::new();
1024    if let Some(catalog) = &table.catalog {
1025        parts.push(catalog.name.clone());
1026    }
1027    if let Some(schema) = &table.schema {
1028        parts.push(schema.name.clone());
1029    }
1030    parts.push(table.name.name.clone());
1031    parts.join(".")
1032}
1033
1034fn collect_cte_aliases(expr: &Expression, dialect: DialectType) -> HashSet<String> {
1035    let mut aliases = HashSet::new();
1036    for node in expr.dfs() {
1037        match node {
1038            Expression::Select(select) => {
1039                if let Some(with) = &select.with {
1040                    collect_with_aliases(with, dialect, &mut aliases);
1041                }
1042            }
1043            Expression::Union(union) => {
1044                if let Some(with) = &union.with {
1045                    collect_with_aliases(with, dialect, &mut aliases);
1046                }
1047            }
1048            Expression::Intersect(intersect) => {
1049                if let Some(with) = &intersect.with {
1050                    collect_with_aliases(with, dialect, &mut aliases);
1051                }
1052            }
1053            Expression::Except(except) => {
1054                if let Some(with) = &except.with {
1055                    collect_with_aliases(with, dialect, &mut aliases);
1056                }
1057            }
1058            _ => {}
1059        }
1060    }
1061    aliases
1062}
1063
1064fn collect_with_aliases(with: &With, dialect: DialectType, aliases: &mut HashSet<String>) {
1065    for cte in &with.ctes {
1066        aliases.insert(normalize_identifier(&cte.alias.name, dialect, true));
1067    }
1068}
1069
1070fn normalize_identifier(name: &str, dialect: DialectType, is_table: bool) -> String {
1071    crate::schema::normalize_name(name, Some(dialect), is_table, true)
1072}
1073
1074fn openlineage_serialization_error(err: serde_json::Error) -> Error {
1075    Error::internal(format!("OpenLineage serialization failed: {err}"))
1076}
1077
1078fn deserialize_dialect_type<'de, D>(deserializer: D) -> std::result::Result<DialectType, D::Error>
1079where
1080    D: Deserializer<'de>,
1081{
1082    let value = String::deserialize(deserializer)?;
1083    value.parse::<DialectType>().map_err(de::Error::custom)
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088    use super::*;
1089
1090    fn options() -> OpenLineageOptions {
1091        OpenLineageOptions {
1092            dialect: DialectType::PostgreSQL,
1093            producer: "https://github.com/tobilg/polyglot".to_string(),
1094            dataset_namespace: Some("postgres://warehouse".to_string()),
1095            output_dataset: Some(OpenLineageDatasetId::new(
1096                "postgres://warehouse",
1097                "analytics.out",
1098            )),
1099            job_namespace: Some("polyglot-tests".to_string()),
1100            job_name: Some("lineage-test".to_string()),
1101            event_time: Some("2026-05-18T00:00:00Z".to_string()),
1102            run_id: Some("3b452093-782c-4ef2-9c0c-aafe2aa6f34d".to_string()),
1103            event_type: Some(OpenLineageRunEventType::Complete),
1104            ..Default::default()
1105        }
1106    }
1107
1108    #[test]
1109    fn deserializes_dialect_aliases_in_options() {
1110        let options: OpenLineageOptions =
1111            serde_json::from_str(r#"{"producer":"polyglot","dialect":"postgres"}"#)
1112                .expect("options");
1113        assert_eq!(options.dialect, DialectType::PostgreSQL);
1114    }
1115
1116    #[test]
1117    fn emits_identity_column_lineage_for_select() {
1118        let result = openlineage_column_lineage("SELECT a FROM t", &options()).expect("lineage");
1119        let field = result.facet.fields.get("a").expect("field a");
1120        assert_eq!(field.input_fields.len(), 1);
1121        assert_eq!(field.input_fields[0].name, "t");
1122        assert_eq!(field.input_fields[0].field, "a");
1123        assert_eq!(field.input_fields[0].transformations[0].subtype, "IDENTITY");
1124    }
1125
1126    #[test]
1127    fn emits_set_operation_value_and_filter_dependencies() {
1128        let union = openlineage_column_lineage(
1129            "SELECT a FROM left_table UNION ALL SELECT b FROM right_table",
1130            &options(),
1131        )
1132        .expect("union lineage");
1133        let union_field = union.facet.fields.get("a").expect("union field");
1134        assert_eq!(union_field.input_fields.len(), 2);
1135        assert!(union_field.input_fields.iter().all(|input| input
1136            .transformations
1137            .iter()
1138            .all(|transformation| transformation.type_ == "DIRECT")));
1139
1140        for operator in ["EXCEPT", "INTERSECT"] {
1141            let result = openlineage_column_lineage(
1142                &format!("SELECT a FROM left_table {operator} SELECT b FROM right_table"),
1143                &options(),
1144            )
1145            .unwrap_or_else(|error| panic!("{operator} lineage failed: {error}"));
1146            let field = result.facet.fields.get("a").expect("output field");
1147            let left = field
1148                .input_fields
1149                .iter()
1150                .find(|input| input.name == "left_table")
1151                .expect("left input");
1152            let right = field
1153                .input_fields
1154                .iter()
1155                .find(|input| input.name == "right_table")
1156                .expect("right input");
1157            assert!(left
1158                .transformations
1159                .iter()
1160                .all(|transformation| transformation.type_ == "DIRECT"));
1161            assert!(right.transformations.iter().any(|transformation| {
1162                transformation.type_ == "INDIRECT" && transformation.subtype == "FILTER"
1163            }));
1164        }
1165
1166        let merged = openlineage_column_lineage(
1167            "SELECT a FROM shared_table EXCEPT SELECT a FROM shared_table",
1168            &options(),
1169        )
1170        .expect("merged dependency lineage");
1171        let merged_field = merged.facet.fields.get("a").expect("merged field");
1172        assert_eq!(merged_field.input_fields.len(), 1);
1173        assert!(merged_field.input_fields[0]
1174            .transformations
1175            .iter()
1176            .any(|transformation| transformation.type_ == "DIRECT"));
1177        assert!(merged_field.input_fields[0]
1178            .transformations
1179            .iter()
1180            .any(|transformation| {
1181                transformation.type_ == "INDIRECT" && transformation.subtype == "FILTER"
1182            }));
1183
1184        let nested = openlineage_column_lineage(
1185            "SELECT a FROM left_table EXCEPT \
1186             (SELECT b FROM right_table UNION ALL SELECT c FROM third_table)",
1187            &options(),
1188        )
1189        .expect("nested set-operation lineage");
1190        let nested_field = nested.facet.fields.get("a").expect("nested field");
1191        for table in ["right_table", "third_table"] {
1192            let input = nested_field
1193                .input_fields
1194                .iter()
1195                .find(|input| input.name == table)
1196                .unwrap_or_else(|| panic!("missing nested input {table}"));
1197            assert!(input.transformations.iter().any(|transformation| {
1198                transformation.type_ == "INDIRECT" && transformation.subtype == "FILTER"
1199            }));
1200        }
1201    }
1202
1203    #[test]
1204    fn emits_column_lineage_for_prepared_statement_body() {
1205        let result = openlineage_column_lineage(
1206            "PREPARE leak AS SELECT id FROM sensitive_table WHERE id = $1",
1207            &options(),
1208        )
1209        .expect("lineage");
1210        let field = result.facet.fields.get("id").expect("field id");
1211        assert_eq!(field.input_fields.len(), 1);
1212        assert_eq!(field.input_fields[0].name, "sensitive_table");
1213        assert_eq!(field.input_fields[0].field, "id");
1214    }
1215
1216    #[test]
1217    fn resolves_input_dataset_behind_table_alias() {
1218        let result = openlineage_column_lineage("SELECT o.total FROM orders o", &options())
1219            .expect("lineage");
1220        let field = result.facet.fields.get("total").expect("field total");
1221        assert_eq!(field.input_fields[0].name, "orders");
1222        assert_eq!(field.input_fields[0].field, "total");
1223    }
1224
1225    #[test]
1226    fn emits_transformation_column_lineage_for_expression() {
1227        let result =
1228            openlineage_column_lineage("SELECT a + b AS c FROM t", &options()).expect("lineage");
1229        let field = result.facet.fields.get("c").expect("field c");
1230        assert_eq!(field.input_fields.len(), 2);
1231        assert!(field.input_fields.iter().any(|f| f.field == "a"));
1232        assert!(field.input_fields.iter().any(|f| f.field == "b"));
1233        assert!(field
1234            .input_fields
1235            .iter()
1236            .all(|f| f.transformations[0].subtype == "TRANSFORMATION"));
1237    }
1238
1239    #[test]
1240    fn omits_bigquery_safe_namespace_from_column_lineage_issue207() {
1241        let mut opts = options();
1242        opts.dialect = DialectType::BigQuery;
1243
1244        let result = openlineage_column_lineage(
1245            r#"
1246WITH import_cte AS (
1247  SELECT timestamp, data, operation
1248  FROM `project`.`dataset`.`source_table`
1249),
1250transform_cte AS (
1251  SELECT
1252    timestamp,
1253    SAFE.PARSE_JSON(data) AS json_data
1254  FROM import_cte
1255)
1256SELECT json_data FROM transform_cte
1257"#,
1258            &opts,
1259        )
1260        .expect("lineage");
1261        let field = result.facet.fields.get("json_data").expect("json_data");
1262
1263        assert!(
1264            field.input_fields.iter().any(|input| input.field == "data"),
1265            "expected data input field, got {:?}",
1266            field.input_fields
1267        );
1268        assert!(
1269            !field
1270                .input_fields
1271                .iter()
1272                .any(|input| input.field.eq_ignore_ascii_case("safe")),
1273            "did not expect SAFE namespace as input field, got {:?}",
1274            field.input_fields
1275        );
1276    }
1277
1278    #[test]
1279    fn emits_bigquery_unnest_alias_column_lineage_issue209() {
1280        let mut opts = options();
1281        opts.dialect = DialectType::BigQuery;
1282        opts.dataset_namespace = Some("bigquery://warehouse".to_string());
1283        opts.output_dataset = Some(OpenLineageDatasetId::new(
1284            "bigquery://warehouse",
1285            "calendar",
1286        ));
1287
1288        let result = openlineage_column_lineage(
1289            r#"
1290SELECT date_val AS week_start
1291FROM UNNEST(GENERATE_DATE_ARRAY('2024-01-01', '2024-12-31', INTERVAL 1 WEEK)) AS date_val
1292"#,
1293            &opts,
1294        )
1295        .expect("lineage");
1296        let field = result.facet.fields.get("week_start").expect("week_start");
1297
1298        assert!(field.input_fields.is_empty());
1299        assert!(
1300            result
1301                .warnings
1302                .iter()
1303                .all(|warning| warning.code != "W_EMPTY_FIELD_LINEAGE"),
1304            "did not expect empty-lineage warning, got {:?}",
1305            result.warnings
1306        );
1307    }
1308
1309    #[test]
1310    fn emits_bigquery_table_backed_unnest_column_lineage() {
1311        let mut opts = options();
1312        opts.dialect = DialectType::BigQuery;
1313        opts.dataset_namespace = Some("bigquery://warehouse".to_string());
1314        opts.output_dataset = Some(OpenLineageDatasetId::new("bigquery://warehouse", "items"));
1315
1316        let result = openlineage_column_lineage(
1317            r#"
1318SELECT item.item AS item
1319FROM t JOIN UNNEST(t.items) AS item ON TRUE
1320"#,
1321            &opts,
1322        )
1323        .expect("lineage");
1324        let field = result.facet.fields.get("item").expect("item");
1325
1326        assert_eq!(field.input_fields.len(), 1);
1327        assert_eq!(field.input_fields[0].name, "t");
1328        assert_eq!(field.input_fields[0].field, "items");
1329    }
1330
1331    #[test]
1332    fn emits_aggregation_column_lineage() {
1333        let result =
1334            openlineage_column_lineage("SELECT SUM(amount) AS total FROM orders", &options())
1335                .expect("lineage");
1336        let field = result.facet.fields.get("total").expect("field total");
1337        assert_eq!(field.input_fields[0].field, "amount");
1338        assert_eq!(
1339            field.input_fields[0].transformations[0].subtype,
1340            "AGGREGATION"
1341        );
1342    }
1343
1344    #[test]
1345    fn infers_insert_output_dataset() {
1346        let mut opts = options();
1347        opts.output_dataset = None;
1348        let result =
1349            openlineage_column_lineage("INSERT INTO analytics.out SELECT a FROM raw.input", &opts)
1350                .expect("lineage");
1351        assert_eq!(result.outputs[0].name, "analytics.out");
1352        assert_eq!(result.inputs[0].name, "raw.input");
1353    }
1354
1355    #[test]
1356    fn maps_insert_target_columns_to_output_fields() {
1357        let mut opts = options();
1358        opts.output_dataset = None;
1359        let result = openlineage_column_lineage(
1360            "INSERT INTO analytics.out (target_a) SELECT source_a FROM raw.input",
1361            &opts,
1362        )
1363        .expect("lineage");
1364        let field = result.facet.fields.get("target_a").expect("target field");
1365        assert_eq!(field.input_fields[0].field, "source_a");
1366        assert!(!result.facet.fields.contains_key("source_a"));
1367    }
1368
1369    #[test]
1370    fn pure_select_requires_output_dataset() {
1371        let mut opts = options();
1372        opts.output_dataset = None;
1373        let err = openlineage_column_lineage("SELECT a FROM t", &opts).unwrap_err();
1374        assert!(err.to_string().contains("outputDataset is required"));
1375    }
1376
1377    #[test]
1378    fn emits_job_event_payload() {
1379        let result = openlineage_job_event("SELECT a FROM t", &options()).expect("event");
1380        assert_eq!(result.event["job"]["namespace"], "polyglot-tests");
1381        assert_eq!(
1382            result.event["job"]["facets"]["sql"]["_schemaURL"],
1383            SQL_JOB_FACET_SCHEMA_URL
1384        );
1385        assert_eq!(
1386            result.event["outputs"][0]["facets"]["columnLineage"]["fields"]["a"]["inputFields"][0]
1387                ["field"],
1388            "a"
1389        );
1390    }
1391
1392    #[test]
1393    fn emits_run_event_payload() {
1394        let result = openlineage_run_event("SELECT a FROM t", &options()).expect("event");
1395        assert_eq!(result.event["eventType"], "COMPLETE");
1396        assert_eq!(
1397            result.event["run"]["runId"],
1398            "3b452093-782c-4ef2-9c0c-aafe2aa6f34d"
1399        );
1400    }
1401
1402    #[test]
1403    fn select_star_without_schema_warns() {
1404        let result = openlineage_column_lineage("SELECT * FROM t", &options()).expect("lineage");
1405        assert!(result.facet.fields.is_empty());
1406        assert!(result
1407            .warnings
1408            .iter()
1409            .any(|w| w.code == "W_STAR_WITHOUT_SCHEMA"));
1410    }
1411
1412    #[test]
1413    fn select_star_with_schema_expands_fields() {
1414        let mut opts = options();
1415        opts.schema = Some(ValidationSchema {
1416            strict: None,
1417            tables: vec![crate::validation::SchemaTable {
1418                name: "t".to_string(),
1419                schema: None,
1420                columns: vec![
1421                    crate::validation::SchemaColumn {
1422                        name: "a".to_string(),
1423                        data_type: "INT".to_string(),
1424                        nullable: None,
1425                        primary_key: false,
1426                        unique: false,
1427                        references: None,
1428                    },
1429                    crate::validation::SchemaColumn {
1430                        name: "b".to_string(),
1431                        data_type: "TEXT".to_string(),
1432                        nullable: None,
1433                        primary_key: false,
1434                        unique: false,
1435                        references: None,
1436                    },
1437                ],
1438                aliases: vec![],
1439                primary_key: vec![],
1440                unique_keys: vec![],
1441                foreign_keys: vec![],
1442            }],
1443        });
1444
1445        let result = openlineage_column_lineage("SELECT * FROM t", &opts).expect("lineage");
1446        assert!(result.facet.fields.contains_key("a"));
1447        assert!(result.facet.fields.contains_key("b"));
1448    }
1449}