1#[cfg(not(feature = "std"))]
19use alloc::{boxed::Box, format, string::String, vec, vec::Vec};
20
21#[cfg(feature = "serde")]
22use serde::{Deserialize, Serialize};
23
24#[cfg(feature = "visitor")]
25use sqlparser_derive::{Visit, VisitMut};
26
27use crate::ast::{
28 ClusteredBy, ColumnDef, CommentDef, CreateTable, CreateTableLikeKind, CreateTableOptions,
29 DistStyle, Expr, FileFormat, ForValues, HiveDistributionStyle, HiveFormat, Ident,
30 InitializeKind, ObjectName, OnCommit, OneOrManyWithParens, Query, RefreshModeKind,
31 RowAccessPolicy, SqliteTableOptions, Statement, StorageLifecyclePolicy,
32 StorageSerializationPolicy, TableConstraint, TableVersion, Tag, WithData, WrappedCollection,
33};
34
35use crate::parser::ParserError;
36
37#[derive(Debug, Clone, PartialEq, Eq, Hash)]
65#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
66#[cfg_attr(feature = "visitor", derive(Visit, VisitMut))]
67pub struct CreateTableBuilder {
68 pub or_replace: bool,
70 pub temporary: bool,
72 pub unlogged: bool,
74 pub external: bool,
76 pub global: Option<bool>,
78 pub if_not_exists: bool,
80 pub transient: bool,
82 pub volatile: bool,
84 pub iceberg: bool,
86 pub snapshot: bool,
88 pub dynamic: bool,
90 pub name: ObjectName,
92 pub columns: Vec<ColumnDef>,
94 pub constraints: Vec<TableConstraint>,
96 pub hive_distribution: HiveDistributionStyle,
98 pub hive_formats: Option<HiveFormat>,
100 pub file_format: Option<FileFormat>,
102 pub location: Option<String>,
104 pub query: Option<Box<Query>>,
106 pub sqlite_table_options: SqliteTableOptions,
108 pub like: Option<CreateTableLikeKind>,
110 pub clone: Option<ObjectName>,
112 pub version: Option<TableVersion>,
114 pub comment: Option<CommentDef>,
116 pub on_commit: Option<OnCommit>,
118 pub on_cluster: Option<Ident>,
120 pub primary_key: Option<Box<Expr>>,
122 pub order_by: Option<OneOrManyWithParens<Expr>>,
124 pub partition_by: Option<Box<Expr>>,
126 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
128 pub clustered_by: Option<ClusteredBy>,
130 pub inherits: Option<Vec<ObjectName>>,
132 pub partition_of: Option<ObjectName>,
134 pub for_values: Option<ForValues>,
136 pub copy_grants: bool,
138 pub enable_schema_evolution: Option<bool>,
140 pub change_tracking: Option<bool>,
142 pub data_retention_time_in_days: Option<u64>,
144 pub max_data_extension_time_in_days: Option<u64>,
146 pub default_ddl_collation: Option<String>,
148 pub with_aggregation_policy: Option<ObjectName>,
150 pub with_row_access_policy: Option<RowAccessPolicy>,
152 pub with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
154 pub with_tags: Option<Vec<Tag>>,
156 pub base_location: Option<String>,
158 pub external_volume: Option<String>,
160 pub with_connection: Option<ObjectName>,
163 pub catalog: Option<String>,
165 pub catalog_sync: Option<String>,
167 pub storage_serialization_policy: Option<StorageSerializationPolicy>,
169 pub table_options: CreateTableOptions,
171 pub target_lag: Option<String>,
173 pub warehouse: Option<Ident>,
175 pub refresh_mode: Option<RefreshModeKind>,
177 pub initialize: Option<InitializeKind>,
179 pub require_user: bool,
181 pub diststyle: Option<DistStyle>,
183 pub distkey: Option<Expr>,
185 pub sortkey: Option<Vec<Expr>>,
187 pub backup: Option<bool>,
189 pub multiset: Option<bool>,
191 pub fallback: Option<bool>,
193 pub with_data: Option<WithData>,
195}
196
197impl CreateTableBuilder {
198 pub fn new(name: ObjectName) -> Self {
200 Self {
201 or_replace: false,
202 temporary: false,
203 unlogged: false,
204 external: false,
205 global: None,
206 if_not_exists: false,
207 transient: false,
208 volatile: false,
209 iceberg: false,
210 snapshot: false,
211 dynamic: false,
212 name,
213 columns: vec![],
214 constraints: vec![],
215 hive_distribution: HiveDistributionStyle::NONE,
216 hive_formats: None,
217 file_format: None,
218 location: None,
219 query: None,
220 sqlite_table_options: SqliteTableOptions::default(),
221 like: None,
222 clone: None,
223 version: None,
224 comment: None,
225 on_commit: None,
226 on_cluster: None,
227 primary_key: None,
228 order_by: None,
229 partition_by: None,
230 cluster_by: None,
231 clustered_by: None,
232 inherits: None,
233 partition_of: None,
234 for_values: None,
235 copy_grants: false,
236 enable_schema_evolution: None,
237 change_tracking: None,
238 data_retention_time_in_days: None,
239 max_data_extension_time_in_days: None,
240 default_ddl_collation: None,
241 with_aggregation_policy: None,
242 with_row_access_policy: None,
243 with_storage_lifecycle_policy: None,
244 with_tags: None,
245 base_location: None,
246 external_volume: None,
247 with_connection: None,
248 catalog: None,
249 catalog_sync: None,
250 storage_serialization_policy: None,
251 table_options: CreateTableOptions::None,
252 target_lag: None,
253 warehouse: None,
254 refresh_mode: None,
255 initialize: None,
256 require_user: false,
257 diststyle: None,
258 distkey: None,
259 sortkey: None,
260 backup: None,
261 multiset: None,
262 fallback: None,
263 with_data: None,
264 }
265 }
266 pub fn or_replace(mut self, or_replace: bool) -> Self {
268 self.or_replace = or_replace;
269 self
270 }
271 pub fn temporary(mut self, temporary: bool) -> Self {
273 self.temporary = temporary;
274 self
275 }
276 pub fn unlogged(mut self, unlogged: bool) -> Self {
278 self.unlogged = unlogged;
279 self
280 }
281 pub fn external(mut self, external: bool) -> Self {
283 self.external = external;
284 self
285 }
286 pub fn global(mut self, global: Option<bool>) -> Self {
288 self.global = global;
289 self
290 }
291 pub fn if_not_exists(mut self, if_not_exists: bool) -> Self {
293 self.if_not_exists = if_not_exists;
294 self
295 }
296 pub fn transient(mut self, transient: bool) -> Self {
298 self.transient = transient;
299 self
300 }
301 pub fn volatile(mut self, volatile: bool) -> Self {
303 self.volatile = volatile;
304 self
305 }
306 pub fn iceberg(mut self, iceberg: bool) -> Self {
308 self.iceberg = iceberg;
309 self
310 }
311 pub fn snapshot(mut self, snapshot: bool) -> Self {
313 self.snapshot = snapshot;
314 self
315 }
316 pub fn dynamic(mut self, dynamic: bool) -> Self {
318 self.dynamic = dynamic;
319 self
320 }
321 pub fn columns(mut self, columns: Vec<ColumnDef>) -> Self {
323 self.columns = columns;
324 self
325 }
326 pub fn constraints(mut self, constraints: Vec<TableConstraint>) -> Self {
328 self.constraints = constraints;
329 self
330 }
331 pub fn hive_distribution(mut self, hive_distribution: HiveDistributionStyle) -> Self {
333 self.hive_distribution = hive_distribution;
334 self
335 }
336 pub fn hive_formats(mut self, hive_formats: Option<HiveFormat>) -> Self {
338 self.hive_formats = hive_formats;
339 self
340 }
341 pub fn file_format(mut self, file_format: Option<FileFormat>) -> Self {
343 self.file_format = file_format;
344 self
345 }
346 pub fn location(mut self, location: Option<String>) -> Self {
348 self.location = location;
349 self
350 }
351 pub fn query(mut self, query: Option<Box<Query>>) -> Self {
353 self.query = query;
354 self
355 }
356 pub fn sqlite_table_options(mut self, sqlite_table_options: SqliteTableOptions) -> Self {
358 self.sqlite_table_options = sqlite_table_options;
359 self
360 }
361 pub fn like(mut self, like: Option<CreateTableLikeKind>) -> Self {
363 self.like = like;
364 self
365 }
366 pub fn clone_clause(mut self, clone: Option<ObjectName>) -> Self {
369 self.clone = clone;
370 self
371 }
372 pub fn version(mut self, version: Option<TableVersion>) -> Self {
374 self.version = version;
375 self
376 }
377 pub fn comment_after_column_def(mut self, comment: Option<CommentDef>) -> Self {
379 self.comment = comment;
380 self
381 }
382 pub fn on_commit(mut self, on_commit: Option<OnCommit>) -> Self {
384 self.on_commit = on_commit;
385 self
386 }
387 pub fn on_cluster(mut self, on_cluster: Option<Ident>) -> Self {
389 self.on_cluster = on_cluster;
390 self
391 }
392 pub fn primary_key(mut self, primary_key: Option<Box<Expr>>) -> Self {
394 self.primary_key = primary_key;
395 self
396 }
397 pub fn order_by(mut self, order_by: Option<OneOrManyWithParens<Expr>>) -> Self {
399 self.order_by = order_by;
400 self
401 }
402 pub fn partition_by(mut self, partition_by: Option<Box<Expr>>) -> Self {
404 self.partition_by = partition_by;
405 self
406 }
407 pub fn cluster_by(mut self, cluster_by: Option<WrappedCollection<Vec<Expr>>>) -> Self {
409 self.cluster_by = cluster_by;
410 self
411 }
412 pub fn clustered_by(mut self, clustered_by: Option<ClusteredBy>) -> Self {
414 self.clustered_by = clustered_by;
415 self
416 }
417 pub fn inherits(mut self, inherits: Option<Vec<ObjectName>>) -> Self {
419 self.inherits = inherits;
420 self
421 }
422
423 pub fn partition_of(mut self, partition_of: Option<ObjectName>) -> Self {
425 self.partition_of = partition_of;
426 self
427 }
428
429 pub fn for_values(mut self, for_values: Option<ForValues>) -> Self {
431 self.for_values = for_values;
432 self
433 }
434 pub fn copy_grants(mut self, copy_grants: bool) -> Self {
436 self.copy_grants = copy_grants;
437 self
438 }
439 pub fn enable_schema_evolution(mut self, enable_schema_evolution: Option<bool>) -> Self {
441 self.enable_schema_evolution = enable_schema_evolution;
442 self
443 }
444 pub fn change_tracking(mut self, change_tracking: Option<bool>) -> Self {
446 self.change_tracking = change_tracking;
447 self
448 }
449 pub fn data_retention_time_in_days(mut self, data_retention_time_in_days: Option<u64>) -> Self {
451 self.data_retention_time_in_days = data_retention_time_in_days;
452 self
453 }
454 pub fn max_data_extension_time_in_days(
456 mut self,
457 max_data_extension_time_in_days: Option<u64>,
458 ) -> Self {
459 self.max_data_extension_time_in_days = max_data_extension_time_in_days;
460 self
461 }
462 pub fn default_ddl_collation(mut self, default_ddl_collation: Option<String>) -> Self {
464 self.default_ddl_collation = default_ddl_collation;
465 self
466 }
467 pub fn with_aggregation_policy(mut self, with_aggregation_policy: Option<ObjectName>) -> Self {
469 self.with_aggregation_policy = with_aggregation_policy;
470 self
471 }
472 pub fn with_row_access_policy(
474 mut self,
475 with_row_access_policy: Option<RowAccessPolicy>,
476 ) -> Self {
477 self.with_row_access_policy = with_row_access_policy;
478 self
479 }
480 pub fn with_storage_lifecycle_policy(
482 mut self,
483 with_storage_lifecycle_policy: Option<StorageLifecyclePolicy>,
484 ) -> Self {
485 self.with_storage_lifecycle_policy = with_storage_lifecycle_policy;
486 self
487 }
488 pub fn with_tags(mut self, with_tags: Option<Vec<Tag>>) -> Self {
490 self.with_tags = with_tags;
491 self
492 }
493 pub fn base_location(mut self, base_location: Option<String>) -> Self {
495 self.base_location = base_location;
496 self
497 }
498 pub fn external_volume(mut self, external_volume: Option<String>) -> Self {
500 self.external_volume = external_volume;
501 self
502 }
503 pub fn with_connection(mut self, with_connection: Option<ObjectName>) -> Self {
505 self.with_connection = with_connection;
506 self
507 }
508 pub fn catalog(mut self, catalog: Option<String>) -> Self {
510 self.catalog = catalog;
511 self
512 }
513 pub fn catalog_sync(mut self, catalog_sync: Option<String>) -> Self {
515 self.catalog_sync = catalog_sync;
516 self
517 }
518 pub fn storage_serialization_policy(
520 mut self,
521 storage_serialization_policy: Option<StorageSerializationPolicy>,
522 ) -> Self {
523 self.storage_serialization_policy = storage_serialization_policy;
524 self
525 }
526 pub fn table_options(mut self, table_options: CreateTableOptions) -> Self {
528 self.table_options = table_options;
529 self
530 }
531 pub fn target_lag(mut self, target_lag: Option<String>) -> Self {
533 self.target_lag = target_lag;
534 self
535 }
536 pub fn warehouse(mut self, warehouse: Option<Ident>) -> Self {
538 self.warehouse = warehouse;
539 self
540 }
541 pub fn refresh_mode(mut self, refresh_mode: Option<RefreshModeKind>) -> Self {
543 self.refresh_mode = refresh_mode;
544 self
545 }
546 pub fn initialize(mut self, initialize: Option<InitializeKind>) -> Self {
548 self.initialize = initialize;
549 self
550 }
551 pub fn require_user(mut self, require_user: bool) -> Self {
553 self.require_user = require_user;
554 self
555 }
556 pub fn diststyle(mut self, diststyle: Option<DistStyle>) -> Self {
558 self.diststyle = diststyle;
559 self
560 }
561 pub fn distkey(mut self, distkey: Option<Expr>) -> Self {
563 self.distkey = distkey;
564 self
565 }
566 pub fn sortkey(mut self, sortkey: Option<Vec<Expr>>) -> Self {
568 self.sortkey = sortkey;
569 self
570 }
571 pub fn backup(mut self, backup: Option<bool>) -> Self {
573 self.backup = backup;
574 self
575 }
576 pub fn multiset(mut self, multiset: Option<bool>) -> Self {
579 self.multiset = multiset;
580 self
581 }
582 pub fn fallback(mut self, fallback: Option<bool>) -> Self {
584 self.fallback = fallback;
585 self
586 }
587 pub fn with_data(mut self, with_data: Option<WithData>) -> Self {
589 self.with_data = with_data;
590 self
591 }
592 pub fn build(self) -> CreateTable {
594 CreateTable {
595 or_replace: self.or_replace,
596 temporary: self.temporary,
597 unlogged: self.unlogged,
598 external: self.external,
599 global: self.global,
600 if_not_exists: self.if_not_exists,
601 transient: self.transient,
602 volatile: self.volatile,
603 iceberg: self.iceberg,
604 snapshot: self.snapshot,
605 dynamic: self.dynamic,
606 name: self.name,
607 columns: self.columns,
608 constraints: self.constraints,
609 hive_distribution: self.hive_distribution,
610 hive_formats: self.hive_formats,
611 file_format: self.file_format,
612 location: self.location,
613 query: self.query,
614 sqlite_table_options: self.sqlite_table_options,
615 like: self.like,
616 clone: self.clone,
617 version: self.version,
618 comment: self.comment,
619 on_commit: self.on_commit,
620 on_cluster: self.on_cluster,
621 primary_key: self.primary_key,
622 order_by: self.order_by,
623 partition_by: self.partition_by,
624 cluster_by: self.cluster_by,
625 clustered_by: self.clustered_by,
626 inherits: self.inherits,
627 partition_of: self.partition_of,
628 for_values: self.for_values,
629 copy_grants: self.copy_grants,
630 enable_schema_evolution: self.enable_schema_evolution,
631 change_tracking: self.change_tracking,
632 data_retention_time_in_days: self.data_retention_time_in_days,
633 max_data_extension_time_in_days: self.max_data_extension_time_in_days,
634 default_ddl_collation: self.default_ddl_collation,
635 with_aggregation_policy: self.with_aggregation_policy,
636 with_row_access_policy: self.with_row_access_policy,
637 with_storage_lifecycle_policy: self.with_storage_lifecycle_policy,
638 with_tags: self.with_tags,
639 base_location: self.base_location,
640 external_volume: self.external_volume,
641 with_connection: self.with_connection,
642 catalog: self.catalog,
643 catalog_sync: self.catalog_sync,
644 storage_serialization_policy: self.storage_serialization_policy,
645 table_options: self.table_options,
646 target_lag: self.target_lag,
647 warehouse: self.warehouse,
648 refresh_mode: self.refresh_mode,
649 initialize: self.initialize,
650 require_user: self.require_user,
651 diststyle: self.diststyle,
652 distkey: self.distkey,
653 sortkey: self.sortkey,
654 backup: self.backup,
655 multiset: self.multiset,
656 fallback: self.fallback,
657 with_data: self.with_data,
658 }
659 }
660}
661
662impl TryFrom<Statement> for CreateTableBuilder {
663 type Error = ParserError;
664
665 fn try_from(stmt: Statement) -> Result<Self, Self::Error> {
668 match stmt {
669 Statement::CreateTable(create_table) => Ok(create_table.into()),
670 _ => Err(ParserError::ParserError(format!(
671 "Expected create table statement, but received: {stmt}"
672 ))),
673 }
674 }
675}
676
677impl From<CreateTable> for CreateTableBuilder {
678 fn from(table: CreateTable) -> Self {
679 Self {
680 or_replace: table.or_replace,
681 temporary: table.temporary,
682 unlogged: table.unlogged,
683 external: table.external,
684 global: table.global,
685 if_not_exists: table.if_not_exists,
686 transient: table.transient,
687 volatile: table.volatile,
688 iceberg: table.iceberg,
689 snapshot: table.snapshot,
690 dynamic: table.dynamic,
691 name: table.name,
692 columns: table.columns,
693 constraints: table.constraints,
694 hive_distribution: table.hive_distribution,
695 hive_formats: table.hive_formats,
696 file_format: table.file_format,
697 location: table.location,
698 query: table.query,
699 sqlite_table_options: table.sqlite_table_options,
700 like: table.like,
701 clone: table.clone,
702 version: table.version,
703 comment: table.comment,
704 on_commit: table.on_commit,
705 on_cluster: table.on_cluster,
706 primary_key: table.primary_key,
707 order_by: table.order_by,
708 partition_by: table.partition_by,
709 cluster_by: table.cluster_by,
710 clustered_by: table.clustered_by,
711 inherits: table.inherits,
712 partition_of: table.partition_of,
713 for_values: table.for_values,
714 copy_grants: table.copy_grants,
715 enable_schema_evolution: table.enable_schema_evolution,
716 change_tracking: table.change_tracking,
717 data_retention_time_in_days: table.data_retention_time_in_days,
718 max_data_extension_time_in_days: table.max_data_extension_time_in_days,
719 default_ddl_collation: table.default_ddl_collation,
720 with_aggregation_policy: table.with_aggregation_policy,
721 with_row_access_policy: table.with_row_access_policy,
722 with_storage_lifecycle_policy: table.with_storage_lifecycle_policy,
723 with_tags: table.with_tags,
724 base_location: table.base_location,
725 external_volume: table.external_volume,
726 with_connection: table.with_connection,
727 catalog: table.catalog,
728 catalog_sync: table.catalog_sync,
729 storage_serialization_policy: table.storage_serialization_policy,
730 table_options: table.table_options,
731 target_lag: table.target_lag,
732 warehouse: table.warehouse,
733 refresh_mode: table.refresh_mode,
734 initialize: table.initialize,
735 require_user: table.require_user,
736 diststyle: table.diststyle,
737 distkey: table.distkey,
738 sortkey: table.sortkey,
739 backup: table.backup,
740 multiset: table.multiset,
741 fallback: table.fallback,
742 with_data: table.with_data,
743 }
744 }
745}
746
747#[derive(Default)]
749pub(crate) struct CreateTableConfiguration {
750 pub partition_by: Option<Box<Expr>>,
751 pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
752 pub inherits: Option<Vec<ObjectName>>,
753 pub table_options: CreateTableOptions,
754}
755
756#[cfg(test)]
757mod tests {
758 use crate::ast::helpers::stmt_create_table::CreateTableBuilder;
759 use crate::ast::{Ident, ObjectName, Statement};
760 use crate::parser::ParserError;
761
762 #[test]
763 pub fn test_from_valid_statement() {
764 let builder = CreateTableBuilder::new(ObjectName::from(vec![Ident::new("table_name")]));
765
766 let create_table = builder.clone().build();
767 let stmt: Statement = create_table.into();
768
769 assert_eq!(builder, CreateTableBuilder::try_from(stmt).unwrap());
770 }
771
772 #[test]
773 pub fn test_from_invalid_statement() {
774 let stmt = Statement::Commit {
775 chain: false,
776 end: false,
777 modifier: None,
778 };
779
780 assert_eq!(
781 CreateTableBuilder::try_from(stmt).unwrap_err(),
782 ParserError::ParserError(
783 "Expected create table statement, but received: COMMIT".to_owned()
784 )
785 );
786 }
787}