-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathcompiler.py
More file actions
642 lines (539 loc) · 25 KB
/
Copy pathcompiler.py
File metadata and controls
642 lines (539 loc) · 25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
# -*- coding: utf-8 -*-
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union, cast
from sqlalchemy import exc, types, util
from sqlalchemy.sql.compiler import (
DDLCompiler,
GenericTypeCompiler,
IdentifierPreparer,
SQLCompiler,
)
from sqlalchemy.sql.elements import BindParameter
from sqlalchemy.sql.schema import Column
from pyathena.model import (
AthenaFileFormat,
AthenaPartitionTransform,
AthenaRowFormatSerde,
)
from pyathena.sqlalchemy.types import AthenaArray, AthenaMap, AthenaStruct
if TYPE_CHECKING:
from sqlalchemy import (
Cast,
CheckConstraint,
ForeignKeyConstraint,
PrimaryKeyConstraint,
Table,
UniqueConstraint,
)
from sqlalchemy.sql.ddl import CreateTable
from sqlalchemy.sql.elements import FunctionElement
from sqlalchemy.sql.selectable import GenerativeSelect
from pyathena.sqlalchemy.base import AthenaDialect
_DialectArgDict = Dict[str, Any]
CreateColumn = Any
class AthenaTypeCompiler(GenericTypeCompiler):
def visit_FLOAT(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_REAL(type_, **kw)
def visit_REAL(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "FLOAT"
def visit_DOUBLE(self, type_, **kw) -> str: # noqa: N802
return "DOUBLE"
def visit_DOUBLE_PRECISION(self, type_, **kw) -> str: # noqa: N802
return "DOUBLE"
def visit_NUMERIC(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_DECIMAL(type_, **kw)
def visit_DECIMAL(self, type_: Type[Any], **kw) -> str: # noqa: N802
if type_.precision is None:
return "DECIMAL"
if type_.scale is None:
return f"DECIMAL({type_.precision})"
return f"DECIMAL({type_.precision}, {type_.scale})"
def visit_TINYINT(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "TINYINT"
def visit_INTEGER(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "INTEGER"
def visit_SMALLINT(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "SMALLINT"
def visit_BIGINT(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "BIGINT"
def visit_TIMESTAMP(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "TIMESTAMP"
def visit_DATETIME(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_TIMESTAMP(type_, **kw)
def visit_DATE(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "DATE"
def visit_TIME(self, type_: Type[Any], **kw) -> str: # noqa: N802
raise exc.CompileError(f"Data type `{type_}` is not supported")
def visit_CLOB(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_BINARY(type_, **kw)
def visit_NCLOB(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_BINARY(type_, **kw)
def visit_CHAR(self, type_: Type[Any], **kw) -> str: # noqa: N802
if type_.length:
return cast(str, self._render_string_type(type_, "CHAR"))
return "STRING"
def visit_NCHAR(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_CHAR(type_, **kw)
def visit_VARCHAR(self, type_: Type[Any], **kw) -> str: # noqa: N802
if type_.length:
return cast(str, self._render_string_type(type_, "VARCHAR"))
return "STRING"
def visit_NVARCHAR(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_VARCHAR(type_, **kw)
def visit_TEXT(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "STRING"
def visit_BLOB(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_BINARY(type_, **kw)
def visit_BINARY(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "BINARY"
def visit_VARBINARY(self, type_: Type[Any], **kw) -> str: # noqa: N802
return self.visit_BINARY(type_, **kw)
def visit_BOOLEAN(self, type_: Type[Any], **kw) -> str: # noqa: N802
return "BOOLEAN"
def visit_string(self, type_, **kw): # noqa: N802
return "STRING"
def visit_unicode(self, type_, **kw): # noqa: N802
return "STRING"
def visit_unicode_text(self, type_, **kw): # noqa: N802
return "STRING"
def visit_null(self, type_, **kw): # noqa: N802
return "NULL"
def visit_tinyint(self, type_, **kw): # noqa: N802
return self.visit_TINYINT(type_, **kw)
def visit_enum(self, type_, **kw):
return self.visit_string(type_, **kw)
def visit_struct(self, type_, **kw): # noqa: N802
if isinstance(type_, AthenaStruct):
if type_.fields:
field_specs = []
for field_name, field_type in type_.fields.items():
field_type_str = self.process(field_type, **kw)
field_specs.append(f"{field_name} {field_type_str}")
return f"ROW({', '.join(field_specs)})"
return "ROW()"
return "ROW()"
def visit_STRUCT(self, type_, **kw): # noqa: N802
return self.visit_struct(type_, **kw)
def visit_map(self, type_, **kw): # noqa: N802
if isinstance(type_, AthenaMap):
key_type_str = self.process(type_.key_type, **kw)
value_type_str = self.process(type_.value_type, **kw)
return f"MAP<{key_type_str}, {value_type_str}>"
return "MAP<STRING, STRING>"
def visit_MAP(self, type_, **kw): # noqa: N802
return self.visit_map(type_, **kw)
def visit_array(self, type_, **kw): # noqa: N802
if isinstance(type_, AthenaArray):
item_type_str = self.process(type_.item_type, **kw)
return f"ARRAY<{item_type_str}>"
return "ARRAY<STRING>"
def visit_ARRAY(self, type_, **kw): # noqa: N802
return self.visit_array(type_, **kw)
class AthenaStatementCompiler(SQLCompiler):
def visit_char_length_func(self, fn: "FunctionElement[Any]", **kw):
return f"length{self.function_argspec(fn, **kw)}"
def visit_filter_func(self, fn: "FunctionElement[Any]", **kw) -> str:
"""Compile Athena filter() function with lambda expressions.
Supports syntax: filter(array_expr, lambda_expr)
Example: filter(ARRAY[1, 2, 3], x -> x > 1)
"""
if len(fn.clauses.clauses) != 2:
raise exc.CompileError(
f"filter() function expects exactly 2 arguments, got {len(fn.clauses.clauses)}"
)
array_expr = fn.clauses.clauses[0]
lambda_expr = fn.clauses.clauses[1]
# Process the array expression normally
array_sql = self.process(array_expr, **kw)
# Process lambda expression - handle string literals as lambda expressions
if isinstance(lambda_expr, BindParameter) and isinstance(lambda_expr.value, str):
# Handle string literal lambda expressions like 'x -> x > 0'
lambda_sql = lambda_expr.value
else:
# Process as regular SQL expression
lambda_sql = self.process(lambda_expr, **kw)
return f"filter({array_sql}, {lambda_sql})"
def visit_cast(self, cast: "Cast[Any]", **kwargs):
if (isinstance(cast.type, types.VARCHAR) and cast.type.length is None) or isinstance(
cast.type, types.String
):
type_clause = "VARCHAR"
elif isinstance(cast.type, types.CHAR) and cast.type.length is None:
type_clause = "CHAR"
elif isinstance(cast.type, (types.BINARY, types.VARBINARY)):
type_clause = "VARBINARY"
elif isinstance(cast.type, (types.FLOAT, types.Float, types.REAL)):
# https://docs.aws.amazon.com/athena/latest/ug/data-types.html
# In Athena, use float in DDL statements like CREATE TABLE
# and real in SQL functions like SELECT CAST.
type_clause = "REAL"
else:
type_clause = cast.typeclause._compiler_dispatch(self, **kwargs)
return f"CAST({cast.clause._compiler_dispatch(self, **kwargs)} AS {type_clause})"
def limit_clause(self, select: "GenerativeSelect", **kw):
text = []
if select._offset_clause is not None:
text.append(" OFFSET " + self.process(select._offset_clause, **kw))
if select._limit_clause is not None:
text.append(" LIMIT " + self.process(select._limit_clause, **kw))
return "\n".join(text)
def get_from_hint_text(self, table, text):
return text
def format_from_hint_text(self, sqltext, table, hint, iscrud):
hint_upper = hint.upper()
if (
any(
[
hint_upper.startswith("FOR TIMESTAMP AS OF"),
hint_upper.startswith("FOR SYSTEM_TIME AS OF"),
hint_upper.startswith("FOR VERSION AS OF"),
hint_upper.startswith("FOR SYSTEM_VERSION AS OF"),
]
)
and "AS" in sqltext
):
_, alias = sqltext.split(" AS ", 1)
return f"{table.original.fullname} {hint} AS {alias}"
return f"{sqltext} {hint}"
class AthenaDDLCompiler(DDLCompiler):
@property
def preparer(self) -> IdentifierPreparer:
return self._preparer
@preparer.setter
def preparer(self, value: IdentifierPreparer):
pass
def __init__(
self,
dialect: "AthenaDialect",
statement: "CreateTable",
schema_translate_map: Optional[Dict[Optional[str], Optional[str]]] = None,
render_schema_translate: bool = False,
compile_kwargs: Optional[Dict[str, Any]] = None,
):
from pyathena.sqlalchemy.preparer import AthenaDDLIdentifierPreparer
self._preparer = AthenaDDLIdentifierPreparer(dialect)
super().__init__(
dialect=dialect,
statement=statement,
render_schema_translate=render_schema_translate,
schema_translate_map=schema_translate_map,
compile_kwargs=compile_kwargs or util.immutabledict(),
)
def _escape_comment(self, value: str) -> str:
value = value.replace("\\", "\\\\").replace("'", r"\'")
# DDL statements raise a KeyError if the placeholders aren't escaped
if self.dialect.identifier_preparer._double_percents:
value = value.replace("%", "%%")
return f"'{value}'"
def _get_comment_specification(self, comment: str) -> str:
return f"COMMENT {self._escape_comment(comment)}"
def _get_bucket_count(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[str]:
if dialect_opts["bucket_count"]:
bucket_count = dialect_opts["bucket_count"]
elif connect_opts:
bucket_count = connect_opts.get("bucket_count")
else:
bucket_count = None
return cast(str, bucket_count) if bucket_count is not None else None
def _get_file_format(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[str]:
if dialect_opts["file_format"]:
file_format = dialect_opts["file_format"]
elif connect_opts:
file_format = connect_opts.get("file_format")
else:
file_format = None
return cast(Optional[str], file_format)
def _get_file_format_specification(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> str:
file_format = self._get_file_format(dialect_opts, connect_opts)
text = []
if file_format:
text.append(f"STORED AS {file_format}")
return "\n".join(text)
def _get_row_format(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[str]:
if dialect_opts["row_format"]:
row_format = dialect_opts["row_format"]
elif connect_opts:
row_format = connect_opts.get("row_format")
else:
row_format = None
return cast(Optional[str], row_format)
def _get_row_format_specification(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> str:
row_format = self._get_row_format(dialect_opts, connect_opts)
text = []
if row_format:
text.append(f"ROW FORMAT {row_format}")
return "\n".join(text)
def _get_serde_properties(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[Union[str, Dict[str, Any]]]:
if dialect_opts["serdeproperties"]:
serde_properties = dialect_opts["serdeproperties"]
elif connect_opts:
serde_properties = connect_opts.get("serdeproperties")
else:
serde_properties = None
return cast(Optional[str], serde_properties)
def _get_serde_properties_specification(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> str:
serde_properties = self._get_serde_properties(dialect_opts, connect_opts)
text = []
if serde_properties:
text.append("WITH SERDEPROPERTIES (")
if isinstance(serde_properties, dict):
text.append(",\n".join([f"\t'{k}' = '{v}'" for k, v in serde_properties.items()]))
else:
text.append(serde_properties)
text.append(")")
return "\n".join(text)
def _get_table_location(
self, table: "Table", dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[str]:
if dialect_opts["location"]:
location = cast(str, dialect_opts["location"])
location += "/" if not location.endswith("/") else ""
elif connect_opts:
base_location = (
cast(str, connect_opts["location"])
if "location" in connect_opts
else cast(str, connect_opts.get("s3_staging_dir"))
)
schema = table.schema if table.schema else connect_opts["schema_name"]
location = f"{base_location}{schema}/{table.name}/"
else:
location = None
return location
def _get_table_location_specification(
self, table: "Table", dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> str:
location = self._get_table_location(table, dialect_opts, connect_opts)
text = []
if location:
text.append(f"LOCATION '{location}'")
else:
if connect_opts:
raise exc.CompileError(
"`location` or `s3_staging_dir` parameter is required in the connection string"
)
raise exc.CompileError(
"The location of the table should be specified "
"by the dialect keyword argument `awsathena_location`"
)
return "\n".join(text)
def _get_table_properties(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[Union[Dict[str, str], str]]:
if dialect_opts["tblproperties"]:
table_properties = cast(str, dialect_opts["tblproperties"])
elif connect_opts:
table_properties = cast(str, connect_opts.get("tblproperties"))
else:
table_properties = None
return table_properties
def _get_compression(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> Optional[str]:
if dialect_opts["compression"]:
compression = cast(str, dialect_opts["compression"])
elif connect_opts:
compression = cast(str, connect_opts.get("compression"))
else:
compression = None
return compression
def _get_table_properties_specification(
self, dialect_opts: "_DialectArgDict", connect_opts: Dict[str, Any]
) -> str:
properties = self._get_table_properties(dialect_opts, connect_opts)
if properties:
if isinstance(properties, dict):
table_properties = [",\n".join([f"\t'{k}' = '{v}'" for k, v in properties.items()])]
else:
table_properties = [properties]
else:
table_properties = []
compression = self._get_compression(dialect_opts, connect_opts)
if compression:
file_format = self._get_file_format(dialect_opts, connect_opts)
row_format = self._get_row_format(dialect_opts, connect_opts)
if file_format:
if file_format == AthenaFileFormat.FILE_FORMAT_PARQUET:
table_properties.append(f"\t'parquet.compress' = '{compression}'")
elif file_format == AthenaFileFormat.FILE_FORMAT_ORC:
table_properties.append(f"\t'orc.compress' = '{compression}'")
else:
table_properties.append(f"\t'write.compress' = '{compression}'")
elif row_format:
if AthenaRowFormatSerde.is_parquet(row_format):
table_properties.append(f"\t'parquet.compress' = '{compression}'")
elif AthenaRowFormatSerde.is_orc(row_format):
table_properties.append(f"\t'orc.compress' = '{compression}'")
else:
table_properties.append(f"\t'write.compress' = '{compression}'")
text = []
if table_properties:
text.append("TBLPROPERTIES (")
text.append(",\n".join(table_properties))
text.append(")")
return "\n".join(text)
def get_column_specification(self, column: "Column[Any]", **kwargs) -> str:
if type(column.type) in [types.Integer, types.INTEGER, types.INT]:
# https://docs.aws.amazon.com/athena/latest/ug/create-table.html
# In Data Definition Language (DDL) queries like CREATE TABLE,
# use the int keyword to represent an integer
type_ = "INT"
else:
type_ = self.dialect.type_compiler.process(column.type, type_expression=column)
text = [f"{self.preparer.format_column(column)} {type_}"]
if column.comment:
text.append(f"{self._get_comment_specification(column.comment)}")
return " ".join(text)
def visit_check_constraint(self, constraint: "CheckConstraint", **kw) -> Optional[str]:
return None
def visit_column_check_constraint(self, constraint: "CheckConstraint", **kw) -> Optional[str]:
return None
def visit_foreign_key_constraint(
self, constraint: "ForeignKeyConstraint", **kw
) -> Optional[str]:
return None
def visit_primary_key_constraint(
self, constraint: "PrimaryKeyConstraint", **kw
) -> Optional[str]:
return None
def visit_unique_constraint(self, constraint: "UniqueConstraint", **kw) -> Optional[str]:
return None
def _get_connect_option_partitions(self, connect_opts: Dict[str, Any]) -> List[str]:
if connect_opts:
partition = cast(str, connect_opts.get("partition"))
partitions = partition.split(",") if partition else []
else:
partitions = []
return partitions
def _get_connect_option_buckets(self, connect_opts: Dict[str, Any]) -> List[str]:
if connect_opts:
bucket = cast(str, connect_opts.get("cluster"))
buckets = bucket.split(",") if bucket else []
else:
buckets = []
return buckets
def _prepared_partitions(self, column: Column[Any]):
# https://docs.aws.amazon.com/athena/latest/ug/querying-iceberg-creating-tables.html#querying-iceberg-partitioning
column_dialect_opts = column.dialect_options["awsathena"]
partition_transform = column_dialect_opts["partition_transform"]
column_name = self.preparer.format_column(column)
transform_column = None
partitions = []
if partition_transform:
if AthenaPartitionTransform.is_valid(partition_transform):
if partition_transform == AthenaPartitionTransform.PARTITION_TRANSFORM_BUCKET:
bucket_count = column_dialect_opts["partition_transform_bucket_count"]
if bucket_count:
transform_column = f"{bucket_count}, {column_name}"
elif partition_transform == AthenaPartitionTransform.PARTITION_TRANSFORM_TRUNCATE:
truncate_length = column_dialect_opts["partition_transform_truncate_length"]
if truncate_length:
transform_column = f"{truncate_length}, {column_name}"
else:
transform_column = column_name
if transform_column:
partitions.append(f"\t{partition_transform}({transform_column})")
else:
partitions.append(f"\t{column_name}")
return partitions
def _prepared_columns(
self,
table: "Table",
is_iceberg: bool,
create_columns: List["CreateColumn"],
connect_opts: Dict[str, Any],
) -> Tuple[List[str], List[str], List[str]]:
columns, partitions, buckets = [], [], []
conn_partitions = self._get_connect_option_partitions(connect_opts)
conn_buckets = self._get_connect_option_buckets(connect_opts)
for create_column in create_columns:
column = create_column.element
column_dialect_opts = column.dialect_options["awsathena"]
try:
processed = self.process(create_column)
if processed is not None:
if (
column_dialect_opts["partition"]
or column.name in conn_partitions
or f"{table.name}.{column.name}" in conn_partitions
):
# https://docs.aws.amazon.com/athena/latest/ug/querying-iceberg-creating-tables.html#querying-iceberg-partitioning
if is_iceberg:
partitions.extend(self._prepared_partitions(column=column))
columns.append(f"\t{processed}")
else:
partitions.append(f"\t{processed}")
else:
columns.append(f"\t{processed}")
if (
column_dialect_opts["cluster"]
or column.name in conn_buckets
or f"{table.name}.{column.name}" in conn_buckets
):
buckets.append(f"\t{self.preparer.format_column(column)}")
except exc.CompileError as e:
raise exc.CompileError(
f"(in table '{table.description}', column '{column.name}'): {e.args[0]}"
) from e
return columns, partitions, buckets
def visit_create_table(self, create: "CreateTable", **kwargs) -> str:
table = create.element
dialect_opts = table.dialect_options["awsathena"]
dialect = cast("AthenaDialect", self.dialect)
connect_opts = dialect._connect_options
table_properties = self._get_table_properties_specification(
dialect_opts, connect_opts
).lower()
is_iceberg = False
if ("table_type" in table_properties) and ("iceberg" in table_properties):
is_iceberg = True
# https://docs.aws.amazon.com/athena/latest/ug/querying-iceberg-creating-tables.html
text = ["\nCREATE TABLE"] if is_iceberg else ["\nCREATE EXTERNAL TABLE"]
if create.if_not_exists:
text.append("IF NOT EXISTS")
text.append(self.preparer.format_table(table))
text.append("(")
text = [" ".join(text)]
columns, partitions, buckets = self._prepared_columns(
table, is_iceberg, create.columns, connect_opts
)
text.append(",\n".join(columns))
text.append(")")
if table.comment:
text.append(self._get_comment_specification(table.comment))
if partitions:
text.append("PARTITIONED BY (")
text.append(",\n".join(partitions))
text.append(")")
bucket_count = self._get_bucket_count(dialect_opts, connect_opts)
if buckets and bucket_count:
text.append("CLUSTERED BY (")
text.append(",\n".join(buckets))
text.append(f") INTO {bucket_count} BUCKETS")
text.append(f"{self.post_create_table(table)}\n")
return "\n".join(text)
def post_create_table(self, table: "Table") -> str:
dialect_opts: "_DialectArgDict" = table.dialect_options["awsathena"]
dialect = cast("AthenaDialect", self.dialect)
connect_opts = dialect._connect_options
text = [
self._get_row_format_specification(dialect_opts, connect_opts),
self._get_serde_properties_specification(dialect_opts, connect_opts),
self._get_file_format_specification(dialect_opts, connect_opts),
self._get_table_location_specification(table, dialect_opts, connect_opts),
self._get_table_properties_specification(dialect_opts, connect_opts),
]
return "\n".join([t for t in text if t])