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