Skip to main content

sqlparser/ast/
spans.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::{
19    ast::{
20        ddl::AlterSchema, query::SelectItemQualifiedWildcardKind, AlterSchemaOperation, AlterTable,
21        ColumnOptions, CreateOperator, CreateOperatorClass, CreateOperatorFamily, CreateView,
22        ExportData, Owner, TypedString,
23    },
24    tokenizer::TokenWithSpan,
25};
26use core::iter;
27
28use crate::tokenizer::Span;
29
30use super::{
31    comments, dcl::SecondaryRoles, value::ValueWithSpan, AccessExpr, AlterColumnOperation,
32    AlterIndexOperation, AlterTableOperation, Analyze, Array, Assignment, AssignmentTarget,
33    AttachedToken, BeginEndStatements, CaseStatement, CloseCursor, ClusteredIndex, ColumnDef,
34    ColumnOption, ColumnOptionDef, ConditionalStatementBlock, ConditionalStatements,
35    ConflictTarget, ConnectByKind, ConstraintCharacteristics, CopySource, CreateIndex, CreateTable,
36    CreateTableOptions, Cte, Delete, DoUpdate, ExceptSelectItem, ExcludeSelectItem, Expr,
37    ExprWithAlias, Fetch, ForValues, FromTable, Function, FunctionArg, FunctionArgExpr,
38    FunctionArgumentClause, FunctionArgumentList, FunctionArguments, GroupByExpr, HavingBound,
39    IfStatement, IlikeSelectItem, IndexColumn, Insert, Interpolate, InterpolateExpr, Join,
40    JoinConstraint, JoinOperator, JsonPath, JsonPathElem, LateralView, LimitClause,
41    MatchRecognizePattern, Measure, Merge, MergeAction, MergeClause, MergeInsertExpr,
42    MergeInsertKind, MergeUpdateExpr, MergeUpdateKind, NamedParenthesizedList,
43    NamedWindowDefinition, ObjectName, ObjectNamePart, Offset, OnConflict, OnConflictAction,
44    OnInsert, OpenStatement, OrderBy, OrderByExpr, OrderByKind, OutputClause, Parens, Partition,
45    PartitionBoundValue, PivotValueSource, ProjectionSelect, Query, RaiseStatement,
46    RaiseStatementValue, ReferentialAction, RenameSelectItem, ReplaceSelectElement,
47    ReplaceSelectItem, Select, SelectInto, SelectItem, SetExpr, SqlOption, Statement, Subscript,
48    SymbolDefinition, TableAlias, TableAliasColumnDef, TableConstraint, TableFactor, TableObject,
49    TableOptionsClustered, TableWithJoins, Update, UpdateTableFromKind, Use, Values, ViewColumnDef,
50    WhileStatement, WildcardAdditionalOptions, With, WithFill,
51};
52
53/// Given an iterator of spans, return the [Span::union] of all spans.
54fn union_spans<I: Iterator<Item = Span>>(iter: I) -> Span {
55    Span::union_iter(iter)
56}
57
58/// Trait for AST nodes that have a source location information.
59///
60/// # Notes:
61///
62/// Source [`Span`] are not yet complete. They may be missing:
63///
64/// 1. keywords or other tokens
65/// 2. span information entirely, in which case they return [`Span::empty()`].
66///
67/// Note Some impl blocks (rendered below) are annotated with which nodes are
68/// missing spans. See [this ticket] for additional information and status.
69///
70/// [this ticket]: https://github.com/apache/datafusion-sqlparser-rs/issues/1548
71///
72/// # Example
73/// ```
74/// # use sqlparser::parser::{Parser, ParserError};
75/// # use sqlparser::ast::Spanned;
76/// # use sqlparser::dialect::GenericDialect;
77/// # use sqlparser::tokenizer::Location;
78/// # fn main() -> Result<(), ParserError> {
79/// let dialect = GenericDialect {};
80/// let sql = r#"SELECT *
81///   FROM table_1"#;
82/// let statements = Parser::new(&dialect)
83///   .try_with_sql(sql)?
84///   .parse_statements()?;
85/// // Get the span of the first statement (SELECT)
86/// let span = statements[0].span();
87/// // statement starts at line 1, column 1 (1 based, not 0 based)
88/// assert_eq!(span.start, Location::new(1, 1));
89/// // statement ends on line 2, column 15
90/// assert_eq!(span.end, Location::new(2, 15));
91/// # Ok(())
92/// # }
93/// ```
94///
95pub trait Spanned {
96    /// Return the [`Span`] (the minimum and maximum [`Location`]) for this AST
97    /// node, by recursively combining the spans of its children.
98    ///
99    /// [`Location`]: crate::tokenizer::Location
100    fn span(&self) -> Span;
101}
102
103impl Spanned for TokenWithSpan {
104    fn span(&self) -> Span {
105        self.span
106    }
107}
108
109impl<T> Spanned for Parens<T> {
110    fn span(&self) -> Span {
111        self.opening_token.0.span.union(&self.closing_token.0.span)
112    }
113}
114
115impl Spanned for Query {
116    fn span(&self) -> Span {
117        let Query {
118            with,
119            body,
120            order_by,
121            limit_clause,
122            fetch,
123            locks: _,          // todo
124            for_clause: _,     // todo, mssql specific
125            settings: _,       // todo, clickhouse specific
126            format_clause: _,  // todo, clickhouse specific
127            pipe_operators: _, // todo bigquery specific
128        } = self;
129
130        union_spans(
131            with.iter()
132                .map(|i| i.span())
133                .chain(core::iter::once(body.span()))
134                .chain(order_by.as_ref().map(|i| i.span()))
135                .chain(limit_clause.as_ref().map(|i| i.span()))
136                .chain(fetch.as_ref().map(|i| i.span())),
137        )
138    }
139}
140
141impl Spanned for LimitClause {
142    fn span(&self) -> Span {
143        match self {
144            LimitClause::LimitOffset {
145                limit,
146                offset,
147                limit_by,
148            } => union_spans(
149                limit
150                    .iter()
151                    .map(|i| i.span())
152                    .chain(offset.as_ref().map(|i| i.span()))
153                    .chain(limit_by.iter().map(|i| i.span())),
154            ),
155            LimitClause::OffsetCommaLimit { offset, limit } => offset.span().union(&limit.span()),
156        }
157    }
158}
159
160impl Spanned for Offset {
161    fn span(&self) -> Span {
162        let Offset {
163            value,
164            rows: _, // enum
165        } = self;
166
167        value.span()
168    }
169}
170
171impl Spanned for Fetch {
172    fn span(&self) -> Span {
173        let Fetch {
174            with_ties: _, // bool
175            percent: _,   // bool
176            quantity,
177        } = self;
178
179        quantity.as_ref().map_or(Span::empty(), |i| i.span())
180    }
181}
182
183impl Spanned for With {
184    fn span(&self) -> Span {
185        let With {
186            with_token,
187            recursive: _, // bool
188            cte_tables,
189        } = self;
190
191        union_spans(
192            core::iter::once(with_token.0.span).chain(cte_tables.iter().map(|item| item.span())),
193        )
194    }
195}
196
197impl Spanned for Cte {
198    fn span(&self) -> Span {
199        let Cte {
200            alias,
201            query,
202            from,
203            materialized: _, // enum
204            closing_paren_token,
205        } = self;
206
207        union_spans(
208            core::iter::once(alias.span())
209                .chain(core::iter::once(query.span()))
210                .chain(from.iter().map(|item| item.span))
211                .chain(core::iter::once(closing_paren_token.0.span)),
212        )
213    }
214}
215
216/// # partial span
217///
218/// [SetExpr::Table] is not implemented.
219impl Spanned for SetExpr {
220    fn span(&self) -> Span {
221        match self {
222            SetExpr::Select(select) => select.span(),
223            SetExpr::Query(query) => query.span(),
224            SetExpr::SetOperation {
225                op: _,
226                set_quantifier: _,
227                left,
228                right,
229            } => left.span().union(&right.span()),
230            SetExpr::Values(values) => values.span(),
231            SetExpr::Insert(statement) => statement.span(),
232            SetExpr::Table(_) => Span::empty(),
233            SetExpr::Update(statement) => statement.span(),
234            SetExpr::Delete(statement) => statement.span(),
235            SetExpr::Merge(statement) => statement.span(),
236        }
237    }
238}
239
240impl Spanned for Values {
241    fn span(&self) -> Span {
242        let Values {
243            explicit_row: _, // bool,
244            value_keyword: _,
245            rows,
246        } = self;
247
248        match &rows[..] {
249            [] => Span::empty(),
250            [f] => f.span(),
251            [f, .., l] => f.span().union(&l.span()),
252        }
253    }
254}
255
256/// # partial span
257///
258/// Missing spans:
259/// - [Statement::CopyIntoSnowflake]
260/// - [Statement::CreateSecret]
261/// - [Statement::CreateRole]
262/// - [Statement::AlterType]
263/// - [Statement::AlterOperator]
264/// - [Statement::AlterRole]
265/// - [Statement::AttachDatabase]
266/// - [Statement::AttachDuckDBDatabase]
267/// - [Statement::DetachDuckDBDatabase]
268/// - [Statement::Drop]
269/// - [Statement::DropFunction]
270/// - [Statement::DropProcedure]
271/// - [Statement::DropSecret]
272/// - [Statement::Declare]
273/// - [Statement::CreateExtension]
274/// - [Statement::CreateCollation]
275/// - [Statement::AlterCollation]
276/// - [Statement::Fetch]
277/// - [Statement::Flush]
278/// - [Statement::Discard]
279/// - [Statement::Set]
280/// - [Statement::ShowFunctions]
281/// - [Statement::ShowVariable]
282/// - [Statement::ShowStatus]
283/// - [Statement::ShowVariables]
284/// - [Statement::ShowCreate]
285/// - [Statement::ShowColumns]
286/// - [Statement::ShowTables]
287/// - [Statement::ShowCollation]
288/// - [Statement::StartTransaction]
289/// - [Statement::Comment]
290/// - [Statement::Commit]
291/// - [Statement::Rollback]
292/// - [Statement::CreateSchema]
293/// - [Statement::CreateDatabase]
294/// - [Statement::CreateFunction]
295/// - [Statement::CreateTrigger]
296/// - [Statement::DropTrigger]
297/// - [Statement::CreateProcedure]
298/// - [Statement::CreateMacro]
299/// - [Statement::CreateStage]
300/// - [Statement::Assert]
301/// - [Statement::Grant]
302/// - [Statement::Revoke]
303/// - [Statement::Deallocate]
304/// - [Statement::Execute]
305/// - [Statement::Prepare]
306/// - [Statement::Kill]
307/// - [Statement::ExplainTable]
308/// - [Statement::Explain]
309/// - [Statement::Savepoint]
310/// - [Statement::ReleaseSavepoint]
311/// - [Statement::Cache]
312/// - [Statement::UNCache]
313/// - [Statement::CreateSequence]
314/// - [Statement::CreateType]
315/// - [Statement::Pragma]
316/// - [Statement::Lock]
317/// - [Statement::LockTables]
318/// - [Statement::UnlockTables]
319/// - [Statement::Unload]
320/// - [Statement::OptimizeTable]
321impl Spanned for Statement {
322    fn span(&self) -> Span {
323        match self {
324            Statement::Analyze(analyze) => analyze.span(),
325            Statement::Truncate(truncate) => truncate.span(),
326            Statement::Msck(msck) => msck.span(),
327            Statement::Query(query) => query.span(),
328            Statement::Insert(insert) => insert.span(),
329            Statement::Install { extension_name } => extension_name.span,
330            Statement::Load { extension_name } => extension_name.span,
331            Statement::Directory {
332                overwrite: _,
333                local: _,
334                path: _,
335                file_format: _,
336                source,
337            } => source.span(),
338            Statement::Case(stmt) => stmt.span(),
339            Statement::If(stmt) => stmt.span(),
340            Statement::While(stmt) => stmt.span(),
341            Statement::Raise(stmt) => stmt.span(),
342            Statement::Call(function) => function.span(),
343            Statement::Copy {
344                source,
345                to: _,
346                target: _,
347                options: _,
348                legacy_options: _,
349                values: _,
350            } => source.span(),
351            Statement::CopyIntoSnowflake {
352                into: _,
353                into_columns: _,
354                from_obj: _,
355                from_obj_alias: _,
356                stage_params: _,
357                from_transformations: _,
358                files: _,
359                pattern: _,
360                file_format: _,
361                copy_options: _,
362                validation_mode: _,
363                kind: _,
364                from_query: _,
365                partition: _,
366            } => Span::empty(),
367            Statement::Open(open) => open.span(),
368            Statement::Close { cursor } => match cursor {
369                CloseCursor::All => Span::empty(),
370                CloseCursor::Specific { name } => name.span,
371            },
372            Statement::Update(update) => update.span(),
373            Statement::Delete(delete) => delete.span(),
374            Statement::CreateView(create_view) => create_view.span(),
375            Statement::CreateTable(create_table) => create_table.span(),
376            Statement::CreateVirtualTable {
377                name,
378                if_not_exists: _,
379                module_name,
380                module_args,
381            } => union_spans(
382                core::iter::once(name.span())
383                    .chain(core::iter::once(module_name.span))
384                    .chain(module_args.iter().map(|i| i.span)),
385            ),
386            Statement::CreateIndex(create_index) => create_index.span(),
387            Statement::CreateRole(create_role) => create_role.span(),
388            Statement::CreateExtension(create_extension) => create_extension.span(),
389            Statement::CreateCollation(create_collation) => create_collation.span(),
390            Statement::DropExtension(drop_extension) => drop_extension.span(),
391            Statement::DropOperator(drop_operator) => drop_operator.span(),
392            Statement::DropOperatorFamily(drop_operator_family) => drop_operator_family.span(),
393            Statement::DropOperatorClass(drop_operator_class) => drop_operator_class.span(),
394            Statement::CreateSecret { .. } => Span::empty(),
395            Statement::CreateServer { .. } => Span::empty(),
396            Statement::CreateConnector { .. } => Span::empty(),
397            Statement::CreateOperator(create_operator) => create_operator.span(),
398            Statement::CreateOperatorFamily(create_operator_family) => {
399                create_operator_family.span()
400            }
401            Statement::CreateOperatorClass(create_operator_class) => create_operator_class.span(),
402            Statement::AlterTable(alter_table) => alter_table.span(),
403            Statement::AlterIndex { name, operation } => name.span().union(&operation.span()),
404            Statement::AlterView {
405                name,
406                columns,
407                query,
408                with_options,
409            } => union_spans(
410                core::iter::once(name.span())
411                    .chain(columns.iter().map(|i| i.span))
412                    .chain(core::iter::once(query.span()))
413                    .chain(with_options.iter().map(|i| i.span())),
414            ),
415            // These statements need to be implemented
416            Statement::AlterFunction { .. } => Span::empty(),
417            Statement::AlterType { .. } => Span::empty(),
418            Statement::AlterCollation { .. } => Span::empty(),
419            Statement::AlterOperator { .. } => Span::empty(),
420            Statement::AlterOperatorFamily { .. } => Span::empty(),
421            Statement::AlterOperatorClass { .. } => Span::empty(),
422            Statement::AlterRole { .. } => Span::empty(),
423            Statement::AlterSession { .. } => Span::empty(),
424            Statement::AttachDatabase { .. } => Span::empty(),
425            Statement::AttachDuckDBDatabase { .. } => Span::empty(),
426            Statement::DetachDuckDBDatabase { .. } => Span::empty(),
427            Statement::Drop { .. } => Span::empty(),
428            Statement::DropFunction(drop_function) => drop_function.span(),
429            Statement::DropDomain { .. } => Span::empty(),
430            Statement::DropProcedure { .. } => Span::empty(),
431            Statement::DropSecret { .. } => Span::empty(),
432            Statement::Declare { .. } => Span::empty(),
433            Statement::Fetch { .. } => Span::empty(),
434            Statement::Flush { .. } => Span::empty(),
435            Statement::Discard { .. } => Span::empty(),
436            Statement::Set(_) => Span::empty(),
437            Statement::ShowFunctions { .. } => Span::empty(),
438            Statement::ShowVariable { .. } => Span::empty(),
439            Statement::ShowStatus { .. } => Span::empty(),
440            Statement::ShowVariables { .. } => Span::empty(),
441            Statement::ShowCreate { .. } => Span::empty(),
442            Statement::ShowColumns { .. } => Span::empty(),
443            Statement::ShowTables { .. } => Span::empty(),
444            Statement::ShowCollation { .. } => Span::empty(),
445            Statement::ShowCharset { .. } => Span::empty(),
446            Statement::Use(u) => u.span(),
447            Statement::StartTransaction { .. } => Span::empty(),
448            Statement::Comment { .. } => Span::empty(),
449            Statement::Commit { .. } => Span::empty(),
450            Statement::Rollback { .. } => Span::empty(),
451            Statement::CreateSchema { .. } => Span::empty(),
452            Statement::CreateDatabase { .. } => Span::empty(),
453            Statement::CreateFunction { .. } => Span::empty(),
454            Statement::CreateDomain { .. } => Span::empty(),
455            Statement::CreateTrigger { .. } => Span::empty(),
456            Statement::DropTrigger { .. } => Span::empty(),
457            Statement::CreateProcedure { .. } => Span::empty(),
458            Statement::CreateMacro { .. } => Span::empty(),
459            Statement::CreateStage { .. } => Span::empty(),
460            Statement::Assert { .. } => Span::empty(),
461            Statement::Grant { .. } => Span::empty(),
462            Statement::Deny { .. } => Span::empty(),
463            Statement::Revoke { .. } => Span::empty(),
464            Statement::Deallocate { .. } => Span::empty(),
465            Statement::Execute { .. } => Span::empty(),
466            Statement::Prepare { .. } => Span::empty(),
467            Statement::Kill { .. } => Span::empty(),
468            Statement::ExplainTable { .. } => Span::empty(),
469            Statement::Explain { .. } => Span::empty(),
470            Statement::Savepoint { .. } => Span::empty(),
471            Statement::ReleaseSavepoint { .. } => Span::empty(),
472            Statement::Merge(merge) => merge.span(),
473            Statement::Cache { .. } => Span::empty(),
474            Statement::UNCache { .. } => Span::empty(),
475            Statement::CreateSequence { .. } => Span::empty(),
476            Statement::CreateType { .. } => Span::empty(),
477            Statement::Pragma { .. } => Span::empty(),
478            Statement::Lock(_) => Span::empty(),
479            Statement::LockTables { .. } => Span::empty(),
480            Statement::UnlockTables => Span::empty(),
481            Statement::Unload { .. } => Span::empty(),
482            Statement::OptimizeTable { .. } => Span::empty(),
483            Statement::CreatePolicy { .. } => Span::empty(),
484            Statement::AlterPolicy { .. } => Span::empty(),
485            Statement::AlterConnector { .. } => Span::empty(),
486            Statement::DropPolicy { .. } => Span::empty(),
487            Statement::DropConnector { .. } => Span::empty(),
488            Statement::ShowCatalogs { .. } => Span::empty(),
489            Statement::ShowDatabases { .. } => Span::empty(),
490            Statement::ShowProcessList { .. } => Span::empty(),
491            Statement::ShowSchemas { .. } => Span::empty(),
492            Statement::ShowObjects { .. } => Span::empty(),
493            Statement::ShowViews { .. } => Span::empty(),
494            Statement::LISTEN { .. } => Span::empty(),
495            Statement::NOTIFY { .. } => Span::empty(),
496            Statement::LoadData { .. } => Span::empty(),
497            Statement::UNLISTEN { .. } => Span::empty(),
498            Statement::RenameTable { .. } => Span::empty(),
499            Statement::RaisError { .. } => Span::empty(),
500            Statement::Throw(_) => Span::empty(),
501            Statement::Print { .. } => Span::empty(),
502            Statement::WaitFor(_) => Span::empty(),
503            Statement::Return { .. } => Span::empty(),
504            Statement::List(..) | Statement::Remove(..) => Span::empty(),
505            Statement::ExportData(ExportData {
506                options,
507                query,
508                connection,
509            }) => union_spans(
510                options
511                    .iter()
512                    .map(|i| i.span())
513                    .chain(core::iter::once(query.span()))
514                    .chain(connection.iter().map(|i| i.span())),
515            ),
516            Statement::CreateUser(..) => Span::empty(),
517            Statement::AlterSchema(s) => s.span(),
518            Statement::Vacuum(..) => Span::empty(),
519            Statement::AlterUser(..) => Span::empty(),
520            Statement::Reset(..) => Span::empty(),
521        }
522    }
523}
524
525impl Spanned for Use {
526    fn span(&self) -> Span {
527        match self {
528            Use::Catalog(object_name) => object_name.span(),
529            Use::Schema(object_name) => object_name.span(),
530            Use::Database(object_name) => object_name.span(),
531            Use::Warehouse(object_name) => object_name.span(),
532            Use::Role(object_name) => object_name.span(),
533            Use::SecondaryRoles(secondary_roles) => {
534                if let SecondaryRoles::List(roles) = secondary_roles {
535                    return union_spans(roles.iter().map(|i| i.span));
536                }
537                Span::empty()
538            }
539            Use::Object(object_name) => object_name.span(),
540            Use::Default => Span::empty(),
541        }
542    }
543}
544
545impl Spanned for CreateTable {
546    fn span(&self) -> Span {
547        let CreateTable {
548            or_replace: _,    // bool
549            temporary: _,     // bool
550            external: _,      // bool
551            global: _,        // bool
552            dynamic: _,       // bool
553            if_not_exists: _, // bool
554            transient: _,     // bool
555            volatile: _,      // bool
556            iceberg: _,       // bool, Snowflake specific
557            snapshot: _,      // bool, BigQuery specific
558            name,
559            columns,
560            constraints,
561            hive_distribution: _, // hive specific
562            hive_formats: _,      // hive specific
563            file_format: _,       // enum
564            location: _,          // string, no span
565            query,
566            without_rowid: _, // bool
567            like: _,
568            clone,
569            comment: _, // todo, no span
570            on_commit: _,
571            on_cluster: _,   // todo, clickhouse specific
572            primary_key: _,  // todo, clickhouse specific
573            order_by: _,     // todo, clickhouse specific
574            partition_by: _, // todo, BigQuery specific
575            cluster_by: _,   // todo, BigQuery specific
576            clustered_by: _, // todo, Hive specific
577            inherits: _,     // todo, PostgreSQL specific
578            partition_of,
579            for_values,
580            strict: _,                          // bool
581            copy_grants: _,                     // bool
582            enable_schema_evolution: _,         // bool
583            change_tracking: _,                 // bool
584            data_retention_time_in_days: _,     // u64, no span
585            max_data_extension_time_in_days: _, // u64, no span
586            default_ddl_collation: _,           // string, no span
587            with_aggregation_policy: _,         // todo, Snowflake specific
588            with_row_access_policy: _,          // todo, Snowflake specific
589            with_storage_lifecycle_policy: _,   // todo, Snowflake specific
590            with_tags: _,                       // todo, Snowflake specific
591            external_volume: _,                 // todo, Snowflake specific
592            with_connection: _,                 // todo, BigQuery external table connection
593            base_location: _,                   // todo, Snowflake specific
594            catalog: _,                         // todo, Snowflake specific
595            catalog_sync: _,                    // todo, Snowflake specific
596            storage_serialization_policy: _,
597            table_options,
598            target_lag: _,
599            warehouse: _,
600            version: _,
601            refresh_mode: _,
602            initialize: _,
603            require_user: _,
604            diststyle: _,
605            distkey: _,
606            sortkey: _,
607            backup: _,
608            multiset: _,
609            fallback: _,
610            with_data: _,
611        } = self;
612
613        union_spans(
614            core::iter::once(name.span())
615                .chain(core::iter::once(table_options.span()))
616                .chain(columns.iter().map(|i| i.span()))
617                .chain(constraints.iter().map(|i| i.span()))
618                .chain(query.iter().map(|i| i.span()))
619                .chain(clone.iter().map(|i| i.span()))
620                .chain(partition_of.iter().map(|i| i.span()))
621                .chain(for_values.iter().map(|i| i.span())),
622        )
623    }
624}
625
626impl Spanned for ColumnDef {
627    fn span(&self) -> Span {
628        let ColumnDef {
629            name,
630            data_type: _, // enum
631            options,
632        } = self;
633
634        union_spans(core::iter::once(name.span).chain(options.iter().map(|i| i.span())))
635    }
636}
637
638impl Spanned for ColumnOptionDef {
639    fn span(&self) -> Span {
640        let ColumnOptionDef { name, option } = self;
641
642        option.span().union_opt(&name.as_ref().map(|i| i.span))
643    }
644}
645
646impl Spanned for TableConstraint {
647    fn span(&self) -> Span {
648        match self {
649            TableConstraint::Unique(constraint) => constraint.span(),
650            TableConstraint::PrimaryKey(constraint) => constraint.span(),
651            TableConstraint::ForeignKey(constraint) => constraint.span(),
652            TableConstraint::Check(constraint) => constraint.span(),
653            TableConstraint::Index(constraint) => constraint.span(),
654            TableConstraint::FulltextOrSpatial(constraint) => constraint.span(),
655            TableConstraint::PrimaryKeyUsingIndex(constraint)
656            | TableConstraint::UniqueUsingIndex(constraint) => constraint.span(),
657        }
658    }
659}
660
661impl Spanned for PartitionBoundValue {
662    fn span(&self) -> Span {
663        match self {
664            PartitionBoundValue::Expr(expr) => expr.span(),
665            // MINVALUE and MAXVALUE are keywords without tracked spans
666            PartitionBoundValue::MinValue => Span::empty(),
667            PartitionBoundValue::MaxValue => Span::empty(),
668        }
669    }
670}
671
672impl Spanned for ForValues {
673    fn span(&self) -> Span {
674        match self {
675            ForValues::In(exprs) => union_spans(exprs.iter().map(|e| e.span())),
676            ForValues::From { from, to } => union_spans(
677                from.iter()
678                    .map(|v| v.span())
679                    .chain(to.iter().map(|v| v.span())),
680            ),
681            // WITH (MODULUS n, REMAINDER r) - u64 values have no spans
682            ForValues::With { .. } => Span::empty(),
683            ForValues::Default => Span::empty(),
684        }
685    }
686}
687
688impl Spanned for CreateIndex {
689    fn span(&self) -> Span {
690        let CreateIndex {
691            name,
692            table_name,
693            using: _,
694            columns,
695            unique: _,        // bool
696            concurrently: _,  // bool
697            r#async: _,       // bool
698            if_not_exists: _, // bool
699            include,
700            nulls_distinct: _, // bool
701            with,
702            predicate,
703            index_options: _,
704            alter_options,
705        } = self;
706
707        union_spans(
708            name.iter()
709                .map(|i| i.span())
710                .chain(core::iter::once(table_name.span()))
711                .chain(columns.iter().map(|i| i.column.span()))
712                .chain(include.iter().map(|i| i.span))
713                .chain(with.iter().map(|i| i.span()))
714                .chain(predicate.iter().map(|i| i.span()))
715                .chain(alter_options.iter().map(|i| i.span())),
716        )
717    }
718}
719
720impl Spanned for IndexColumn {
721    fn span(&self) -> Span {
722        self.column.span()
723    }
724}
725
726impl Spanned for CaseStatement {
727    fn span(&self) -> Span {
728        let CaseStatement {
729            case_token: AttachedToken(start),
730            match_expr: _,
731            when_blocks: _,
732            else_block: _,
733            end_case_token: AttachedToken(end),
734        } = self;
735
736        union_spans([start.span, end.span].into_iter())
737    }
738}
739
740impl Spanned for IfStatement {
741    fn span(&self) -> Span {
742        let IfStatement {
743            if_block,
744            elseif_blocks,
745            else_block,
746            end_token,
747        } = self;
748
749        union_spans(
750            iter::once(if_block.span())
751                .chain(elseif_blocks.iter().map(|b| b.span()))
752                .chain(else_block.as_ref().map(|b| b.span()))
753                .chain(end_token.as_ref().map(|AttachedToken(t)| t.span)),
754        )
755    }
756}
757
758impl Spanned for WhileStatement {
759    fn span(&self) -> Span {
760        let WhileStatement { while_block } = self;
761
762        while_block.span()
763    }
764}
765
766impl Spanned for ConditionalStatements {
767    fn span(&self) -> Span {
768        match self {
769            ConditionalStatements::Sequence { statements } => {
770                union_spans(statements.iter().map(|s| s.span()))
771            }
772            ConditionalStatements::BeginEnd(bes) => bes.span(),
773        }
774    }
775}
776
777impl Spanned for ConditionalStatementBlock {
778    fn span(&self) -> Span {
779        let ConditionalStatementBlock {
780            start_token: AttachedToken(start_token),
781            condition,
782            then_token,
783            conditional_statements,
784        } = self;
785
786        union_spans(
787            iter::once(start_token.span)
788                .chain(condition.as_ref().map(|c| c.span()))
789                .chain(then_token.as_ref().map(|AttachedToken(t)| t.span))
790                .chain(iter::once(conditional_statements.span())),
791        )
792    }
793}
794
795impl Spanned for RaiseStatement {
796    fn span(&self) -> Span {
797        let RaiseStatement { value } = self;
798
799        union_spans(value.iter().map(|value| value.span()))
800    }
801}
802
803impl Spanned for RaiseStatementValue {
804    fn span(&self) -> Span {
805        match self {
806            RaiseStatementValue::UsingMessage(expr) => expr.span(),
807            RaiseStatementValue::Expr(expr) => expr.span(),
808        }
809    }
810}
811
812/// # partial span
813///
814/// Missing spans:
815/// - [ColumnOption::Null]
816/// - [ColumnOption::NotNull]
817/// - [ColumnOption::Comment]
818/// - [ColumnOption::PrimaryKey]
819/// - [ColumnOption::Unique]
820/// - [ColumnOption::DialectSpecific]
821/// - [ColumnOption::Generated]
822impl Spanned for ColumnOption {
823    fn span(&self) -> Span {
824        match self {
825            ColumnOption::Null => Span::empty(),
826            ColumnOption::NotNull => Span::empty(),
827            ColumnOption::Default(expr) => expr.span(),
828            ColumnOption::Materialized(expr) => expr.span(),
829            ColumnOption::Ephemeral(expr) => expr.as_ref().map_or(Span::empty(), |e| e.span()),
830            ColumnOption::Alias(expr) => expr.span(),
831            ColumnOption::PrimaryKey(constraint) => constraint.span(),
832            ColumnOption::Unique(constraint) => constraint.span(),
833            ColumnOption::Check(constraint) => constraint.span(),
834            ColumnOption::ForeignKey(constraint) => constraint.span(),
835            ColumnOption::DialectSpecific(_) => Span::empty(),
836            ColumnOption::CharacterSet(object_name) => object_name.span(),
837            ColumnOption::Collation(object_name) => object_name.span(),
838            ColumnOption::Comment(_) => Span::empty(),
839            ColumnOption::OnUpdate(expr) => expr.span(),
840            ColumnOption::Generated { .. } => Span::empty(),
841            ColumnOption::Options(vec) => union_spans(vec.iter().map(|i| i.span())),
842            ColumnOption::Identity(..) => Span::empty(),
843            ColumnOption::OnConflict(..) => Span::empty(),
844            ColumnOption::Policy(..) => Span::empty(),
845            ColumnOption::Tags(..) => Span::empty(),
846            ColumnOption::Srid(..) => Span::empty(),
847            ColumnOption::Invisible => Span::empty(),
848        }
849    }
850}
851
852/// # missing span
853impl Spanned for ReferentialAction {
854    fn span(&self) -> Span {
855        Span::empty()
856    }
857}
858
859/// # missing span
860impl Spanned for ConstraintCharacteristics {
861    fn span(&self) -> Span {
862        let ConstraintCharacteristics {
863            deferrable: _, // bool
864            initially: _,  // enum
865            enforced: _,   // bool
866        } = self;
867
868        Span::empty()
869    }
870}
871
872impl Spanned for Analyze {
873    fn span(&self) -> Span {
874        union_spans(
875            self.table_name
876                .iter()
877                .map(|t| t.span())
878                .chain(
879                    self.partitions
880                        .iter()
881                        .flat_map(|i| i.iter().map(|k| k.span())),
882                )
883                .chain(self.columns.iter().map(|i| i.span)),
884        )
885    }
886}
887
888/// # partial span
889///
890/// Missing spans:
891/// - [AlterColumnOperation::SetNotNull]
892/// - [AlterColumnOperation::DropNotNull]
893/// - [AlterColumnOperation::DropDefault]
894/// - [AlterColumnOperation::AddGenerated]
895impl Spanned for AlterColumnOperation {
896    fn span(&self) -> Span {
897        match self {
898            AlterColumnOperation::SetNotNull => Span::empty(),
899            AlterColumnOperation::DropNotNull => Span::empty(),
900            AlterColumnOperation::SetDefault { value } => value.span(),
901            AlterColumnOperation::DropDefault => Span::empty(),
902            AlterColumnOperation::SetDataType {
903                data_type: _,
904                using,
905                had_set: _,
906            } => using.as_ref().map_or(Span::empty(), |u| u.span()),
907            AlterColumnOperation::AddGenerated { .. } => Span::empty(),
908        }
909    }
910}
911
912impl Spanned for CopySource {
913    fn span(&self) -> Span {
914        match self {
915            CopySource::Table {
916                table_name,
917                columns,
918            } => union_spans(
919                core::iter::once(table_name.span()).chain(columns.iter().map(|i| i.span)),
920            ),
921            CopySource::Query(query) => query.span(),
922        }
923    }
924}
925
926impl Spanned for Delete {
927    fn span(&self) -> Span {
928        let Delete {
929            delete_token,
930            optimizer_hints: _,
931            tables,
932            from,
933            using,
934            selection,
935            returning,
936            output,
937            order_by,
938            limit,
939        } = self;
940
941        union_spans(
942            core::iter::once(delete_token.0.span).chain(
943                tables
944                    .iter()
945                    .map(|i| i.span())
946                    .chain(core::iter::once(from.span()))
947                    .chain(
948                        using
949                            .iter()
950                            .map(|u| union_spans(u.iter().map(|i| i.span()))),
951                    )
952                    .chain(selection.iter().map(|i| i.span()))
953                    .chain(returning.iter().flat_map(|i| i.iter().map(|k| k.span())))
954                    .chain(output.iter().map(|i| i.span()))
955                    .chain(order_by.iter().map(|i| i.span()))
956                    .chain(limit.iter().map(|i| i.span())),
957            ),
958        )
959    }
960}
961
962impl Spanned for Update {
963    fn span(&self) -> Span {
964        let Update {
965            update_token,
966            optimizer_hints: _,
967            table,
968            assignments,
969            from,
970            selection,
971            returning,
972            output,
973            or: _,
974            order_by,
975            limit,
976        } = self;
977
978        union_spans(
979            core::iter::once(table.span())
980                .chain(core::iter::once(update_token.0.span))
981                .chain(assignments.iter().map(|i| i.span()))
982                .chain(from.iter().map(|i| i.span()))
983                .chain(selection.iter().map(|i| i.span()))
984                .chain(returning.iter().flat_map(|i| i.iter().map(|k| k.span())))
985                .chain(output.iter().map(|i| i.span()))
986                .chain(order_by.iter().map(|i| i.span()))
987                .chain(limit.iter().map(|i| i.span())),
988        )
989    }
990}
991
992impl Spanned for Merge {
993    fn span(&self) -> Span {
994        union_spans(
995            [self.merge_token.0.span, self.on.span()]
996                .into_iter()
997                .chain(self.clauses.iter().map(Spanned::span))
998                .chain(self.output.iter().map(Spanned::span)),
999        )
1000    }
1001}
1002
1003impl Spanned for FromTable {
1004    fn span(&self) -> Span {
1005        match self {
1006            FromTable::WithFromKeyword(vec) => union_spans(vec.iter().map(|i| i.span())),
1007            FromTable::WithoutKeyword(vec) => union_spans(vec.iter().map(|i| i.span())),
1008        }
1009    }
1010}
1011
1012impl Spanned for ViewColumnDef {
1013    fn span(&self) -> Span {
1014        let ViewColumnDef {
1015            name,
1016            data_type: _, // todo, DataType
1017            options,
1018        } = self;
1019
1020        name.span.union_opt(&options.as_ref().map(|o| o.span()))
1021    }
1022}
1023
1024impl Spanned for ColumnOptions {
1025    fn span(&self) -> Span {
1026        union_spans(self.as_slice().iter().map(|i| i.span()))
1027    }
1028}
1029
1030impl Spanned for SqlOption {
1031    fn span(&self) -> Span {
1032        match self {
1033            SqlOption::Clustered(table_options_clustered) => table_options_clustered.span(),
1034            SqlOption::Ident(ident) => ident.span,
1035            SqlOption::KeyValue { key, value } => key.span.union(&value.span()),
1036            SqlOption::Partition {
1037                column_name,
1038                range_direction: _,
1039                for_values,
1040            } => union_spans(
1041                core::iter::once(column_name.span).chain(for_values.iter().map(|i| i.span())),
1042            ),
1043            SqlOption::TableSpace(_) => Span::empty(),
1044            SqlOption::Comment(_) => Span::empty(),
1045            SqlOption::NamedParenthesizedList(NamedParenthesizedList {
1046                key: name,
1047                name: value,
1048                values,
1049            }) => union_spans(core::iter::once(name.span).chain(values.iter().map(|i| i.span)))
1050                .union_opt(&value.as_ref().map(|i| i.span)),
1051        }
1052    }
1053}
1054
1055/// # partial span
1056///
1057/// Missing spans:
1058/// - [TableOptionsClustered::ColumnstoreIndex]
1059impl Spanned for TableOptionsClustered {
1060    fn span(&self) -> Span {
1061        match self {
1062            TableOptionsClustered::ColumnstoreIndex => Span::empty(),
1063            TableOptionsClustered::ColumnstoreIndexOrder(vec) => {
1064                union_spans(vec.iter().map(|i| i.span))
1065            }
1066            TableOptionsClustered::Index(vec) => union_spans(vec.iter().map(|i| i.span())),
1067        }
1068    }
1069}
1070
1071impl Spanned for ClusteredIndex {
1072    fn span(&self) -> Span {
1073        let ClusteredIndex {
1074            name,
1075            asc: _, // bool
1076        } = self;
1077
1078        name.span
1079    }
1080}
1081
1082impl Spanned for CreateTableOptions {
1083    fn span(&self) -> Span {
1084        match self {
1085            CreateTableOptions::None => Span::empty(),
1086            CreateTableOptions::With(vec) => union_spans(vec.iter().map(|i| i.span())),
1087            CreateTableOptions::Options(vec) => {
1088                union_spans(vec.as_slice().iter().map(|i| i.span()))
1089            }
1090            CreateTableOptions::Plain(vec) => union_spans(vec.iter().map(|i| i.span())),
1091            CreateTableOptions::TableProperties(vec) => union_spans(vec.iter().map(|i| i.span())),
1092        }
1093    }
1094}
1095
1096/// # partial span
1097///
1098/// Missing spans:
1099/// - [AlterTableOperation::OwnerTo]
1100impl Spanned for AlterTableOperation {
1101    fn span(&self) -> Span {
1102        match self {
1103            AlterTableOperation::AddConstraint {
1104                constraint,
1105                not_valid: _,
1106            } => constraint.span(),
1107            AlterTableOperation::AddColumn {
1108                column_keyword: _,
1109                if_not_exists: _,
1110                column_def,
1111                column_position: _,
1112            } => column_def.span(),
1113            AlterTableOperation::AddProjection {
1114                if_not_exists: _,
1115                name,
1116                select,
1117            } => name.span.union(&select.span()),
1118            AlterTableOperation::DropProjection { if_exists: _, name } => name.span,
1119            AlterTableOperation::MaterializeProjection {
1120                if_exists: _,
1121                name,
1122                partition,
1123            } => name.span.union_opt(&partition.as_ref().map(|i| i.span)),
1124            AlterTableOperation::ClearProjection {
1125                if_exists: _,
1126                name,
1127                partition,
1128            } => name.span.union_opt(&partition.as_ref().map(|i| i.span)),
1129            AlterTableOperation::DisableRowLevelSecurity => Span::empty(),
1130            AlterTableOperation::DisableRule { name } => name.span,
1131            AlterTableOperation::DisableTrigger { name } => name.span,
1132            AlterTableOperation::DropConstraint {
1133                if_exists: _,
1134                name,
1135                drop_behavior: _,
1136            } => name.span,
1137            AlterTableOperation::DropColumn {
1138                has_column_keyword: _,
1139                column_names,
1140                if_exists: _,
1141                drop_behavior: _,
1142            } => union_spans(column_names.iter().map(|i| i.span)),
1143            AlterTableOperation::AttachPartition { partition } => partition.span(),
1144            AlterTableOperation::DetachPartition { partition } => partition.span(),
1145            AlterTableOperation::FreezePartition {
1146                partition,
1147                with_name,
1148            } => partition
1149                .span()
1150                .union_opt(&with_name.as_ref().map(|n| n.span)),
1151            AlterTableOperation::UnfreezePartition {
1152                partition,
1153                with_name,
1154            } => partition
1155                .span()
1156                .union_opt(&with_name.as_ref().map(|n| n.span)),
1157            AlterTableOperation::DropPrimaryKey { .. } => Span::empty(),
1158            AlterTableOperation::DropForeignKey { name, .. } => name.span,
1159            AlterTableOperation::DropIndex { name } => name.span,
1160            AlterTableOperation::EnableAlwaysRule { name } => name.span,
1161            AlterTableOperation::EnableAlwaysTrigger { name } => name.span,
1162            AlterTableOperation::EnableReplicaRule { name } => name.span,
1163            AlterTableOperation::EnableReplicaTrigger { name } => name.span,
1164            AlterTableOperation::EnableRowLevelSecurity => Span::empty(),
1165            AlterTableOperation::ForceRowLevelSecurity => Span::empty(),
1166            AlterTableOperation::NoForceRowLevelSecurity => Span::empty(),
1167            AlterTableOperation::EnableRule { name } => name.span,
1168            AlterTableOperation::EnableTrigger { name } => name.span,
1169            AlterTableOperation::RenamePartitions {
1170                old_partitions,
1171                new_partitions,
1172            } => union_spans(
1173                old_partitions
1174                    .iter()
1175                    .map(|i| i.span())
1176                    .chain(new_partitions.iter().map(|i| i.span())),
1177            ),
1178            AlterTableOperation::AddPartitions {
1179                if_not_exists: _,
1180                new_partitions,
1181            } => union_spans(new_partitions.iter().map(|i| i.span())),
1182            AlterTableOperation::DropPartitions {
1183                partitions,
1184                if_exists: _,
1185            } => union_spans(partitions.iter().map(|i| i.span())),
1186            AlterTableOperation::RenameColumn {
1187                old_column_name,
1188                new_column_name,
1189            } => old_column_name.span.union(&new_column_name.span),
1190            AlterTableOperation::RenameTable { table_name } => table_name.span(),
1191            AlterTableOperation::ChangeColumn {
1192                old_name,
1193                new_name,
1194                data_type: _,
1195                options,
1196                column_position: _,
1197            } => union_spans(
1198                core::iter::once(old_name.span)
1199                    .chain(core::iter::once(new_name.span))
1200                    .chain(options.iter().map(|i| i.span())),
1201            ),
1202            AlterTableOperation::ModifyColumn {
1203                col_name,
1204                data_type: _,
1205                options,
1206                column_position: _,
1207            } => {
1208                union_spans(core::iter::once(col_name.span).chain(options.iter().map(|i| i.span())))
1209            }
1210            AlterTableOperation::RenameConstraint { old_name, new_name } => {
1211                old_name.span.union(&new_name.span)
1212            }
1213            AlterTableOperation::AlterColumn { column_name, op } => {
1214                column_name.span.union(&op.span())
1215            }
1216            AlterTableOperation::SwapWith { table_name } => table_name.span(),
1217            AlterTableOperation::SetTblProperties { table_properties } => {
1218                union_spans(table_properties.iter().map(|i| i.span()))
1219            }
1220            AlterTableOperation::OwnerTo { .. } => Span::empty(),
1221            AlterTableOperation::ClusterBy { exprs } => union_spans(exprs.iter().map(|e| e.span())),
1222            AlterTableOperation::DropClusteringKey => Span::empty(),
1223            AlterTableOperation::AlterSortKey { .. } => Span::empty(),
1224            AlterTableOperation::SuspendRecluster => Span::empty(),
1225            AlterTableOperation::ResumeRecluster => Span::empty(),
1226            AlterTableOperation::Refresh { .. } => Span::empty(),
1227            AlterTableOperation::Suspend => Span::empty(),
1228            AlterTableOperation::Resume => Span::empty(),
1229            AlterTableOperation::Algorithm { .. } => Span::empty(),
1230            AlterTableOperation::AutoIncrement { value, .. } => value.span(),
1231            AlterTableOperation::Lock { .. } => Span::empty(),
1232            AlterTableOperation::ReplicaIdentity { .. } => Span::empty(),
1233            AlterTableOperation::ValidateConstraint { name } => name.span,
1234            AlterTableOperation::SetOptionsParens { options } => {
1235                union_spans(options.iter().map(|i| i.span()))
1236            }
1237        }
1238    }
1239}
1240
1241impl Spanned for Partition {
1242    fn span(&self) -> Span {
1243        match self {
1244            Partition::Identifier(ident) => ident.span,
1245            Partition::Expr(expr) => expr.span(),
1246            Partition::Part(expr) => expr.span(),
1247            Partition::Partitions(vec) => union_spans(vec.iter().map(|i| i.span())),
1248        }
1249    }
1250}
1251
1252impl Spanned for ProjectionSelect {
1253    fn span(&self) -> Span {
1254        let ProjectionSelect {
1255            projection,
1256            order_by,
1257            group_by,
1258        } = self;
1259
1260        union_spans(
1261            projection
1262                .iter()
1263                .map(|i| i.span())
1264                .chain(order_by.iter().map(|i| i.span()))
1265                .chain(group_by.iter().map(|i| i.span())),
1266        )
1267    }
1268}
1269
1270/// # partial span
1271///
1272/// Missing spans:
1273/// - [OrderByKind::All]
1274impl Spanned for OrderBy {
1275    fn span(&self) -> Span {
1276        match &self.kind {
1277            OrderByKind::All(_) => Span::empty(),
1278            OrderByKind::Expressions(exprs) => union_spans(
1279                exprs
1280                    .iter()
1281                    .map(|i| i.span())
1282                    .chain(self.interpolate.iter().map(|i| i.span())),
1283            ),
1284        }
1285    }
1286}
1287
1288/// # partial span
1289///
1290/// Missing spans:
1291/// - [GroupByExpr::All]
1292impl Spanned for GroupByExpr {
1293    fn span(&self) -> Span {
1294        match self {
1295            GroupByExpr::All(_) => Span::empty(),
1296            GroupByExpr::Expressions(exprs, _modifiers) => {
1297                union_spans(exprs.iter().map(|i| i.span()))
1298            }
1299        }
1300    }
1301}
1302
1303impl Spanned for Interpolate {
1304    fn span(&self) -> Span {
1305        let Interpolate { exprs } = self;
1306
1307        union_spans(exprs.iter().flat_map(|i| i.iter().map(|e| e.span())))
1308    }
1309}
1310
1311impl Spanned for InterpolateExpr {
1312    fn span(&self) -> Span {
1313        let InterpolateExpr { column, expr } = self;
1314
1315        column.span.union_opt(&expr.as_ref().map(|e| e.span()))
1316    }
1317}
1318
1319impl Spanned for AlterIndexOperation {
1320    fn span(&self) -> Span {
1321        match self {
1322            AlterIndexOperation::RenameIndex { index_name } => index_name.span(),
1323        }
1324    }
1325}
1326
1327/// # partial span
1328///
1329/// Missing spans:ever
1330/// - [Insert::insert_alias]
1331impl Spanned for Insert {
1332    fn span(&self) -> Span {
1333        let Insert {
1334            insert_token,
1335            optimizer_hints: _,
1336            or: _,     // enum, sqlite specific
1337            ignore: _, // bool
1338            into: _,   // bool
1339            table,
1340            table_alias,
1341            columns,
1342            overwrite: _, // bool
1343            source,
1344            partitioned,
1345            after_columns,
1346            has_table_keyword: _, // bool
1347            on,
1348            returning,
1349            output,
1350            replace_into: _, // bool
1351            priority: _,     // todo, mysql specific
1352            insert_alias: _, // todo, mysql specific
1353            assignments,
1354            settings: _,                 // todo, clickhouse specific
1355            format_clause: _,            // todo, clickhouse specific
1356            multi_table_insert_type: _,  // snowflake multi-table insert
1357            multi_table_into_clauses: _, // snowflake multi-table insert
1358            multi_table_when_clauses: _, // snowflake multi-table insert
1359            multi_table_else_clause: _,  // snowflake multi-table insert
1360        } = self;
1361
1362        union_spans(
1363            core::iter::once(insert_token.0.span)
1364                .chain(core::iter::once(table.span()))
1365                .chain(table_alias.iter().map(|k| k.alias.span))
1366                .chain(columns.iter().map(|i| i.span()))
1367                .chain(source.as_ref().map(|q| q.span()))
1368                .chain(assignments.iter().map(|i| i.span()))
1369                .chain(partitioned.iter().flat_map(|i| i.iter().map(|k| k.span())))
1370                .chain(after_columns.iter().map(|i| i.span))
1371                .chain(on.as_ref().map(|i| i.span()))
1372                .chain(returning.iter().flat_map(|i| i.iter().map(|k| k.span())))
1373                .chain(output.iter().map(|i| i.span())),
1374        )
1375    }
1376}
1377
1378impl Spanned for OnInsert {
1379    fn span(&self) -> Span {
1380        match self {
1381            OnInsert::DuplicateKeyUpdate(vec) => union_spans(vec.iter().map(|i| i.span())),
1382            OnInsert::OnConflict(on_conflict) => on_conflict.span(),
1383        }
1384    }
1385}
1386
1387impl Spanned for OnConflict {
1388    fn span(&self) -> Span {
1389        let OnConflict {
1390            conflict_target,
1391            action,
1392        } = self;
1393
1394        action
1395            .span()
1396            .union_opt(&conflict_target.as_ref().map(|i| i.span()))
1397    }
1398}
1399
1400impl Spanned for ConflictTarget {
1401    fn span(&self) -> Span {
1402        match self {
1403            ConflictTarget::Columns(vec) => union_spans(vec.iter().map(|i| i.span)),
1404            ConflictTarget::OnConstraint(object_name) => object_name.span(),
1405        }
1406    }
1407}
1408
1409/// # partial span
1410///
1411/// Missing spans:
1412/// - [OnConflictAction::DoNothing]
1413impl Spanned for OnConflictAction {
1414    fn span(&self) -> Span {
1415        match self {
1416            OnConflictAction::DoNothing => Span::empty(),
1417            OnConflictAction::DoUpdate(do_update) => do_update.span(),
1418        }
1419    }
1420}
1421
1422impl Spanned for DoUpdate {
1423    fn span(&self) -> Span {
1424        let DoUpdate {
1425            assignments,
1426            selection,
1427        } = self;
1428
1429        union_spans(
1430            assignments
1431                .iter()
1432                .map(|i| i.span())
1433                .chain(selection.iter().map(|i| i.span())),
1434        )
1435    }
1436}
1437
1438impl Spanned for Assignment {
1439    fn span(&self) -> Span {
1440        let Assignment { target, value } = self;
1441
1442        target.span().union(&value.span())
1443    }
1444}
1445
1446impl Spanned for AssignmentTarget {
1447    fn span(&self) -> Span {
1448        match self {
1449            AssignmentTarget::ColumnName(object_name) => object_name.span(),
1450            AssignmentTarget::Tuple(vec) => union_spans(vec.iter().map(|i| i.span())),
1451        }
1452    }
1453}
1454
1455/// # partial span
1456///
1457/// Most expressions are missing keywords in their spans.
1458/// f.e. `IS NULL <expr>` reports as `<expr>::span`.
1459///
1460/// Missing spans:
1461/// - [Expr::MatchAgainst] # MySQL specific
1462/// - [Expr::RLike] # MySQL specific
1463/// - [Expr::Struct] # BigQuery specific
1464/// - [Expr::Named] # BigQuery specific
1465/// - [Expr::Dictionary] # DuckDB specific
1466/// - [Expr::Map] # DuckDB specific
1467/// - [Expr::Lambda]
1468impl Spanned for Expr {
1469    fn span(&self) -> Span {
1470        match self {
1471            Expr::Identifier(ident) => ident.span,
1472            Expr::CompoundIdentifier(vec) => union_spans(vec.iter().map(|i| i.span)),
1473            Expr::CompoundFieldAccess { root, access_chain } => {
1474                union_spans(iter::once(root.span()).chain(access_chain.iter().map(|i| i.span())))
1475            }
1476            Expr::IsFalse(expr) => expr.span(),
1477            Expr::IsNotFalse(expr) => expr.span(),
1478            Expr::IsTrue(expr) => expr.span(),
1479            Expr::IsNotTrue(expr) => expr.span(),
1480            Expr::IsNull(expr) => expr.span(),
1481            Expr::IsNotNull(expr) => expr.span(),
1482            Expr::IsUnknown(expr) => expr.span(),
1483            Expr::IsNotUnknown(expr) => expr.span(),
1484            Expr::IsDistinctFrom(lhs, rhs) => lhs.span().union(&rhs.span()),
1485            Expr::IsNotDistinctFrom(lhs, rhs) => lhs.span().union(&rhs.span()),
1486            Expr::InList {
1487                expr,
1488                list,
1489                negated: _,
1490            } => union_spans(
1491                core::iter::once(expr.span()).chain(list.iter().map(|item| item.span())),
1492            ),
1493            Expr::InSubquery {
1494                expr,
1495                subquery,
1496                negated: _,
1497            } => expr.span().union(&subquery.span()),
1498            Expr::InUnnest {
1499                expr,
1500                array_expr,
1501                negated: _,
1502            } => expr.span().union(&array_expr.span()),
1503            Expr::Between {
1504                expr,
1505                negated: _,
1506                low,
1507                high,
1508            } => expr.span().union(&low.span()).union(&high.span()),
1509
1510            Expr::BinaryOp { left, op: _, right } => left.span().union(&right.span()),
1511            Expr::Like {
1512                negated: _,
1513                expr,
1514                pattern,
1515                escape_char: _,
1516                any: _,
1517            } => expr.span().union(&pattern.span()),
1518            Expr::ILike {
1519                negated: _,
1520                expr,
1521                pattern,
1522                escape_char: _,
1523                any: _,
1524            } => expr.span().union(&pattern.span()),
1525            Expr::RLike { .. } => Span::empty(),
1526            Expr::IsNormalized {
1527                expr,
1528                form: _,
1529                negated: _,
1530            } => expr.span(),
1531            Expr::SimilarTo {
1532                negated: _,
1533                expr,
1534                pattern,
1535                escape_char: _,
1536            } => expr.span().union(&pattern.span()),
1537            Expr::Ceil { expr, field: _ } => expr.span(),
1538            Expr::Floor { expr, field: _ } => expr.span(),
1539            Expr::Position { expr, r#in } => expr.span().union(&r#in.span()),
1540            Expr::Overlay {
1541                expr,
1542                overlay_what,
1543                overlay_from,
1544                overlay_for,
1545            } => expr
1546                .span()
1547                .union(&overlay_what.span())
1548                .union(&overlay_from.span())
1549                .union_opt(&overlay_for.as_ref().map(|i| i.span())),
1550            Expr::Collate { expr, collation } => expr
1551                .span()
1552                .union(&union_spans(collation.0.iter().map(|i| i.span()))),
1553            Expr::Nested(expr) => expr.span(),
1554            Expr::Value(value) => value.span(),
1555            Expr::TypedString(TypedString { value, .. }) => value.span(),
1556            Expr::Function(function) => function.span(),
1557            Expr::GroupingSets(vec) => {
1558                union_spans(vec.iter().flat_map(|i| i.iter().map(|k| k.span())))
1559            }
1560            Expr::Cube(vec) => union_spans(vec.iter().flat_map(|i| i.iter().map(|k| k.span()))),
1561            Expr::Rollup(vec) => union_spans(vec.iter().flat_map(|i| i.iter().map(|k| k.span()))),
1562            Expr::Tuple(vec) => union_spans(vec.iter().map(|i| i.span())),
1563            Expr::Array(array) => array.span(),
1564            Expr::MatchAgainst { .. } => Span::empty(),
1565            Expr::JsonAccess { value, path } => value.span().union(&path.span()),
1566            Expr::AnyOp {
1567                left,
1568                compare_op: _,
1569                right,
1570                is_some: _,
1571            } => left.span().union(&right.span()),
1572            Expr::AllOp {
1573                left,
1574                compare_op: _,
1575                right,
1576            } => left.span().union(&right.span()),
1577            Expr::UnaryOp { op: _, expr } => expr.span(),
1578            Expr::Convert {
1579                expr,
1580                data_type: _,
1581                charset,
1582                target_before_value: _,
1583                styles,
1584                is_try: _,
1585            } => union_spans(
1586                core::iter::once(expr.span())
1587                    .chain(charset.as_ref().map(|i| i.span()))
1588                    .chain(styles.iter().map(|i| i.span())),
1589            ),
1590            Expr::Cast {
1591                kind: _,
1592                expr,
1593                data_type: _,
1594                array: _,
1595                format: _,
1596            } => expr.span(),
1597            Expr::AtTimeZone {
1598                timestamp,
1599                time_zone,
1600            } => timestamp.span().union(&time_zone.span()),
1601            Expr::Extract {
1602                field: _,
1603                syntax: _,
1604                expr,
1605            } => expr.span(),
1606            Expr::Substring {
1607                expr,
1608                substring_from,
1609                substring_for,
1610                special: _,
1611                shorthand: _,
1612            } => union_spans(
1613                core::iter::once(expr.span())
1614                    .chain(substring_from.as_ref().map(|i| i.span()))
1615                    .chain(substring_for.as_ref().map(|i| i.span())),
1616            ),
1617            Expr::Trim {
1618                expr,
1619                trim_where: _,
1620                trim_what,
1621                trim_characters,
1622            } => union_spans(
1623                core::iter::once(expr.span())
1624                    .chain(trim_what.as_ref().map(|i| i.span()))
1625                    .chain(
1626                        trim_characters
1627                            .as_ref()
1628                            .map(|items| union_spans(items.iter().map(|i| i.span()))),
1629                    ),
1630            ),
1631            Expr::Prefixed { value, .. } => value.span(),
1632            Expr::Case {
1633                case_token,
1634                end_token,
1635                operand,
1636                conditions,
1637                else_result,
1638            } => union_spans(
1639                iter::once(case_token.0.span)
1640                    .chain(
1641                        operand
1642                            .as_ref()
1643                            .map(|i| i.span())
1644                            .into_iter()
1645                            .chain(conditions.iter().flat_map(|case_when| {
1646                                [case_when.condition.span(), case_when.result.span()]
1647                            }))
1648                            .chain(else_result.as_ref().map(|i| i.span())),
1649                    )
1650                    .chain(iter::once(end_token.0.span)),
1651            ),
1652            Expr::Exists { subquery, .. } => subquery.span(),
1653            Expr::Subquery(query) => query.span(),
1654            Expr::Struct { .. } => Span::empty(),
1655            Expr::Named { .. } => Span::empty(),
1656            Expr::Dictionary(_) => Span::empty(),
1657            Expr::Map(_) => Span::empty(),
1658            Expr::Interval(interval) => interval.value.span(),
1659            Expr::Wildcard(token) => token.0.span,
1660            Expr::QualifiedWildcard(object_name, token) => union_spans(
1661                object_name
1662                    .0
1663                    .iter()
1664                    .map(|i| i.span())
1665                    .chain(iter::once(token.0.span)),
1666            ),
1667            Expr::OuterJoin(expr) => expr.span(),
1668            Expr::Prior(expr) => expr.span(),
1669            Expr::Lambda(_) => Span::empty(),
1670            Expr::MemberOf(member_of) => member_of.value.span().union(&member_of.array.span()),
1671        }
1672    }
1673}
1674
1675impl Spanned for Subscript {
1676    fn span(&self) -> Span {
1677        match self {
1678            Subscript::Index { index } => index.span(),
1679            Subscript::Slice {
1680                lower_bound,
1681                upper_bound,
1682                stride,
1683            } => union_spans(
1684                [
1685                    lower_bound.as_ref().map(|i| i.span()),
1686                    upper_bound.as_ref().map(|i| i.span()),
1687                    stride.as_ref().map(|i| i.span()),
1688                ]
1689                .into_iter()
1690                .flatten(),
1691            ),
1692        }
1693    }
1694}
1695
1696impl Spanned for AccessExpr {
1697    fn span(&self) -> Span {
1698        match self {
1699            AccessExpr::Dot(ident) => ident.span(),
1700            AccessExpr::Subscript(subscript) => subscript.span(),
1701        }
1702    }
1703}
1704
1705impl Spanned for ObjectName {
1706    fn span(&self) -> Span {
1707        let ObjectName(segments) = self;
1708
1709        union_spans(segments.iter().map(|i| i.span()))
1710    }
1711}
1712
1713impl Spanned for ObjectNamePart {
1714    fn span(&self) -> Span {
1715        match self {
1716            ObjectNamePart::Identifier(ident) => ident.span,
1717            ObjectNamePart::Function(func) => func
1718                .name
1719                .span
1720                .union(&union_spans(func.args.iter().map(|i| i.span()))),
1721        }
1722    }
1723}
1724
1725impl Spanned for Array {
1726    fn span(&self) -> Span {
1727        let Array {
1728            elem,
1729            named: _, // bool
1730        } = self;
1731
1732        union_spans(elem.iter().map(|i| i.span()))
1733    }
1734}
1735
1736impl Spanned for Function {
1737    fn span(&self) -> Span {
1738        let Function {
1739            name,
1740            uses_odbc_syntax: _,
1741            parameters,
1742            args,
1743            filter,
1744            null_treatment: _, // enum
1745            over: _,           // todo
1746            within_group,
1747        } = self;
1748
1749        union_spans(
1750            name.0
1751                .iter()
1752                .map(|i| i.span())
1753                .chain(iter::once(args.span()))
1754                .chain(iter::once(parameters.span()))
1755                .chain(filter.iter().map(|i| i.span()))
1756                .chain(within_group.iter().map(|i| i.span())),
1757        )
1758    }
1759}
1760
1761/// # partial span
1762///
1763/// The span of [FunctionArguments::None] is empty.
1764impl Spanned for FunctionArguments {
1765    fn span(&self) -> Span {
1766        match self {
1767            FunctionArguments::None => Span::empty(),
1768            FunctionArguments::Subquery(query) => query.span(),
1769            FunctionArguments::List(list) => list.span(),
1770        }
1771    }
1772}
1773
1774impl Spanned for FunctionArgumentList {
1775    fn span(&self) -> Span {
1776        let FunctionArgumentList {
1777            duplicate_treatment: _, // enum
1778            args,
1779            clauses,
1780        } = self;
1781
1782        union_spans(
1783            // # todo: duplicate-treatment span
1784            args.iter()
1785                .map(|i| i.span())
1786                .chain(clauses.iter().map(|i| i.span())),
1787        )
1788    }
1789}
1790
1791impl Spanned for FunctionArgumentClause {
1792    fn span(&self) -> Span {
1793        match self {
1794            FunctionArgumentClause::IgnoreOrRespectNulls(_) => Span::empty(),
1795            FunctionArgumentClause::OrderBy(vec) => union_spans(vec.iter().map(|i| i.expr.span())),
1796            FunctionArgumentClause::Limit(expr) => expr.span(),
1797            FunctionArgumentClause::OnOverflow(_) => Span::empty(),
1798            FunctionArgumentClause::Having(HavingBound(_kind, expr)) => expr.span(),
1799            FunctionArgumentClause::Separator(value) => value.span(),
1800            FunctionArgumentClause::JsonNullClause(_) => Span::empty(),
1801            FunctionArgumentClause::JsonReturningClause(_) => Span::empty(),
1802        }
1803    }
1804}
1805
1806/// # partial span
1807///
1808/// see Spanned impl for JsonPathElem for more information
1809impl Spanned for JsonPath {
1810    fn span(&self) -> Span {
1811        let JsonPath { path } = self;
1812
1813        union_spans(path.iter().map(|i| i.span()))
1814    }
1815}
1816
1817/// # partial span
1818///
1819/// Missing spans:
1820/// - [JsonPathElem::Dot]
1821impl Spanned for JsonPathElem {
1822    fn span(&self) -> Span {
1823        match self {
1824            JsonPathElem::Dot { .. } => Span::empty(),
1825            JsonPathElem::Bracket { key } => key.span(),
1826            JsonPathElem::ColonBracket { key } => key.span(),
1827        }
1828    }
1829}
1830
1831impl Spanned for SelectItemQualifiedWildcardKind {
1832    fn span(&self) -> Span {
1833        match self {
1834            SelectItemQualifiedWildcardKind::ObjectName(object_name) => object_name.span(),
1835            SelectItemQualifiedWildcardKind::Expr(expr) => expr.span(),
1836        }
1837    }
1838}
1839
1840impl Spanned for SelectItem {
1841    fn span(&self) -> Span {
1842        match self {
1843            SelectItem::UnnamedExpr(expr) => expr.span(),
1844            SelectItem::ExprWithAlias { expr, alias } => expr.span().union(&alias.span),
1845            SelectItem::ExprWithAliases { expr, aliases } => {
1846                union_spans(iter::once(expr.span()).chain(aliases.iter().map(|i| i.span)))
1847            }
1848            SelectItem::QualifiedWildcard(kind, wildcard_additional_options) => union_spans(
1849                [kind.span()]
1850                    .into_iter()
1851                    .chain(iter::once(wildcard_additional_options.span())),
1852            ),
1853            SelectItem::Wildcard(wildcard_additional_options) => wildcard_additional_options.span(),
1854        }
1855    }
1856}
1857
1858impl Spanned for WildcardAdditionalOptions {
1859    fn span(&self) -> Span {
1860        let WildcardAdditionalOptions {
1861            wildcard_token,
1862            opt_ilike,
1863            opt_exclude,
1864            opt_except,
1865            opt_replace,
1866            opt_rename,
1867            opt_alias,
1868        } = self;
1869
1870        union_spans(
1871            core::iter::once(wildcard_token.0.span)
1872                .chain(opt_ilike.as_ref().map(|i| i.span()))
1873                .chain(opt_exclude.as_ref().map(|i| i.span()))
1874                .chain(opt_rename.as_ref().map(|i| i.span()))
1875                .chain(opt_replace.as_ref().map(|i| i.span()))
1876                .chain(opt_except.as_ref().map(|i| i.span()))
1877                .chain(opt_alias.as_ref().map(|i| i.span)),
1878        )
1879    }
1880}
1881
1882/// # missing span
1883impl Spanned for IlikeSelectItem {
1884    fn span(&self) -> Span {
1885        Span::empty()
1886    }
1887}
1888
1889impl Spanned for ExcludeSelectItem {
1890    fn span(&self) -> Span {
1891        match self {
1892            ExcludeSelectItem::Single(name) => name.span(),
1893            ExcludeSelectItem::Multiple(vec) => union_spans(vec.iter().map(|i| i.span())),
1894        }
1895    }
1896}
1897
1898impl Spanned for RenameSelectItem {
1899    fn span(&self) -> Span {
1900        match self {
1901            RenameSelectItem::Single(ident) => ident.ident.span.union(&ident.alias.span),
1902            RenameSelectItem::Multiple(vec) => {
1903                union_spans(vec.iter().map(|i| i.ident.span.union(&i.alias.span)))
1904            }
1905        }
1906    }
1907}
1908
1909impl Spanned for ExceptSelectItem {
1910    fn span(&self) -> Span {
1911        let ExceptSelectItem {
1912            first_element,
1913            additional_elements,
1914        } = self;
1915
1916        union_spans(
1917            iter::once(first_element.span).chain(additional_elements.iter().map(|i| i.span)),
1918        )
1919    }
1920}
1921
1922impl Spanned for ReplaceSelectItem {
1923    fn span(&self) -> Span {
1924        let ReplaceSelectItem { items } = self;
1925
1926        union_spans(items.iter().map(|i| i.span()))
1927    }
1928}
1929
1930impl Spanned for ReplaceSelectElement {
1931    fn span(&self) -> Span {
1932        let ReplaceSelectElement {
1933            expr,
1934            column_name,
1935            as_keyword: _, // bool
1936        } = self;
1937
1938        expr.span().union(&column_name.span)
1939    }
1940}
1941
1942/// # partial span
1943///
1944/// Missing spans:
1945/// - [TableFactor::JsonTable]
1946impl Spanned for TableFactor {
1947    fn span(&self) -> Span {
1948        match self {
1949            TableFactor::Table {
1950                name,
1951                alias,
1952                args: _,
1953                with_hints: _,
1954                version: _,
1955                with_ordinality: _,
1956                partitions: _,
1957                json_path: _,
1958                sample: _,
1959                index_hints: _,
1960            } => union_spans(
1961                name.0
1962                    .iter()
1963                    .map(|i| i.span())
1964                    .chain(alias.as_ref().map(|alias| {
1965                        union_spans(
1966                            iter::once(alias.name.span)
1967                                .chain(alias.columns.iter().map(|i| i.span())),
1968                        )
1969                    })),
1970            ),
1971            TableFactor::Derived {
1972                lateral: _,
1973                subquery,
1974                alias,
1975                sample: _,
1976            } => subquery
1977                .span()
1978                .union_opt(&alias.as_ref().map(|alias| alias.span())),
1979            TableFactor::TableFunction { expr, alias } => expr
1980                .span()
1981                .union_opt(&alias.as_ref().map(|alias| alias.span())),
1982            TableFactor::UNNEST {
1983                alias,
1984                with_offset: _,
1985                with_offset_alias,
1986                array_exprs,
1987                with_ordinality: _,
1988            } => union_spans(
1989                alias
1990                    .iter()
1991                    .map(|i| i.span())
1992                    .chain(array_exprs.iter().map(|i| i.span()))
1993                    .chain(with_offset_alias.as_ref().map(|i| i.span)),
1994            ),
1995            TableFactor::NestedJoin {
1996                table_with_joins,
1997                alias,
1998            } => table_with_joins
1999                .span()
2000                .union_opt(&alias.as_ref().map(|alias| alias.span())),
2001            TableFactor::Function {
2002                lateral: _,
2003                name,
2004                args,
2005                with_ordinality: _,
2006                alias,
2007            } => union_spans(
2008                name.0
2009                    .iter()
2010                    .map(|i| i.span())
2011                    .chain(args.iter().map(|i| i.span()))
2012                    .chain(alias.as_ref().map(|alias| alias.span())),
2013            ),
2014            TableFactor::JsonTable { .. } => Span::empty(),
2015            TableFactor::XmlTable { .. } => Span::empty(),
2016            TableFactor::Pivot {
2017                table,
2018                aggregate_functions,
2019                value_column,
2020                value_source,
2021                default_on_null,
2022                alias,
2023            } => union_spans(
2024                core::iter::once(table.span())
2025                    .chain(aggregate_functions.iter().map(|i| i.span()))
2026                    .chain(value_column.iter().map(|i| i.span()))
2027                    .chain(core::iter::once(value_source.span()))
2028                    .chain(default_on_null.as_ref().map(|i| i.span()))
2029                    .chain(alias.as_ref().map(|i| i.span())),
2030            ),
2031            TableFactor::Unpivot {
2032                table,
2033                value,
2034                null_inclusion: _,
2035                name,
2036                columns,
2037                alias,
2038            } => union_spans(
2039                core::iter::once(table.span())
2040                    .chain(core::iter::once(value.span()))
2041                    .chain(core::iter::once(name.span))
2042                    .chain(columns.iter().map(|ilist| ilist.span()))
2043                    .chain(alias.as_ref().map(|alias| alias.span())),
2044            ),
2045            TableFactor::MatchRecognize {
2046                table,
2047                partition_by,
2048                order_by,
2049                measures,
2050                rows_per_match: _,
2051                after_match_skip: _,
2052                pattern,
2053                symbols,
2054                alias,
2055            } => union_spans(
2056                core::iter::once(table.span())
2057                    .chain(partition_by.iter().map(|i| i.span()))
2058                    .chain(order_by.iter().map(|i| i.span()))
2059                    .chain(measures.iter().map(|i| i.span()))
2060                    .chain(core::iter::once(pattern.span()))
2061                    .chain(symbols.iter().map(|i| i.span()))
2062                    .chain(alias.as_ref().map(|i| i.span())),
2063            ),
2064            TableFactor::SemanticView {
2065                name,
2066                dimensions,
2067                metrics,
2068                facts,
2069                where_clause,
2070                alias,
2071            } => union_spans(
2072                name.0
2073                    .iter()
2074                    .map(|i| i.span())
2075                    .chain(dimensions.iter().map(|d| d.span()))
2076                    .chain(metrics.iter().map(|m| m.span()))
2077                    .chain(facts.iter().map(|f| f.span()))
2078                    .chain(where_clause.as_ref().map(|e| e.span()))
2079                    .chain(alias.as_ref().map(|a| a.span())),
2080            ),
2081            TableFactor::OpenJsonTable { .. } => Span::empty(),
2082        }
2083    }
2084}
2085
2086impl Spanned for PivotValueSource {
2087    fn span(&self) -> Span {
2088        match self {
2089            PivotValueSource::List(vec) => union_spans(vec.iter().map(|i| i.span())),
2090            PivotValueSource::Any(vec) => union_spans(vec.iter().map(|i| i.span())),
2091            PivotValueSource::Subquery(query) => query.span(),
2092        }
2093    }
2094}
2095
2096impl Spanned for ExprWithAlias {
2097    fn span(&self) -> Span {
2098        let ExprWithAlias { expr, alias } = self;
2099
2100        expr.span().union_opt(&alias.as_ref().map(|i| i.span))
2101    }
2102}
2103
2104/// # missing span
2105impl Spanned for MatchRecognizePattern {
2106    fn span(&self) -> Span {
2107        Span::empty()
2108    }
2109}
2110
2111impl Spanned for SymbolDefinition {
2112    fn span(&self) -> Span {
2113        let SymbolDefinition { symbol, definition } = self;
2114
2115        symbol.span.union(&definition.span())
2116    }
2117}
2118
2119impl Spanned for Measure {
2120    fn span(&self) -> Span {
2121        let Measure { expr, alias } = self;
2122
2123        expr.span().union(&alias.span)
2124    }
2125}
2126
2127impl Spanned for OrderByExpr {
2128    fn span(&self) -> Span {
2129        let OrderByExpr {
2130            expr,
2131            options: _,
2132            with_fill,
2133        } = self;
2134
2135        expr.span().union_opt(&with_fill.as_ref().map(|f| f.span()))
2136    }
2137}
2138
2139impl Spanned for WithFill {
2140    fn span(&self) -> Span {
2141        let WithFill { from, to, step } = self;
2142
2143        union_spans(
2144            from.iter()
2145                .map(|f| f.span())
2146                .chain(to.iter().map(|t| t.span()))
2147                .chain(step.iter().map(|s| s.span())),
2148        )
2149    }
2150}
2151
2152impl Spanned for FunctionArg {
2153    fn span(&self) -> Span {
2154        match self {
2155            FunctionArg::Named {
2156                name,
2157                arg,
2158                operator: _,
2159            } => name.span.union(&arg.span()),
2160            FunctionArg::Unnamed(arg) => arg.span(),
2161            FunctionArg::ExprNamed {
2162                name,
2163                arg,
2164                operator: _,
2165            } => name.span().union(&arg.span()),
2166        }
2167    }
2168}
2169
2170/// # partial span
2171///
2172/// Missing spans:
2173/// - [FunctionArgExpr::Wildcard]
2174/// - [FunctionArgExpr::WildcardWithOptions]
2175impl Spanned for FunctionArgExpr {
2176    fn span(&self) -> Span {
2177        match self {
2178            FunctionArgExpr::Expr(expr) => expr.span(),
2179            FunctionArgExpr::QualifiedWildcard(object_name) => {
2180                union_spans(object_name.0.iter().map(|i| i.span()))
2181            }
2182            FunctionArgExpr::Wildcard => Span::empty(),
2183            FunctionArgExpr::WildcardWithOptions(_) => Span::empty(),
2184        }
2185    }
2186}
2187
2188impl Spanned for TableAlias {
2189    fn span(&self) -> Span {
2190        let TableAlias {
2191            explicit: _,
2192            name,
2193            columns,
2194            at,
2195        } = self;
2196        union_spans(
2197            core::iter::once(name.span)
2198                .chain(columns.iter().map(Spanned::span))
2199                .chain(at.iter().map(|at| at.span)),
2200        )
2201    }
2202}
2203
2204impl Spanned for TableAliasColumnDef {
2205    fn span(&self) -> Span {
2206        let TableAliasColumnDef { name, data_type: _ } = self;
2207
2208        name.span
2209    }
2210}
2211
2212impl Spanned for ValueWithSpan {
2213    fn span(&self) -> Span {
2214        self.span
2215    }
2216}
2217
2218impl Spanned for Join {
2219    fn span(&self) -> Span {
2220        let Join {
2221            relation,
2222            global: _, // bool
2223            join_operator,
2224        } = self;
2225
2226        relation.span().union(&join_operator.span())
2227    }
2228}
2229
2230/// # partial span
2231///
2232/// Missing spans:
2233/// - [JoinOperator::CrossJoin]
2234/// - [JoinOperator::CrossApply]
2235/// - [JoinOperator::OuterApply]
2236impl Spanned for JoinOperator {
2237    fn span(&self) -> Span {
2238        match self {
2239            JoinOperator::Join(join_constraint) => join_constraint.span(),
2240            JoinOperator::Inner(join_constraint) => join_constraint.span(),
2241            JoinOperator::Left(join_constraint) => join_constraint.span(),
2242            JoinOperator::LeftOuter(join_constraint) => join_constraint.span(),
2243            JoinOperator::Right(join_constraint) => join_constraint.span(),
2244            JoinOperator::RightOuter(join_constraint) => join_constraint.span(),
2245            JoinOperator::FullOuter(join_constraint) => join_constraint.span(),
2246            JoinOperator::CrossJoin(join_constraint) => join_constraint.span(),
2247            JoinOperator::LeftSemi(join_constraint) => join_constraint.span(),
2248            JoinOperator::RightSemi(join_constraint) => join_constraint.span(),
2249            JoinOperator::LeftAnti(join_constraint) => join_constraint.span(),
2250            JoinOperator::RightAnti(join_constraint) => join_constraint.span(),
2251            JoinOperator::CrossApply => Span::empty(),
2252            JoinOperator::OuterApply => Span::empty(),
2253            JoinOperator::AsOf {
2254                match_condition,
2255                constraint,
2256            } => match_condition.span().union(&constraint.span()),
2257            JoinOperator::Anti(join_constraint) => join_constraint.span(),
2258            JoinOperator::Semi(join_constraint) => join_constraint.span(),
2259            JoinOperator::StraightJoin(join_constraint) => join_constraint.span(),
2260            JoinOperator::ArrayJoin => Span::empty(),
2261            JoinOperator::LeftArrayJoin => Span::empty(),
2262            JoinOperator::InnerArrayJoin => Span::empty(),
2263        }
2264    }
2265}
2266
2267/// # partial span
2268///
2269/// Missing spans:
2270/// - [JoinConstraint::Natural]
2271/// - [JoinConstraint::None]
2272impl Spanned for JoinConstraint {
2273    fn span(&self) -> Span {
2274        match self {
2275            JoinConstraint::On(expr) => expr.span(),
2276            JoinConstraint::Using(vec) => union_spans(vec.iter().map(|i| i.span())),
2277            JoinConstraint::Natural => Span::empty(),
2278            JoinConstraint::None => Span::empty(),
2279        }
2280    }
2281}
2282
2283impl Spanned for TableWithJoins {
2284    fn span(&self) -> Span {
2285        let TableWithJoins { relation, joins } = self;
2286
2287        union_spans(core::iter::once(relation.span()).chain(joins.iter().map(|item| item.span())))
2288    }
2289}
2290
2291impl Spanned for Select {
2292    fn span(&self) -> Span {
2293        let Select {
2294            select_token,
2295            optimizer_hints: _,
2296            distinct: _, // todo
2297            select_modifiers: _,
2298            top: _, // todo, mysql specific
2299            projection,
2300            exclude: _,
2301            into,
2302            from,
2303            lateral_views,
2304            prewhere,
2305            selection,
2306            group_by,
2307            cluster_by,
2308            distribute_by,
2309            sort_by,
2310            having,
2311            named_window,
2312            qualify,
2313            window_before_qualify: _, // bool
2314            value_table_mode: _,      // todo, BigQuery specific
2315            connect_by,
2316            top_before_distinct: _,
2317            flavor: _,
2318        } = self;
2319
2320        union_spans(
2321            core::iter::once(select_token.0.span)
2322                .chain(projection.iter().map(|item| item.span()))
2323                .chain(into.iter().map(|item| item.span()))
2324                .chain(from.iter().map(|item| item.span()))
2325                .chain(lateral_views.iter().map(|item| item.span()))
2326                .chain(prewhere.iter().map(|item| item.span()))
2327                .chain(selection.iter().map(|item| item.span()))
2328                .chain(connect_by.iter().map(|item| item.span()))
2329                .chain(core::iter::once(group_by.span()))
2330                .chain(cluster_by.iter().map(|item| item.span()))
2331                .chain(distribute_by.iter().map(|item| item.span()))
2332                .chain(sort_by.iter().map(|item| item.span()))
2333                .chain(having.iter().map(|item| item.span()))
2334                .chain(named_window.iter().map(|item| item.span()))
2335                .chain(qualify.iter().map(|item| item.span())),
2336        )
2337    }
2338}
2339
2340impl Spanned for ConnectByKind {
2341    fn span(&self) -> Span {
2342        match self {
2343            ConnectByKind::ConnectBy {
2344                connect_token,
2345                nocycle: _,
2346                relationships,
2347            } => union_spans(
2348                core::iter::once(connect_token.0.span())
2349                    .chain(relationships.last().iter().map(|item| item.span())),
2350            ),
2351            ConnectByKind::StartWith {
2352                start_token,
2353                condition,
2354            } => union_spans([start_token.0.span(), condition.span()].into_iter()),
2355        }
2356    }
2357}
2358
2359impl Spanned for NamedWindowDefinition {
2360    fn span(&self) -> Span {
2361        let NamedWindowDefinition(
2362            ident,
2363            _, // todo: NamedWindowExpr
2364        ) = self;
2365
2366        ident.span
2367    }
2368}
2369
2370impl Spanned for LateralView {
2371    fn span(&self) -> Span {
2372        let LateralView {
2373            lateral_view,
2374            lateral_view_name,
2375            lateral_col_alias,
2376            outer: _, // bool
2377        } = self;
2378
2379        union_spans(
2380            core::iter::once(lateral_view.span())
2381                .chain(core::iter::once(lateral_view_name.span()))
2382                .chain(lateral_col_alias.iter().map(|i| i.span)),
2383        )
2384    }
2385}
2386
2387impl Spanned for SelectInto {
2388    fn span(&self) -> Span {
2389        let SelectInto {
2390            temporary: _, // bool
2391            unlogged: _,  // bool
2392            table: _,     // bool
2393            name,
2394        } = self;
2395
2396        name.span()
2397    }
2398}
2399
2400impl Spanned for UpdateTableFromKind {
2401    fn span(&self) -> Span {
2402        let from = match self {
2403            UpdateTableFromKind::BeforeSet(from) => from,
2404            UpdateTableFromKind::AfterSet(from) => from,
2405        };
2406        union_spans(from.iter().map(|t| t.span()))
2407    }
2408}
2409
2410impl Spanned for TableObject {
2411    fn span(&self) -> Span {
2412        match self {
2413            TableObject::TableName(ObjectName(segments)) => {
2414                union_spans(segments.iter().map(|i| i.span()))
2415            }
2416            TableObject::TableFunction(func) => func.span(),
2417            TableObject::TableQuery(query) => query.span(),
2418        }
2419    }
2420}
2421
2422impl Spanned for BeginEndStatements {
2423    fn span(&self) -> Span {
2424        let BeginEndStatements {
2425            begin_token,
2426            statements,
2427            end_token,
2428        } = self;
2429        union_spans(
2430            core::iter::once(begin_token.0.span)
2431                .chain(statements.iter().map(|i| i.span()))
2432                .chain(core::iter::once(end_token.0.span)),
2433        )
2434    }
2435}
2436
2437impl Spanned for OpenStatement {
2438    fn span(&self) -> Span {
2439        let OpenStatement { cursor_name } = self;
2440        cursor_name.span
2441    }
2442}
2443
2444impl Spanned for AlterSchemaOperation {
2445    fn span(&self) -> Span {
2446        match self {
2447            AlterSchemaOperation::SetDefaultCollate { collate } => collate.span(),
2448            AlterSchemaOperation::AddReplica { replica, options } => union_spans(
2449                core::iter::once(replica.span)
2450                    .chain(options.iter().flat_map(|i| i.iter().map(|i| i.span()))),
2451            ),
2452            AlterSchemaOperation::DropReplica { replica } => replica.span,
2453            AlterSchemaOperation::SetOptionsParens { options } => {
2454                union_spans(options.iter().map(|i| i.span()))
2455            }
2456            AlterSchemaOperation::Rename { name } => name.span(),
2457            AlterSchemaOperation::OwnerTo { owner } => {
2458                if let Owner::Ident(ident) = owner {
2459                    ident.span
2460                } else {
2461                    Span::empty()
2462                }
2463            }
2464        }
2465    }
2466}
2467
2468impl Spanned for AlterSchema {
2469    fn span(&self) -> Span {
2470        union_spans(
2471            core::iter::once(self.name.span()).chain(self.operations.iter().map(|i| i.span())),
2472        )
2473    }
2474}
2475
2476impl Spanned for CreateView {
2477    fn span(&self) -> Span {
2478        union_spans(
2479            core::iter::once(self.name.span())
2480                .chain(self.columns.iter().map(|i| i.span()))
2481                .chain(core::iter::once(self.query.span()))
2482                .chain(core::iter::once(self.options.span()))
2483                .chain(self.cluster_by.iter().map(|i| i.span))
2484                .chain(self.to.iter().map(|i| i.span())),
2485        )
2486    }
2487}
2488
2489impl Spanned for AlterTable {
2490    fn span(&self) -> Span {
2491        union_spans(
2492            core::iter::once(self.name.span())
2493                .chain(self.operations.iter().map(|i| i.span()))
2494                .chain(self.on_cluster.iter().map(|i| i.span))
2495                .chain(core::iter::once(self.end_token.0.span)),
2496        )
2497    }
2498}
2499
2500impl Spanned for CreateOperator {
2501    fn span(&self) -> Span {
2502        Span::empty()
2503    }
2504}
2505
2506impl Spanned for CreateOperatorFamily {
2507    fn span(&self) -> Span {
2508        Span::empty()
2509    }
2510}
2511
2512impl Spanned for CreateOperatorClass {
2513    fn span(&self) -> Span {
2514        Span::empty()
2515    }
2516}
2517
2518impl Spanned for MergeClause {
2519    fn span(&self) -> Span {
2520        union_spans([self.when_token.0.span, self.action.span()].into_iter())
2521    }
2522}
2523
2524impl Spanned for MergeAction {
2525    fn span(&self) -> Span {
2526        match self {
2527            MergeAction::Insert(expr) => expr.span(),
2528            MergeAction::Update(expr) => expr.span(),
2529            MergeAction::Delete { delete_token } => delete_token.0.span,
2530        }
2531    }
2532}
2533
2534impl Spanned for MergeInsertExpr {
2535    fn span(&self) -> Span {
2536        union_spans(
2537            [
2538                self.insert_token.0.span,
2539                self.kind_token.0.span,
2540                match self.kind {
2541                    MergeInsertKind::Values(ref values) => values.span(),
2542                    MergeInsertKind::Row | MergeInsertKind::Wildcard => Span::empty(),
2543                },
2544            ]
2545            .into_iter()
2546            .chain(self.insert_predicate.iter().map(Spanned::span))
2547            .chain(self.columns.iter().map(|i| i.span())),
2548        )
2549    }
2550}
2551
2552impl Spanned for MergeUpdateExpr {
2553    fn span(&self) -> Span {
2554        let kind_span = match &self.kind {
2555            MergeUpdateKind::Set(assignments) => union_spans(assignments.iter().map(Spanned::span)),
2556            MergeUpdateKind::Wildcard => Span::empty(),
2557        };
2558        union_spans(
2559            core::iter::once(self.update_token.0.span)
2560                .chain(core::iter::once(kind_span))
2561                .chain(self.update_predicate.iter().map(Spanned::span))
2562                .chain(self.delete_predicate.iter().map(Spanned::span)),
2563        )
2564    }
2565}
2566
2567impl Spanned for OutputClause {
2568    fn span(&self) -> Span {
2569        match self {
2570            OutputClause::Output {
2571                output_token,
2572                select_items,
2573                into_table,
2574            } => union_spans(
2575                core::iter::once(output_token.0.span)
2576                    .chain(into_table.iter().map(Spanned::span))
2577                    .chain(select_items.iter().map(Spanned::span)),
2578            ),
2579            OutputClause::Returning {
2580                returning_token,
2581                select_items,
2582            } => union_spans(
2583                core::iter::once(returning_token.0.span)
2584                    .chain(select_items.iter().map(Spanned::span)),
2585            ),
2586        }
2587    }
2588}
2589
2590impl Spanned for comments::CommentWithSpan {
2591    fn span(&self) -> Span {
2592        self.span
2593    }
2594}
2595
2596#[cfg(test)]
2597pub mod tests {
2598    use crate::ast::Value;
2599    use crate::dialect::{Dialect, GenericDialect, SnowflakeDialect};
2600    use crate::parser::Parser;
2601    use crate::tokenizer::{Location, Span};
2602
2603    use super::*;
2604
2605    struct SpanTest<'a>(Parser<'a>, &'a str);
2606
2607    impl<'a> SpanTest<'a> {
2608        fn new(dialect: &'a dyn Dialect, sql: &'a str) -> Self {
2609            Self(Parser::new(dialect).try_with_sql(sql).unwrap(), sql)
2610        }
2611
2612        // get the subsection of the source string that corresponds to the span
2613        // only works on single-line strings
2614        fn get_source(&self, span: Span) -> &'a str {
2615            // lines in spans are 1-indexed
2616            &self.1[(span.start.column as usize - 1)..(span.end.column - 1) as usize]
2617        }
2618    }
2619
2620    #[test]
2621    fn test_join() {
2622        let dialect = &GenericDialect;
2623        let mut test = SpanTest::new(
2624            dialect,
2625            "SELECT id, name FROM users LEFT JOIN companies ON users.company_id = companies.id",
2626        );
2627
2628        let query = test.0.parse_select().unwrap();
2629        let select_span = query.span();
2630
2631        assert_eq!(
2632            test.get_source(select_span),
2633            "SELECT id, name FROM users LEFT JOIN companies ON users.company_id = companies.id"
2634        );
2635
2636        let join_span = query.from[0].joins[0].span();
2637
2638        // 'LEFT JOIN' missing
2639        assert_eq!(
2640            test.get_source(join_span),
2641            "companies ON users.company_id = companies.id"
2642        );
2643    }
2644
2645    #[test]
2646    pub fn test_union() {
2647        let dialect = &GenericDialect;
2648        let mut test = SpanTest::new(
2649            dialect,
2650            "SELECT a FROM postgres.public.source UNION SELECT a FROM postgres.public.source",
2651        );
2652
2653        let query = test.0.parse_query().unwrap();
2654        let select_span = query.span();
2655
2656        assert_eq!(
2657            test.get_source(select_span),
2658            "SELECT a FROM postgres.public.source UNION SELECT a FROM postgres.public.source"
2659        );
2660    }
2661
2662    #[test]
2663    pub fn test_subquery() {
2664        let dialect = &GenericDialect;
2665        let mut test = SpanTest::new(
2666            dialect,
2667            "SELECT a FROM (SELECT a FROM postgres.public.source) AS b",
2668        );
2669
2670        let query = test.0.parse_select().unwrap();
2671        let select_span = query.span();
2672
2673        assert_eq!(
2674            test.get_source(select_span),
2675            "SELECT a FROM (SELECT a FROM postgres.public.source) AS b"
2676        );
2677
2678        let subquery_span = query.from[0].span();
2679
2680        // left paren missing
2681        assert_eq!(
2682            test.get_source(subquery_span),
2683            "SELECT a FROM postgres.public.source) AS b"
2684        );
2685    }
2686
2687    #[test]
2688    pub fn test_cte() {
2689        let dialect = &GenericDialect;
2690        let mut test = SpanTest::new(dialect, "WITH cte_outer AS (SELECT a FROM postgres.public.source), cte_ignored AS (SELECT a FROM cte_outer), cte_inner AS (SELECT a FROM cte_outer) SELECT a FROM cte_inner");
2691
2692        let query = test.0.parse_query().unwrap();
2693
2694        let select_span = query.span();
2695
2696        assert_eq!(test.get_source(select_span), "WITH cte_outer AS (SELECT a FROM postgres.public.source), cte_ignored AS (SELECT a FROM cte_outer), cte_inner AS (SELECT a FROM cte_outer) SELECT a FROM cte_inner");
2697    }
2698
2699    #[test]
2700    pub fn test_snowflake_lateral_flatten() {
2701        let dialect = &SnowflakeDialect;
2702        let mut test = SpanTest::new(dialect, "SELECT FLATTENED.VALUE:field::TEXT AS FIELD FROM SNOWFLAKE.SCHEMA.SOURCE AS S, LATERAL FLATTEN(INPUT => S.JSON_ARRAY) AS FLATTENED");
2703
2704        let query = test.0.parse_select().unwrap();
2705
2706        let select_span = query.span();
2707
2708        assert_eq!(test.get_source(select_span), "SELECT FLATTENED.VALUE:field::TEXT AS FIELD FROM SNOWFLAKE.SCHEMA.SOURCE AS S, LATERAL FLATTEN(INPUT => S.JSON_ARRAY) AS FLATTENED");
2709    }
2710
2711    #[test]
2712    pub fn test_wildcard_from_cte() {
2713        let dialect = &GenericDialect;
2714        let mut test = SpanTest::new(
2715            dialect,
2716            "WITH cte AS (SELECT a FROM postgres.public.source) SELECT cte.* FROM cte",
2717        );
2718
2719        let query = test.0.parse_query().unwrap();
2720        let cte_span = query.clone().with.unwrap().cte_tables[0].span();
2721        let cte_query_span = query.clone().with.unwrap().cte_tables[0].query.span();
2722        let body_span = query.body.span();
2723
2724        // the WITH keyboard is part of the query
2725        assert_eq!(
2726            test.get_source(cte_span),
2727            "cte AS (SELECT a FROM postgres.public.source)"
2728        );
2729        assert_eq!(
2730            test.get_source(cte_query_span),
2731            "SELECT a FROM postgres.public.source"
2732        );
2733
2734        assert_eq!(test.get_source(body_span), "SELECT cte.* FROM cte");
2735    }
2736
2737    #[test]
2738    fn test_case_expr_span() {
2739        let dialect = &GenericDialect;
2740        let mut test = SpanTest::new(dialect, "CASE 1 WHEN 2 THEN 3 ELSE 4 END");
2741        let expr = test.0.parse_expr().unwrap();
2742        let expr_span = expr.span();
2743        assert_eq!(
2744            test.get_source(expr_span),
2745            "CASE 1 WHEN 2 THEN 3 ELSE 4 END"
2746        );
2747    }
2748
2749    #[test]
2750    fn test_placeholder_span() {
2751        let sql = "\nSELECT\n  :fooBar";
2752        let r = Parser::parse_sql(&GenericDialect, sql).unwrap();
2753        assert_eq!(1, r.len());
2754        match &r[0] {
2755            Statement::Query(q) => {
2756                let col = &q.body.as_select().unwrap().projection[0];
2757                match col {
2758                    SelectItem::UnnamedExpr(Expr::Value(ValueWithSpan {
2759                        value: Value::Placeholder(s),
2760                        span,
2761                    })) => {
2762                        assert_eq!(":fooBar", s);
2763                        assert_eq!(&Span::new((3, 3).into(), (3, 10).into()), span);
2764                    }
2765                    _ => panic!("expected unnamed expression; got {col:?}"),
2766                }
2767            }
2768            stmt => panic!("expected query; got {stmt:?}"),
2769        }
2770    }
2771
2772    #[test]
2773    fn test_alter_table_multiline_span() {
2774        let sql = r#"-- foo
2775ALTER TABLE users
2776  ADD COLUMN foo
2777  varchar; -- hi there"#;
2778
2779        let r = Parser::parse_sql(&crate::dialect::PostgreSqlDialect {}, sql).unwrap();
2780        assert_eq!(1, r.len());
2781
2782        let stmt_span = r[0].span();
2783
2784        assert_eq!(stmt_span.start, (2, 13).into());
2785        assert_eq!(stmt_span.end, (4, 11).into());
2786    }
2787
2788    #[test]
2789    fn test_update_statement_span() {
2790        let sql = r#"-- foo
2791      UPDATE foo
2792   /* bar */
2793   SET bar = 3
2794 WHERE quux > 42 ;
2795"#;
2796
2797        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
2798        assert_eq!(1, r.len());
2799
2800        let stmt_span = r[0].span();
2801
2802        assert_eq!(stmt_span.start, (2, 7).into());
2803        assert_eq!(stmt_span.end, (5, 17).into());
2804    }
2805
2806    #[test]
2807    fn test_insert_statement_span() {
2808        let sql = r#"
2809/* foo */ INSERT  INTO  FOO  (X, Y, Z)
2810  SELECT 1, 2, 3
2811  FROM DUAL
2812;"#;
2813
2814        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
2815        assert_eq!(1, r.len());
2816
2817        let stmt_span = r[0].span();
2818
2819        assert_eq!(stmt_span.start, (2, 11).into());
2820        assert_eq!(stmt_span.end, (4, 12).into());
2821    }
2822
2823    #[test]
2824    fn test_replace_statement_span() {
2825        let sql = r#"
2826/* foo */ REPLACE INTO
2827    cities(name,population)
2828SELECT
2829    name,
2830    population
2831FROM
2832   cities
2833WHERE id = 1
2834;"#;
2835
2836        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
2837        assert_eq!(1, r.len());
2838
2839        dbg!(&r[0]);
2840
2841        let stmt_span = r[0].span();
2842
2843        assert_eq!(stmt_span.start, (2, 11).into());
2844        assert_eq!(stmt_span.end, (9, 13).into());
2845    }
2846
2847    #[test]
2848    fn test_delete_statement_span() {
2849        let sql = r#"-- foo
2850      DELETE /* quux */
2851        FROM foo
2852       WHERE foo.x = 42
2853;"#;
2854
2855        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
2856        assert_eq!(1, r.len());
2857
2858        let stmt_span = r[0].span();
2859
2860        assert_eq!(stmt_span.start, (2, 7).into());
2861        assert_eq!(stmt_span.end, (4, 24).into());
2862    }
2863
2864    #[test]
2865    fn test_merge_statement_spans() {
2866        let sql = r#"
2867        -- plain merge statement; no RETURNING, no OUTPUT
2868
2869        MERGE INTO target_table USING source_table
2870                ON target_table.id = source_table.oooid
2871
2872        /* an inline comment */ WHEN NOT MATCHED THEN
2873            INSERT (ID, description)
2874               VALUES (source_table.id, source_table.description)
2875
2876            -- another one
2877                WHEN MATCHED AND target_table.x = 'X' THEN
2878            UPDATE SET target_table.description = source_table.description
2879
2880              WHEN MATCHED AND target_table.x != 'X' THEN   DELETE
2881        WHEN NOT MATCHED AND 1 THEN INSERT (product, quantity) ROW
2882        "#;
2883
2884        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
2885        assert_eq!(1, r.len());
2886
2887        // ~ assert the span of the whole statement
2888        let stmt_span = r[0].span();
2889        assert_eq!(stmt_span.start, (4, 9).into());
2890        assert_eq!(stmt_span.end, (16, 67).into());
2891
2892        // ~ individual tokens within the statement
2893        let Statement::Merge(Merge {
2894            merge_token,
2895            optimizer_hints: _,
2896            into: _,
2897            table: _,
2898            source: _,
2899            on: _,
2900            clauses,
2901            output,
2902        }) = &r[0]
2903        else {
2904            panic!("not a MERGE statement");
2905        };
2906        assert_eq!(
2907            merge_token.0.span,
2908            Span::new(Location::new(4, 9), Location::new(4, 14))
2909        );
2910        assert_eq!(clauses.len(), 4);
2911
2912        // ~ the INSERT clause's TOKENs
2913        assert_eq!(
2914            clauses[0].when_token.0.span,
2915            Span::new(Location::new(7, 33), Location::new(7, 37))
2916        );
2917        if let MergeAction::Insert(MergeInsertExpr {
2918            insert_token,
2919            kind_token,
2920            ..
2921        }) = &clauses[0].action
2922        {
2923            assert_eq!(
2924                insert_token.0.span,
2925                Span::new(Location::new(8, 13), Location::new(8, 19))
2926            );
2927            assert_eq!(
2928                kind_token.0.span,
2929                Span::new(Location::new(9, 16), Location::new(9, 22))
2930            );
2931        } else {
2932            panic!("not a MERGE INSERT clause");
2933        }
2934
2935        // ~ the UPDATE token(s)
2936        assert_eq!(
2937            clauses[1].when_token.0.span,
2938            Span::new(Location::new(12, 17), Location::new(12, 21))
2939        );
2940        if let MergeAction::Update(MergeUpdateExpr {
2941            update_token,
2942            kind: _,
2943            update_predicate: _,
2944            delete_predicate: _,
2945        }) = &clauses[1].action
2946        {
2947            assert_eq!(
2948                update_token.0.span,
2949                Span::new(Location::new(13, 13), Location::new(13, 19))
2950            );
2951        } else {
2952            panic!("not a MERGE UPDATE clause");
2953        }
2954
2955        // the DELETE token(s)
2956        assert_eq!(
2957            clauses[2].when_token.0.span,
2958            Span::new(Location::new(15, 15), Location::new(15, 19))
2959        );
2960        if let MergeAction::Delete { delete_token } = &clauses[2].action {
2961            assert_eq!(
2962                delete_token.0.span,
2963                Span::new(Location::new(15, 61), Location::new(15, 67))
2964            );
2965        } else {
2966            panic!("not a MERGE DELETE clause");
2967        }
2968
2969        // ~ an INSERT clause's ROW token
2970        assert_eq!(
2971            clauses[3].when_token.0.span,
2972            Span::new(Location::new(16, 9), Location::new(16, 13))
2973        );
2974        if let MergeAction::Insert(MergeInsertExpr {
2975            insert_token,
2976            kind_token,
2977            ..
2978        }) = &clauses[3].action
2979        {
2980            assert_eq!(
2981                insert_token.0.span,
2982                Span::new(Location::new(16, 37), Location::new(16, 43))
2983            );
2984            assert_eq!(
2985                kind_token.0.span,
2986                Span::new(Location::new(16, 64), Location::new(16, 67))
2987            );
2988        } else {
2989            panic!("not a MERGE INSERT clause");
2990        }
2991
2992        assert!(output.is_none());
2993    }
2994
2995    #[test]
2996    fn test_merge_statement_spans_with_returning() {
2997        let sql = r#"
2998    MERGE INTO wines AS w
2999    USING wine_stock_changes AS s
3000        ON s.winename = w.winename
3001    WHEN NOT MATCHED AND s.stock_delta > 0 THEN INSERT VALUES (s.winename, s.stock_delta)
3002    WHEN MATCHED AND w.stock + s.stock_delta > 0 THEN UPDATE SET stock = w.stock + s.stock_delta
3003    WHEN MATCHED THEN DELETE
3004    RETURNING merge_action(), w.*
3005        "#;
3006
3007        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
3008        assert_eq!(1, r.len());
3009
3010        // ~ assert the span of the whole statement
3011        let stmt_span = r[0].span();
3012        assert_eq!(
3013            stmt_span,
3014            Span::new(Location::new(2, 5), Location::new(8, 34))
3015        );
3016
3017        // ~ individual tokens within the statement
3018        if let Statement::Merge(Merge { output, .. }) = &r[0] {
3019            if let Some(OutputClause::Returning {
3020                returning_token, ..
3021            }) = output
3022            {
3023                assert_eq!(
3024                    returning_token.0.span,
3025                    Span::new(Location::new(8, 5), Location::new(8, 14))
3026                );
3027            } else {
3028                panic!("unexpected MERGE output clause");
3029            }
3030        } else {
3031            panic!("not a MERGE statement");
3032        };
3033    }
3034
3035    #[test]
3036    fn test_merge_statement_spans_with_output() {
3037        let sql = r#"MERGE INTO a USING b ON a.id = b.id
3038        WHEN MATCHED THEN DELETE
3039              OUTPUT inserted.*"#;
3040
3041        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
3042        assert_eq!(1, r.len());
3043
3044        // ~ assert the span of the whole statement
3045        let stmt_span = r[0].span();
3046        assert_eq!(
3047            stmt_span,
3048            Span::new(Location::new(1, 1), Location::new(3, 32))
3049        );
3050
3051        // ~ individual tokens within the statement
3052        if let Statement::Merge(Merge { output, .. }) = &r[0] {
3053            if let Some(OutputClause::Output { output_token, .. }) = output {
3054                assert_eq!(
3055                    output_token.0.span,
3056                    Span::new(Location::new(3, 15), Location::new(3, 21))
3057                );
3058            } else {
3059                panic!("unexpected MERGE output clause");
3060            }
3061        } else {
3062            panic!("not a MERGE statement");
3063        };
3064    }
3065
3066    #[test]
3067    fn test_merge_statement_spans_with_update_predicates() {
3068        let sql = r#"
3069       MERGE INTO a USING b ON a.id = b.id
3070        WHEN MATCHED THEN
3071              UPDATE set a.x = a.x + b.x
3072               WHERE b.x != 2
3073              DELETE WHERE a.x <> 3"#;
3074
3075        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
3076        assert_eq!(1, r.len());
3077
3078        // ~ assert the span of the whole statement
3079        let stmt_span = r[0].span();
3080        assert_eq!(
3081            stmt_span,
3082            Span::new(Location::new(2, 8), Location::new(6, 36))
3083        );
3084    }
3085
3086    #[test]
3087    fn test_merge_statement_spans_with_insert_predicate() {
3088        let sql = r#"
3089       MERGE INTO a USING b ON a.id = b.id
3090        WHEN NOT MATCHED THEN
3091            INSERT VALUES (b.x, b.y) WHERE b.x != 2
3092-- qed
3093"#;
3094
3095        let r = Parser::parse_sql(&crate::dialect::GenericDialect, sql).unwrap();
3096        assert_eq!(1, r.len());
3097
3098        // ~ assert the span of the whole statement
3099        let stmt_span = r[0].span();
3100        assert_eq!(
3101            stmt_span,
3102            Span::new(Location::new(2, 8), Location::new(4, 52))
3103        );
3104    }
3105}