sqlx_models_parser/ast/statement/
display.rs

1use super::*;
2
3impl fmt::Display for Statement {
4    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
5        use Statement::*;
6        match self {
7            Analyze(x) => write!(f, "{}", x),
8            Truncate(x) => write!(f, "{}", x),
9            Explain(x) => write!(f, "{}", x),
10            Query(x) => write!(f, "{}", x),
11            Msck(x) => write!(f, "{}", x),
12            Insert(x) => write!(f, "{}", x),
13            Directory(x) => write!(f, "{}", x),
14            Copy(x) => write!(f, "{}", x),
15            Update(x) => write!(f, "{}", x),
16            Delete(x) => write!(f, "{}", x),
17            CreateView(x) => write!(f, "{}", x),
18            CreateTable(x) => write!(f, "{}", x),
19            CreateVirtualTable(x) => write!(f, "{}", x),
20            CreateIndex(x) => write!(f, "{}", x),
21            AlterTable(x) => write!(f, "{}", x),
22            SetVariable(x) => write!(f, "{}", x),
23            ShowVariable(x) => write!(f, "{}", x),
24            ShowCreate(x) => write!(f, "{}", x),
25            ShowColumns(x) => write!(f, "{}", x),
26            StartTransaction(x) => write!(f, "{}", x),
27            SetTransaction(x) => write!(f, "{}", x),
28            Rollback(x) => write!(f, "{}", x),
29            Drop(x) => write!(f, "{}", x),
30            Commit(x) => write!(f, "{}", x),
31            CreateSchema(x) => write!(f, "{}", x),
32            CreateDatabase(x) => write!(f, "{}", x),
33            Assert(x) => write!(f, "{}", x),
34            Deallocate(x) => write!(f, "{}", x),
35            Execute(x) => write!(f, "{}", x),
36            Prepare(x) => write!(f, "{}", x),
37        }
38    }
39}
40impl fmt::Display for Explain {
41    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42        write!(f, "EXPLAIN ")?;
43
44        if self.analyze {
45            write!(f, "ANALYZE ")?;
46        }
47
48        if self.verbose {
49            write!(f, "VERBOSE ")?;
50        }
51
52        write!(f, "{}", self.statement)
53    }
54}
55
56impl fmt::Display for Directory {
57    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58        write!(
59            f,
60            "INSERT{overwrite}{local} DIRECTORY '{path}'",
61            overwrite = if self.overwrite { " OVERWRITE" } else { "" },
62            local = if self.local { " LOCAL" } else { "" },
63            path = self.path
64        )?;
65        if let Some(ref ff) = self.file_format {
66            write!(f, " STORED AS {}", ff)?
67        }
68        write!(f, " {}", self.source)
69    }
70}
71
72impl fmt::Display for Msck {
73    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74        write!(
75            f,
76            "MSCK {repair}TABLE {table}",
77            repair = if self.repair { "REPAIR " } else { "" },
78            table = self.table_name
79        )?;
80        if let Some(ref pa) = self.partition_action {
81            write!(f, " {}", pa)?;
82        }
83        Ok(())
84    }
85}
86
87impl fmt::Display for Truncate {
88    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
89        write!(f, "TRUNCATE TABLE {}", self.table_name)?;
90        if let Some(ref parts) = self.partitions {
91            if !parts.is_empty() {
92                write!(f, " PARTITION ({})", display_comma_separated(parts))?;
93            }
94        }
95        Ok(())
96    }
97}
98
99impl fmt::Display for Analyze {
100    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101        write!(f, "ANALYZE TABLE {}", self.table_name)?;
102        if let Some(ref parts) = self.partitions {
103            if !parts.is_empty() {
104                write!(f, " PARTITION ({})", display_comma_separated(parts))?;
105            }
106        }
107
108        if self.compute_statistics {
109            write!(f, " COMPUTE STATISTICS")?;
110        }
111        if self.noscan {
112            write!(f, " NOSCAN")?;
113        }
114        if self.cache_metadata {
115            write!(f, " CACHE METADATA")?;
116        }
117        if self.for_columns {
118            write!(f, " FOR COLUMNS")?;
119            if !self.columns.is_empty() {
120                write!(f, " {}", display_comma_separated(&self.columns))?;
121            }
122        }
123        Ok(())
124    }
125}
126
127impl fmt::Display for Insert {
128    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129        if let Some(action) = &self.or {
130            write!(f, "INSERT OR {} INTO {} ", action, self.table_name)?;
131        } else {
132            write!(
133                f,
134                "INSERT {act}{tbl} {table_name} ",
135                table_name = self.table_name,
136                act = if self.overwrite { "OVERWRITE" } else { "INTO" },
137                tbl = if self.table { " TABLE" } else { "" }
138            )?;
139        }
140        if !self.columns.is_empty() {
141            write!(f, "({}) ", display_comma_separated(&self.columns))?;
142        }
143        if let Some(ref parts) = self.partitioned {
144            if !parts.is_empty() {
145                write!(f, "PARTITION ({}) ", display_comma_separated(parts))?;
146            }
147        }
148        if !self.after_columns.is_empty() {
149            write!(f, "({}) ", display_comma_separated(&self.after_columns))?;
150        }
151        write!(f, "{}", self.source)
152    }
153}
154
155impl fmt::Display for Copy {
156    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157        write!(f, "COPY {}", self.table_name)?;
158        if !self.columns.is_empty() {
159            write!(f, " ({})", display_comma_separated(&self.columns))?;
160        }
161        write!(f, " FROM stdin; ")?;
162        if !self.values.is_empty() {
163            writeln!(f)?;
164            let mut delim = "";
165            for v in &self.values {
166                write!(f, "{}", delim)?;
167                delim = "\t";
168                if let Some(v) = v {
169                    write!(f, "{}", v)?;
170                } else {
171                    write!(f, "\\N")?;
172                }
173            }
174        }
175        write!(f, "\n\\.")
176    }
177}
178
179impl fmt::Display for Update {
180    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
181        write!(f, "UPDATE {}", self.table_name)?;
182        if !self.assignments.is_empty() {
183            write!(f, " SET {}", display_comma_separated(&self.assignments))?;
184        }
185        if let Some(ref selection) = self.selection {
186            write!(f, " WHERE {}", selection)?;
187        }
188        Ok(())
189    }
190}
191
192impl fmt::Display for Delete {
193    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
194        write!(f, "DELETE FROM {}", self.table_name)?;
195        if let Some(ref selection) = self.selection {
196            write!(f, " WHERE {}", selection)?;
197        }
198        Ok(())
199    }
200}
201
202impl fmt::Display for CreateDatabase {
203    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
204        write!(f, "CREATE")?;
205        if self.if_not_exists {
206            write!(f, " IF NOT EXISTS")?;
207        }
208        write!(f, " {}", self.db_name)?;
209        if let Some(ref l) = self.location {
210            write!(f, " LOCATION '{}'", l)?;
211        }
212        if let Some(ref ml) = self.managed_location {
213            write!(f, " MANAGEDLOCATION '{}'", ml)?;
214        }
215        Ok(())
216    }
217}
218
219impl fmt::Display for CreateView {
220    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
221        write!(
222            f,
223            "CREATE {or_replace}{materialized}VIEW {name}",
224            or_replace = if self.or_replace { "OR REPLACE " } else { "" },
225            materialized = if self.materialized {
226                "MATERIALIZED "
227            } else {
228                ""
229            },
230            name = self.name
231        )?;
232        if !self.with_options.is_empty() {
233            write!(f, " WITH ({})", display_comma_separated(&self.with_options))?;
234        }
235        if !self.columns.is_empty() {
236            write!(f, " ({})", display_comma_separated(&self.columns))?;
237        }
238        write!(f, " AS {}", self.query)
239    }
240}
241
242impl fmt::Display for CreateTable {
243    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244        let name = &self.name;
245        let columns = &self.columns;
246        let constraints = &self.constraints;
247        let table_properties = &self.table_properties;
248        let with_options = &self.with_options;
249        let or_replace = &self.or_replace;
250        let if_not_exists = &self.if_not_exists;
251        let hive_distribution = &self.hive_distribution;
252        let hive_formats = &self.hive_formats;
253        let external = &self.external;
254        let temporary = &self.temporary;
255        let file_format = &self.file_format;
256        let location = &self.location;
257        let query = &self.query;
258        let without_rowid = &self.without_rowid;
259        let like = &self.like;
260        write!(
261            f,
262            "CREATE {or_replace}{external}{temporary}TABLE {if_not_exists}{name}",
263            or_replace = if *or_replace { "OR REPLACE " } else { "" },
264            external = if *external { "EXTERNAL " } else { "" },
265            if_not_exists = if *if_not_exists { "IF NOT EXISTS " } else { "" },
266            temporary = if *temporary { "TEMPORARY " } else { "" },
267            name = name,
268        )?;
269        if !columns.is_empty() || !constraints.is_empty() {
270            write!(f, " ({}", display_comma_separated(columns))?;
271            if !columns.is_empty() && !constraints.is_empty() {
272                write!(f, ", ")?;
273            }
274            write!(f, "{})", display_comma_separated(constraints))?;
275        } else if query.is_none() && like.is_none() {
276            // PostgreSQL allows `CREATE TABLE t ();`, but requires empty parens
277            write!(f, " ()")?;
278        }
279        // Only for SQLite
280        if *without_rowid {
281            write!(f, " WITHOUT ROWID")?;
282        }
283
284        // Only for Hive
285        if let Some(l) = like {
286            write!(f, " LIKE {}", l)?;
287        }
288        match hive_distribution {
289            HiveDistributionStyle::PARTITIONED { columns } => {
290                write!(f, " PARTITIONED BY ({})", display_comma_separated(columns))?;
291            }
292            HiveDistributionStyle::CLUSTERED {
293                columns,
294                sorted_by,
295                num_buckets,
296            } => {
297                write!(f, " CLUSTERED BY ({})", display_comma_separated(columns))?;
298                if !sorted_by.is_empty() {
299                    write!(f, " SORTED BY ({})", display_comma_separated(sorted_by))?;
300                }
301                if *num_buckets > 0 {
302                    write!(f, " INTO {} BUCKETS", num_buckets)?;
303                }
304            }
305            HiveDistributionStyle::SKEWED {
306                columns,
307                on,
308                stored_as_directories,
309            } => {
310                write!(
311                    f,
312                    " SKEWED BY ({})) ON ({})",
313                    display_comma_separated(columns),
314                    display_comma_separated(on)
315                )?;
316                if *stored_as_directories {
317                    write!(f, " STORED AS DIRECTORIES")?;
318                }
319            }
320            _ => (),
321        }
322
323        if let Some(HiveFormat {
324            row_format,
325            storage,
326            location,
327        }) = hive_formats
328        {
329            match row_format {
330                Some(HiveRowFormat::SERDE { class }) => write!(f, " ROW FORMAT SERDE '{}'", class)?,
331                Some(HiveRowFormat::DELIMITED) => write!(f, " ROW FORMAT DELIMITED")?,
332                None => (),
333            }
334            match storage {
335                Some(HiveIOFormat::IOF {
336                    input_format,
337                    output_format,
338                }) => write!(
339                    f,
340                    " STORED AS INPUTFORMAT {} OUTPUTFORMAT {}",
341                    input_format, output_format
342                )?,
343                Some(HiveIOFormat::FileFormat { format }) if !*external => {
344                    write!(f, " STORED AS {}", format)?
345                }
346                _ => (),
347            }
348            if !*external {
349                if let Some(loc) = location {
350                    write!(f, " LOCATION '{}'", loc)?;
351                }
352            }
353        }
354        if *external {
355            write!(
356                f,
357                " STORED AS {} LOCATION '{}'",
358                file_format.as_ref().unwrap(),
359                location.as_ref().unwrap()
360            )?;
361        }
362        if !table_properties.is_empty() {
363            write!(
364                f,
365                " TBLPROPERTIES ({})",
366                display_comma_separated(table_properties)
367            )?;
368        }
369        if !with_options.is_empty() {
370            write!(f, " WITH ({})", display_comma_separated(with_options))?;
371        }
372        if let Some(query) = query {
373            write!(f, " AS {}", query)?;
374        }
375        Ok(())
376    }
377}
378
379impl fmt::Display for CreateVirtualTable {
380    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
381        write!(
382            f,
383            "CREATE VIRTUAL TABLE {if_not_exists}{name} USING {module_name}",
384            if_not_exists = if self.if_not_exists {
385                "IF NOT EXISTS "
386            } else {
387                ""
388            },
389            name = self.name,
390            module_name = self.module_name
391        )?;
392        if !self.module_args.is_empty() {
393            write!(f, " ({})", display_comma_separated(&self.module_args))?;
394        }
395        Ok(())
396    }
397}
398
399impl fmt::Display for CreateIndex {
400    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401        write!(
402            f,
403            "CREATE {unique}INDEX {if_not_exists}{name} ON {table_name}({columns})",
404            unique = if self.unique { "UNIQUE " } else { "" },
405            if_not_exists = if self.if_not_exists {
406                "IF NOT EXISTS "
407            } else {
408                ""
409            },
410            name = self.name,
411            table_name = self.table_name,
412            columns = display_separated(&self.columns, ",")
413        )
414    }
415}
416
417impl fmt::Display for AlterTable {
418    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
419        write!(f, "ALTER TABLE {} {}", self.name, self.operation)
420    }
421}
422
423impl fmt::Display for Drop {
424    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
425        write!(
426            f,
427            "DROP {}{} {}{}{}",
428            self.object_type,
429            if self.if_exists { " IF EXISTS" } else { "" },
430            display_comma_separated(&self.names),
431            if self.cascade { " CASCADE" } else { "" },
432            if self.purge { " PURGE" } else { "" }
433        )
434    }
435}
436
437impl fmt::Display for SetVariable {
438    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
439        f.write_str("SET ")?;
440        if self.local {
441            f.write_str("LOCAL ")?;
442        }
443        write!(
444            f,
445            "{hivevar}{name} = {value}",
446            hivevar = if self.hivevar { "HIVEVAR:" } else { "" },
447            name = self.variable,
448            value = display_comma_separated(&self.value)
449        )
450    }
451}
452
453impl fmt::Display for ShowVariable {
454    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
455        write!(f, "SHOW")?;
456        if !self.variable.is_empty() {
457            write!(f, " {}", display_separated(&self.variable, " "))?;
458        }
459        Ok(())
460    }
461}
462
463impl fmt::Display for ShowCreate {
464    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
465        write!(
466            f,
467            "SHOW CREATE {obj_type} {obj_name}",
468            obj_type = self.obj_type,
469            obj_name = self.obj_name,
470        )?;
471        Ok(())
472    }
473}
474
475impl fmt::Display for ShowColumns {
476    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
477        write!(
478            f,
479            "SHOW {extended}{full}COLUMNS FROM {table_name}",
480            extended = if self.extended { "EXTENDED " } else { "" },
481            full = if self.full { "FULL " } else { "" },
482            table_name = self.table_name,
483        )?;
484        if let Some(filter) = &self.filter {
485            write!(f, " {}", filter)?;
486        }
487        Ok(())
488    }
489}
490
491impl fmt::Display for StartTransaction {
492    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
493        write!(f, "START TRANSACTION")?;
494        if !self.modes.is_empty() {
495            write!(f, " {}", display_comma_separated(&self.modes))?;
496        }
497        Ok(())
498    }
499}
500
501impl fmt::Display for SetTransaction {
502    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
503        write!(f, "SET TRANSACTION")?;
504        if !self.modes.is_empty() {
505            write!(f, " {}", display_comma_separated(&self.modes))?;
506        }
507        Ok(())
508    }
509}
510
511impl fmt::Display for Commit {
512    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
513        write!(f, "COMMIT{}", if self.chain { " AND CHAIN" } else { "" },)
514    }
515}
516
517impl fmt::Display for Rollback {
518    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
519        write!(f, "ROLLBACK{}", if self.chain { " AND CHAIN" } else { "" },)
520    }
521}
522
523impl fmt::Display for CreateSchema {
524    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525        write!(
526            f,
527            "CREATE SCHEMA {if_not_exists}{name}",
528            if_not_exists = if self.if_not_exists {
529                "IF NOT EXISTS "
530            } else {
531                ""
532            },
533            name = self.schema_name
534        )
535    }
536}
537
538impl fmt::Display for Assert {
539    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
540        write!(f, "ASSERT {}", self.condition)?;
541        if let Some(m) = &self.message {
542            write!(f, " AS {}", m)?;
543        }
544        Ok(())
545    }
546}
547impl fmt::Display for Deallocate {
548    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
549        write!(
550            f,
551            "DEALLOCATE {prepare}{name}",
552            prepare = if self.prepare { "PREPARE " } else { "" },
553            name = self.name,
554        )
555    }
556}
557
558impl fmt::Display for Execute {
559    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
560        write!(f, "EXECUTE {}", self.name)?;
561        if !self.parameters.is_empty() {
562            write!(f, "({})", display_comma_separated(&self.parameters))?;
563        }
564        Ok(())
565    }
566}
567
568impl fmt::Display for Prepare {
569    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
570        write!(f, "PREPARE {} ", self.name)?;
571        if !self.data_types.is_empty() {
572            write!(f, "({}) ", display_comma_separated(&self.data_types))?;
573        }
574        write!(f, "AS {}", self.statement)
575    }
576}