sqlglot.generator
1from __future__ import annotations 2 3import logging 4import re 5import typing as t 6from collections import defaultdict 7from decimal import Decimal 8from functools import reduce, wraps 9 10from sqlglot import exp 11from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages 12from sqlglot.expressions import apply_index_offset 13from sqlglot.expressions.core import maybe_parse 14from sqlglot.helper import csv, name_sequence, seq_get 15from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS 16from sqlglot.time import format_time 17from sqlglot.tokens import TokenType 18 19if t.TYPE_CHECKING: 20 from sqlglot._typing import E 21 from sqlglot.dialects.dialect import DialectType 22 23 G = t.TypeVar("G", bound="Generator") 24 GeneratorMethod = t.Callable[[G, E], str] 25 26logger = logging.getLogger("sqlglot") 27 28_HIGH_BYTE_RE = re.compile(r"[\x80-\xff]") 29 30ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)") 31UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}." 32 33 34def unsupported_args( 35 *args: str | tuple[str, str], 36) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 37 """ 38 Decorator that can be used to mark certain args of an `Expr` subclass as unsupported. 39 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 40 """ 41 diagnostic_by_arg: dict[str, str | None] = {} 42 for arg in args: 43 if isinstance(arg, str): 44 diagnostic_by_arg[arg] = None 45 else: 46 diagnostic_by_arg[arg[0]] = arg[1] 47 48 def decorator(func: GeneratorMethod) -> GeneratorMethod: 49 @wraps(func) 50 def _func(generator: G, expression: E) -> str: 51 for arg_name, diagnostic in diagnostic_by_arg.items(): 52 generator._warn_unsupported_arg(expression, arg_name, diagnostic) 53 54 return func(generator, expression) 55 56 return _func 57 58 return decorator 59 60 61AFTER_HAVING_MODIFIER_TRANSFORMS: dict[str, t.Any] = { 62 "windows": lambda self, e: ( 63 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 64 if e.args.get("windows") 65 else "" 66 ), 67 "qualify": lambda self, e: self.sql(e, "qualify"), 68} 69 70 71_DISPATCH_CACHE: dict[type[Generator], dict[type[exp.Expr], t.Callable[..., str]]] = {} 72 73 74def _build_dispatch( 75 cls: type[Generator], 76) -> dict[type[exp.Expr], t.Callable[..., str]]: 77 dispatch: dict[type[exp.Expr], t.Callable[..., str]] = dict(cls.TRANSFORMS) 78 79 for attr_name in dir(cls): 80 if not attr_name.endswith("_sql") or attr_name.startswith("_"): 81 continue 82 83 expr_key = attr_name[:-4] 84 expr_cls = exp.EXPR_CLASSES.get(expr_key) 85 86 if expr_cls and expr_cls not in dispatch: 87 dispatch[expr_cls] = getattr(cls, attr_name) 88 89 return dispatch 90 91 92class Generator: 93 """ 94 Generator converts a given syntax tree to the corresponding SQL string. 95 96 Args: 97 pretty: Whether to format the produced SQL string. 98 Default: False. 99 identify: Determines when an identifier should be quoted. Possible values are: 100 False (default): Never quote, except in cases where it's mandatory by the dialect. 101 True: Always quote except for specials cases. 102 'safe': Only quote identifiers that are case insensitive. 103 normalize: Whether to normalize identifiers to lowercase. 104 Default: False. 105 pad: The pad size in a formatted string. For example, this affects the indentation of 106 a projection in a query, relative to its nesting level. 107 Default: 2. 108 indent: The indentation size in a formatted string. For example, this affects the 109 indentation of subqueries and filters under a `WHERE` clause. 110 Default: 2. 111 normalize_functions: How to normalize function names. Possible values are: 112 "upper" or True (default): Convert names to uppercase. 113 "lower": Convert names to lowercase. 114 False: Disables function name normalization. 115 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 116 Default ErrorLevel.WARN. 117 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 118 This is only relevant if unsupported_level is ErrorLevel.RAISE. 119 Default: 3 120 leading_comma: Whether the comma is leading or trailing in select expressions. 121 This is only relevant when generating in pretty mode. 122 Default: False 123 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 124 The default is on the smaller end because the length only represents a segment and not the true 125 line length. 126 Default: 80 127 comments: Whether to preserve comments in the output SQL code. 128 Default: True 129 """ 130 131 TRANSFORMS: t.ClassVar[dict[type[exp.Expr], t.Callable[..., str]]] = { 132 **JSON_PATH_PART_TRANSFORMS, 133 exp.Adjacent: lambda self, e: self.binary(e, "-|-"), 134 exp.AllowedValuesProperty: lambda self, e: ( 135 f"ALLOWED_VALUES {self.expressions(e, flat=True)}" 136 ), 137 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 138 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 139 exp.ArrayContainedBy: lambda self, e: self.binary(e, "<@"), 140 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 141 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 142 exp.AssumeColumnConstraint: lambda self, e: f"ASSUME ({self.sql(e, 'this')})", 143 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 144 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 145 exp.BinaryColumnConstraint: lambda *_: "BINARY", 146 exp.CaseSpecificColumnConstraint: lambda _, e: ( 147 f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC" 148 ), 149 exp.CalledOnNullInputProperty: lambda *_: "CALLED ON NULL INPUT", 150 exp.Ceil: lambda self, e: self.ceil_floor(e), 151 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 152 exp.CharacterSetProperty: lambda self, e: ( 153 f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}" 154 ), 155 exp.ClusteredColumnConstraint: lambda self, e: ( 156 f"CLUSTERED ({self.expressions(e, 'this', indent=False)})" 157 ), 158 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 159 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 160 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 161 exp.ConvertToCharset: lambda self, e: self.func( 162 "CONVERT", e.this, e.args["dest"], e.args.get("source") 163 ), 164 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 165 exp.CopyTagsProperty: lambda *_: "COPY TAGS", 166 exp.CredentialsProperty: lambda self, e: ( 167 f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})" 168 ), 169 exp.CurrentCatalog: lambda *_: "CURRENT_CATALOG", 170 exp.SessionUser: lambda *_: "SESSION_USER", 171 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 172 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 173 exp.ApiProperty: lambda *_: "API", 174 exp.ApplicationProperty: lambda *_: "APPLICATION", 175 exp.CatalogProperty: lambda *_: "CATALOG", 176 exp.ComputeProperty: lambda *_: "COMPUTE", 177 exp.DatabaseProperty: lambda *_: "DATABASE", 178 exp.DynamicProperty: lambda *_: "DYNAMIC", 179 exp.EmptyProperty: lambda *_: "EMPTY", 180 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 181 exp.EndStatement: lambda *_: "END", 182 exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})", 183 exp.HandlerProperty: lambda self, e: f"HANDLER {self.sql(e, 'this')}", 184 exp.ParameterStyleProperty: lambda self, e: f"PARAMETER STYLE {self.sql(e, 'this')}", 185 exp.EphemeralColumnConstraint: lambda self, e: ( 186 f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}" 187 ), 188 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 189 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 190 exp.Except: lambda self, e: self.set_operations(e), 191 exp.ExternalProperty: lambda *_: "EXTERNAL", 192 exp.Floor: lambda self, e: self.ceil_floor(e), 193 exp.Get: lambda self, e: self.get_put_sql(e), 194 exp.GlobalProperty: lambda *_: "GLOBAL", 195 exp.HeapProperty: lambda *_: "HEAP", 196 exp.HybridProperty: lambda *_: "HYBRID", 197 exp.IcebergProperty: lambda *_: "ICEBERG", 198 exp.IgnoreGrantsProperty: lambda *_: "IGNORE GRANTS", 199 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 200 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 201 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 202 exp.Intersect: lambda self, e: self.set_operations(e), 203 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 204 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DType.BIGINT)), 205 exp.JSONBContainsAnyTopKeys: lambda self, e: self.binary(e, "?|"), 206 exp.JSONBContainsAllTopKeys: lambda self, e: self.binary(e, "?&"), 207 exp.JSONBContainsTopKey: lambda self, e: self.binary(e, "?"), 208 exp.JSONBDeleteAtPath: lambda self, e: self.binary(e, "#-"), 209 exp.JSONBPathExists: lambda self, e: self.binary(e, "@?"), 210 exp.JSONObject: lambda self, e: self._jsonobject_sql(e), 211 exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e), 212 exp.LanguageProperty: lambda self, e: self.naked_property(e), 213 exp.LocationProperty: lambda self, e: self.naked_property(e), 214 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 215 exp.MaskingProperty: lambda *_: "MASKING", 216 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 217 exp.NetFunc: lambda self, e: f"NET.{self.sql(e, 'this')}", 218 exp.NetworkProperty: lambda *_: "NETWORK", 219 exp.NonClusteredColumnConstraint: lambda self, e: ( 220 f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})" 221 ), 222 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 223 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 224 exp.OnCommitProperty: lambda _, e: ( 225 f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS" 226 ), 227 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 228 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 229 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 230 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 231 exp.ExtendsLeft: lambda self, e: self.binary(e, "&<"), 232 exp.ExtendsRight: lambda self, e: self.binary(e, "&>"), 233 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 234 exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression), 235 exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression), 236 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 237 exp.PositionalColumn: lambda self, e: f"#{self.sql(e, 'this')}", 238 exp.ProjectionPolicyColumnConstraint: lambda self, e: ( 239 f"PROJECTION POLICY {self.sql(e, 'this')}" 240 ), 241 exp.InvisibleColumnConstraint: lambda self, e: "INVISIBLE", 242 exp.ZeroFillColumnConstraint: lambda self, e: "ZEROFILL", 243 exp.Put: lambda self, e: self.get_put_sql(e), 244 exp.RemoteWithConnectionModelProperty: lambda self, e: ( 245 f"REMOTE WITH CONNECTION {self.sql(e, 'this')}" 246 ), 247 exp.ReturnsProperty: lambda self, e: ( 248 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 249 ), 250 exp.RowAccessProperty: lambda *_: "ROW ACCESS", 251 exp.SafeFunc: lambda self, e: f"SAFE.{self.sql(e, 'this')}", 252 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 253 exp.SecureProperty: lambda *_: "SECURE", 254 exp.SecurityIntegrationProperty: lambda *_: "SECURITY", 255 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 256 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 257 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 258 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 259 exp.SqlReadWriteProperty: lambda _, e: e.name, 260 exp.SqlSecurityProperty: lambda self, e: f"SQL SECURITY {self.sql(e, 'this')}", 261 exp.StabilityProperty: lambda _, e: e.name, 262 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 263 exp.StreamingTableProperty: lambda *_: "STREAMING", 264 exp.StrictProperty: lambda *_: "STRICT", 265 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 266 exp.TableColumn: lambda self, e: self.sql(e.this), 267 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 268 exp.TemporaryProperty: lambda *_: "TEMPORARY", 269 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 270 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 271 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 272 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 273 exp.TransientProperty: lambda *_: "TRANSIENT", 274 exp.VirtualProperty: lambda *_: "VIRTUAL", 275 exp.TriggerExecute: lambda self, e: f"EXECUTE FUNCTION {self.sql(e, 'this')}", 276 exp.Union: lambda self, e: self.set_operations(e), 277 exp.UnloggedProperty: lambda *_: "UNLOGGED", 278 exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 279 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 280 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 281 exp.UtcDate: lambda self, e: self.sql(exp.CurrentDate(this=exp.Literal.string("UTC"))), 282 exp.UtcTime: lambda self, e: self.sql(exp.CurrentTime(this=exp.Literal.string("UTC"))), 283 exp.UtcTimestamp: lambda self, e: self.sql( 284 exp.CurrentTimestamp(this=exp.Literal.string("UTC")) 285 ), 286 exp.Variadic: lambda self, e: f"VARIADIC {self.sql(e, 'this')}", 287 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 288 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 289 exp.VolatileProperty: lambda *_: "VOLATILE", 290 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 291 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 292 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 293 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 294 exp.WithoutRowidProperty: lambda *_: "WITHOUT ROWID", 295 exp.ForceProperty: lambda *_: "FORCE", 296 } 297 298 # Whether null ordering is supported in order by 299 # True: Full Support, None: No support, False: No support for certain cases 300 # such as window specifications, aggregate functions etc 301 NULL_ORDERING_SUPPORTED: bool | None = True 302 303 # Window functions that support NULLS FIRST/LAST 304 WINDOW_FUNCS_WITH_NULL_ORDERING: t.ClassVar[tuple[type[exp.Expression], ...]] = () 305 306 # Window functions that require an ORDER BY in their window specification 307 WINDOW_FUNCS_REQUIRING_ORDER: t.ClassVar[tuple[type[exp.Expression], ...]] = () 308 309 # Whether ignore nulls is inside the agg or outside. 310 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 311 IGNORE_NULLS_IN_FUNC = False 312 313 # Whether IGNORE NULLS is placed before ORDER BY in the agg. 314 # FIRST(x IGNORE NULLS ORDER BY y) vs FIRST(x ORDER BY y IGNORE NULLS) 315 IGNORE_NULLS_BEFORE_ORDER = True 316 317 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 318 LOCKING_READS_SUPPORTED = False 319 320 # Whether the EXCEPT and INTERSECT operations can return duplicates 321 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 322 323 # Wrap derived values in parens, usually standard but spark doesn't support it 324 WRAP_DERIVED_VALUES = True 325 326 # Whether create function uses an AS before the RETURN 327 CREATE_FUNCTION_RETURN_AS = True 328 329 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 330 MATCHED_BY_SOURCE = True 331 332 # Whether MERGE ... WHEN MATCHED/NOT MATCHED THEN UPDATE/INSERT ... WHERE is supported 333 SUPPORTS_MERGE_WHERE = False 334 335 # First version supporting MERGE WITH SCHEMA EVOLUTION 336 MERGE_SCHEMA_EVOLUTION_MIN_VERSION: t.ClassVar[tuple[int, ...] | None] = None 337 338 # Whether MERGE uses ALL BY NAME instead of a star to update or insert all columns 339 MERGE_ALL_BY_NAME = False 340 341 # Whether the INTERVAL expression works only with values like '1 day' 342 SINGLE_STRING_INTERVAL = False 343 344 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 345 INTERVAL_ALLOWS_PLURAL_FORM = True 346 347 # Whether intervals in a REFRESH schedule (AutoRefreshProperty) are generated without the 348 # INTERVAL keyword, e.g. ClickHouse's REFRESH EVERY 30 SECOND 349 AUTO_REFRESH_BARE_INTERVALS = False 350 351 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 352 LIMIT_FETCH = "ALL" 353 354 # Whether limit and fetch allows expressions or just limits 355 LIMIT_ONLY_LITERALS = False 356 357 # Whether a table is allowed to be renamed with a db 358 RENAME_TABLE_WITH_DB = True 359 360 # The separator for grouping sets and rollups 361 GROUPINGS_SEP = "," 362 363 # Whether GROUPING SETS can follow GROUP BY expressions without a comma 364 SUPPORTS_GROUPING_SETS_AS_SUFFIX = False 365 366 # The string used for creating an index on a table 367 INDEX_ON = "ON" 368 369 # Separator for IN/OUT parameter mode (Oracle uses " " for "IN OUT", PostgreSQL uses "" for "INOUT") 370 INOUT_SEPARATOR = " " 371 372 # Whether join hints should be generated 373 JOIN_HINTS = True 374 375 # Whether directed joins are supported 376 DIRECTED_JOINS = False 377 378 # Whether top-k distance/similarity joins are supported 379 SUPPORTS_NEAREST_JOIN = False 380 381 # Whether MATCH_CONDITION in ASOF joins is supported 382 SUPPORTS_MATCH_CONDITION = False 383 384 # Whether ASOF JOIN MATCH_CONDITION should be folded into the ON clause 385 MATCH_CONDITION_IN_ON = False 386 387 # Whether table hints should be generated 388 TABLE_HINTS = True 389 390 # Whether query hints should be generated 391 QUERY_HINTS = True 392 393 # What kind of separator to use for query hints 394 QUERY_HINT_SEP = ", " 395 396 # Whether comparing against booleans (e.g. x IS TRUE) is supported 397 IS_BOOL_ALLOWED = True 398 399 # Whether casting a fractional number to an integer rounds it instead of truncating it 400 CAST_TO_INT_ROUNDS = False 401 402 # Whether the native integer division operator returns NULL for a zero divisor instead of raising 403 SAFE_INT_DIVISION = False 404 405 # The infix integer division operator, e.g. DIV in MySQL. If unset, IntDiv is a truncated division 406 INT_DIV_OPERATOR: str | None = None 407 408 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 409 DUPLICATE_KEY_UPDATE_WITH_SET = True 410 411 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 412 LIMIT_IS_TOP = False 413 414 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 415 RETURNING_END = True 416 417 # Whether to generate an unquoted value for EXTRACT's date part argument 418 EXTRACT_ALLOWS_QUOTES = True 419 420 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 421 TZ_TO_WITH_TIME_ZONE = False 422 423 # Whether the NVL2 function is supported 424 NVL2_SUPPORTED = True 425 426 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 427 SELECT_KINDS: t.ClassVar[tuple[str, ...]] = ("STRUCT", "VALUE") 428 429 # Whether VALUES statements can be used as derived tables. 430 # MySQL 5 and Redshift do not allow this, so when False, it will convert 431 # SELECT * VALUES into SELECT UNION 432 VALUES_AS_TABLE = True 433 434 # Whether COLUMN/COLUMNS keywords are included when adding columns with ALTER TABLE. 435 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 436 437 # Whether ALTER TABLE mutli-column additions are wrapped in parentheses. 438 ALTER_TABLE_ADD_COLUMNS_WRAPPED = True 439 440 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 441 UNNEST_WITH_ORDINALITY = True 442 443 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 444 SEMI_ANTI_JOIN_WITH_SIDE = True 445 446 # Whether to include the type of a computed column in the CREATE DDL 447 COMPUTED_COLUMN_WITH_TYPE = True 448 449 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 450 SUPPORTS_TABLE_COPY = True 451 452 # Whether parentheses are required around the table sample's expression 453 TABLESAMPLE_REQUIRES_PARENS = True 454 455 # Whether a table sample clause's size needs to be followed by the ROWS keyword 456 TABLESAMPLE_SIZE_IS_ROWS = True 457 458 # The keyword(s) to use when generating a sample clause 459 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 460 461 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 462 TABLESAMPLE_WITH_METHOD = True 463 464 # The keyword to use when specifying the seed of a sample clause 465 TABLESAMPLE_SEED_KEYWORD = "SEED" 466 467 # Whether the historical data clause (AT ... / BEFORE ...) is generated after the table alias 468 HISTORICAL_DATA_POST_ALIAS = False 469 470 # Whether COLLATE is a function instead of a binary operator 471 COLLATE_IS_FUNC = False 472 473 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 474 DATA_TYPE_SPECIFIERS_ALLOWED = False 475 476 # Whether conditions require booleans WHERE x = 0 vs WHERE x 477 ENSURE_BOOLS = False 478 479 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 480 CTE_RECURSIVE_KEYWORD_REQUIRED = True 481 482 # Whether CONCAT requires >1 arguments 483 SUPPORTS_SINGLE_ARG_CONCAT = True 484 485 # Whether LAST_DAY function supports a date part argument 486 LAST_DAY_SUPPORTS_DATE_PART = True 487 488 # Whether named columns are allowed in table aliases 489 SUPPORTS_TABLE_ALIAS_COLUMNS = True 490 491 # Whether named columns are allowed in CTE definitions 492 SUPPORTS_NAMED_CTE_COLUMNS = True 493 494 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 495 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 496 497 # Whether a (UN)PIVOT's alias is introduced with AS (Oracle rejects it, ORA-03048) 498 PIVOT_ALIAS_WITH_AS = True 499 500 # What delimiter to use for separating JSON key/value pairs 501 JSON_KEY_VALUE_PAIR_SEP = ":" 502 503 # INSERT OVERWRITE TABLE x override 504 INSERT_OVERWRITE = " OVERWRITE TABLE" 505 506 # Whether the SELECT .. INTO syntax is used instead of CTAS 507 SUPPORTS_SELECT_INTO = False 508 509 SUPPORTS_OPTIMIZE = False 510 SUPPORTS_EXECUTE_IMMEDIATE = True 511 512 # Whether UNLOGGED tables can be created 513 SUPPORTS_UNLOGGED_TABLES = False 514 515 # Whether the CREATE TABLE LIKE statement is supported 516 SUPPORTS_CREATE_TABLE_LIKE = True 517 518 # Whether ALTER TABLE ... MODIFY COLUMN column-redefinition syntax is supported 519 SUPPORTS_MODIFY_COLUMN = False 520 521 # Whether ALTER TABLE ... CHANGE COLUMN column-rename-and-redefine syntax is supported 522 SUPPORTS_CHANGE_COLUMN = False 523 524 # Whether ALTER COLUMN can set a column's nullability together with its type 525 SUPPORTS_ALTER_COLUMN_NULLABILITY = False 526 527 # Whether ALTER COLUMN IF EXISTS is supported 528 SUPPORTS_ALTER_COLUMN_IF_EXISTS = False 529 530 # Whether the LikeProperty needs to be specified inside of the schema clause 531 LIKE_PROPERTY_INSIDE_SCHEMA = False 532 533 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 534 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 535 MULTI_ARG_DISTINCT = True 536 537 # Whether the JSON extraction operators expect a value of type JSON 538 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 539 540 # Whether the .^ operator can select nested JSON objects 541 SUPPORTS_NESTED_JSON_SELECT = False 542 543 # Whether bracketed keys like ["foo"] are supported in JSON paths 544 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 545 546 # Whether to escape keys using single quotes in JSON paths 547 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 548 549 # Whether a quoted JSON path key (e.g. from a quoted identifier or ['key'] bracket) must be 550 # rendered in bracket form to preserve its case-sensitivity, even if it would otherwise match 551 # SAFE_JSON_PATH_KEY_RE and render as a bare dotted key. Needed for dialects like Databricks 552 # where a bare colon key is case-insensitive but a bracketed key is case-sensitive. 553 JSON_PATH_KEY_QUOTED_FORCES_BRACKETS = False 554 555 # The JSONPathPart expressions supported by this dialect 556 SUPPORTED_JSON_PATH_PARTS: t.ClassVar = ALL_JSON_PATH_PARTS.copy() 557 558 # Whether any(f(x) for x in array) can be implemented by this dialect 559 CAN_IMPLEMENT_ARRAY_ANY = False 560 561 # Whether the function TO_NUMBER is supported 562 SUPPORTS_TO_NUMBER = True 563 564 # Whether EXCLUDE in window specification is supported 565 SUPPORTS_WINDOW_EXCLUDE = False 566 567 # Whether or not set op modifiers apply to the outer set op or select. 568 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 569 # True means limit 1 happens after the set op, False means it it happens on y. 570 SET_OP_MODIFIERS = True 571 572 # Whether a SELECT operand can have a branch-local LIMIT/TOP without parentheses. 573 SET_OP_LIMITS = False 574 575 # Whether set operation operands can be parenthesized without a SELECT wrapper. 576 SET_OP_PARENTHESIZED_OPERANDS = True 577 578 # Whether parameters from COPY statement are wrapped in parentheses 579 COPY_PARAMS_ARE_WRAPPED = True 580 581 # Whether values of params are set with "=" token or empty space 582 COPY_PARAMS_EQ_REQUIRED = False 583 584 # Whether COPY statement has INTO keyword 585 COPY_HAS_INTO_KEYWORD = True 586 587 # Whether the conditional TRY(expression) function is supported 588 TRY_SUPPORTED = True 589 590 # Whether the UESCAPE syntax in unicode strings is supported 591 SUPPORTS_UESCAPE = True 592 593 # Function used to replace escaped unicode codes in unicode strings 594 UNICODE_SUBSTITUTE: t.ClassVar[t.Any] = None 595 596 # The keyword to use when generating a star projection with excluded columns 597 STAR_EXCEPT = "EXCEPT" 598 599 # The HEX function name 600 HEX_FUNC = "HEX" 601 602 # Function that constructs a binary value from a hex-encoded byte string. 603 BYTE_STRING_FUNCTION = "" 604 605 # The keywords to use when prefixing & separating WITH based properties 606 WITH_PROPERTIES_PREFIX = "WITH" 607 608 # Whether to quote the generated expression of exp.JsonPath 609 QUOTE_JSON_PATH = True 610 611 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 612 PAD_FILL_PATTERN_IS_REQUIRED = False 613 614 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 615 SUPPORTS_EXPLODING_PROJECTIONS = True 616 617 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 618 ARRAY_CONCAT_IS_VAR_LEN = True 619 620 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 621 SUPPORTS_CONVERT_TIMEZONE = False 622 623 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 624 SUPPORTS_MEDIAN = True 625 626 # Whether UNIX_SECONDS(timestamp) is supported 627 SUPPORTS_UNIX_SECONDS = False 628 629 # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>) 630 ALTER_SET_WRAPPED = False 631 632 # Whether to normalize the date parts in EXTRACT(<date_part> FROM <expr>) into a common representation 633 # using the dialect's general aliases as a fallback for parts without an EXTRACT-specific mapping. 634 # For instance, to extract the day of week in ISO semantics, one can use ISODOW, DAYOFWEEKISO etc depending on the dialect. 635 # TODO: The normalization should be done by default once we've tested it across all dialects. 636 NORMALIZE_EXTRACT_DATE_PARTS = False 637 638 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 639 PARSE_JSON_NAME: str | None = "PARSE_JSON" 640 641 # The function name of the exp.ArraySize expression 642 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 643 644 DAYOFWEEK_NAME = "" 645 DAYOFWEEK_ZERO_BASED = False 646 647 # Override for sample variance; otherwise use the expression's function name. 648 VARIANCE_NAME: str = "" 649 650 # Whether VARIANCE natively returns zero for a single non-NULL value. 651 VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE = False 652 653 # The syntax to use when altering the type of a column 654 ALTER_SET_TYPE = "SET DATA TYPE" 655 656 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 657 # None -> Doesn't support it at all 658 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 659 # True (Postgres) -> Explicitly requires it 660 ARRAY_SIZE_DIM_REQUIRED: bool | None = None 661 662 # Whether a multi-argument DECODE(...) function is supported. If not, a CASE expression is generated 663 SUPPORTS_DECODE_CASE = True 664 665 # Whether CHR / CHAR accepts multiple code points, e.g. CHAR(72, 105). If not, the calls are concatenated 666 SUPPORTS_MULTI_ARG_CHR = True 667 668 # Whether SYMMETRIC and ASYMMETRIC flags are supported with BETWEEN expression 669 SUPPORTS_BETWEEN_FLAGS = False 670 671 # Whether LIKE and ILIKE support quantifiers such as LIKE ANY/ALL/SOME 672 SUPPORTS_LIKE_QUANTIFIERS = True 673 674 # Prefix which is appended to exp.Table expressions in MATCH AGAINST 675 MATCH_AGAINST_TABLE_PREFIX: str | None = None 676 677 # Whether to include the VARIABLE keyword for SET assignments 678 SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD = False 679 680 # The keyword to use for default value assignment in DECLARE statements 681 DECLARE_DEFAULT_ASSIGNMENT = "=" 682 683 # Whether FROM is supported in UPDATE statements or if joins must be generated instead, e.g: 684 # Supported (Postgres, Doris etc): UPDATE t1 SET t1.a = t2.b FROM t2 685 # Unsupported (MySQL, SingleStore): UPDATE t1 JOIN t2 ON TRUE SET t1.a = t2.b 686 UPDATE_STATEMENT_SUPPORTS_FROM = True 687 688 # Whether SELECT *, ... EXCLUDE requires wrapping in a subquery for transpilation. 689 STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = True 690 691 # Whether DROP and ALTER statements against Iceberg tables include 'ICEBERG', e.g.: 692 # - Snowflake: DROP ICEBERG TABLE a.b; 693 # - DuckDB: DROP TABLE a.b; 694 SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY = True 695 696 TYPE_MAPPING: t.ClassVar = { 697 exp.DType.DATETIME2: "TIMESTAMP", 698 exp.DType.NCHAR: "CHAR", 699 exp.DType.NVARCHAR: "VARCHAR", 700 exp.DType.MEDIUMTEXT: "TEXT", 701 exp.DType.LONGTEXT: "TEXT", 702 exp.DType.TINYTEXT: "TEXT", 703 exp.DType.BLOB: "VARBINARY", 704 exp.DType.MEDIUMBLOB: "BLOB", 705 exp.DType.LONGBLOB: "BLOB", 706 exp.DType.TINYBLOB: "BLOB", 707 exp.DType.INET: "INET", 708 exp.DType.ROWVERSION: "VARBINARY", 709 exp.DType.SMALLDATETIME: "TIMESTAMP", 710 } 711 712 UNSUPPORTED_TYPES: t.ClassVar[set[exp.DType]] = set() 713 714 # mapping of DType to its default parameters, bounds 715 TYPE_PARAM_SETTINGS: t.ClassVar[ 716 dict[exp.DType, tuple[tuple[int, ...], tuple[int | None, ...]]] 717 ] = {} 718 719 TIME_PART_SINGULARS: t.ClassVar = { 720 "MICROSECONDS": "MICROSECOND", 721 "SECONDS": "SECOND", 722 "MINUTES": "MINUTE", 723 "HOURS": "HOUR", 724 "DAYS": "DAY", 725 "WEEKS": "WEEK", 726 "MONTHS": "MONTH", 727 "QUARTERS": "QUARTER", 728 "YEARS": "YEAR", 729 } 730 731 AFTER_HAVING_MODIFIER_TRANSFORMS: t.ClassVar = { 732 "cluster": lambda self, e: self.sql(e, "cluster"), 733 "distribute": lambda self, e: self.sql(e, "distribute"), 734 "sort": lambda self, e: self.sql(e, "sort"), 735 **AFTER_HAVING_MODIFIER_TRANSFORMS, 736 } 737 738 TOKEN_MAPPING: t.ClassVar[dict[TokenType, str]] = {} 739 740 STRUCT_DELIMITER: t.ClassVar = ("<", ">") 741 742 PARAMETER_TOKEN = "@" 743 NAMED_PLACEHOLDER_TOKEN = ":" 744 745 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.ClassVar[set[str]] = set() 746 747 PROPERTIES_LOCATION: t.ClassVar = { 748 exp.AggregateKeyProperty: exp.Properties.Location.POST_SCHEMA, 749 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 750 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 751 exp.ApiProperty: exp.Properties.Location.POST_CREATE, 752 exp.ApplicationProperty: exp.Properties.Location.POST_CREATE, 753 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 754 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 755 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 756 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 757 exp.CalledOnNullInputProperty: exp.Properties.Location.POST_SCHEMA, 758 exp.CatalogProperty: exp.Properties.Location.POST_CREATE, 759 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 760 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 761 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 762 exp.ComputeProperty: exp.Properties.Location.POST_CREATE, 763 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 764 exp.CopyTagsProperty: exp.Properties.Location.POST_SCHEMA, 765 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 766 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 767 exp.ClusterProperty: exp.Properties.Location.POST_SCHEMA, 768 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 769 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 770 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 771 exp.DatabaseProperty: exp.Properties.Location.POST_CREATE, 772 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 773 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 774 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 775 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 776 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 777 exp.DistKeyProperty: exp.Properties.Location.UNSUPPORTED, 778 exp.DistStyleProperty: exp.Properties.Location.UNSUPPORTED, 779 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 780 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 781 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 782 exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA, 783 exp.HandlerProperty: exp.Properties.Location.POST_SCHEMA, 784 exp.ParameterStyleProperty: exp.Properties.Location.POST_SCHEMA, 785 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 786 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 787 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 788 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 789 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 790 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 791 exp.HeapProperty: exp.Properties.Location.POST_WITH, 792 exp.HybridProperty: exp.Properties.Location.POST_CREATE, 793 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 794 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 795 exp.IgnoreGrantsProperty: exp.Properties.Location.POST_SCHEMA, 796 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 797 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 798 exp.InteractiveProperty: exp.Properties.Location.UNSUPPORTED, 799 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 800 exp.JournalProperty: exp.Properties.Location.POST_NAME, 801 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 802 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 803 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 804 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 805 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 806 exp.LogProperty: exp.Properties.Location.POST_NAME, 807 exp.MaskingProperty: exp.Properties.Location.POST_CREATE, 808 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 809 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 810 exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA, 811 exp.NetworkProperty: exp.Properties.Location.POST_CREATE, 812 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 813 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 814 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 815 exp.OptionsProperty: exp.Properties.Location.UNSUPPORTED, 816 exp.Order: exp.Properties.Location.POST_SCHEMA, 817 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 818 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 819 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 820 exp.PhysicalProperty: exp.Properties.Location.UNSUPPORTED, 821 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 822 exp.Property: exp.Properties.Location.POST_WITH, 823 exp.RefreshTriggerProperty: exp.Properties.Location.POST_SCHEMA, 824 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 825 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 826 exp.RollupProperty: exp.Properties.Location.UNSUPPORTED, 827 exp.RowAccessProperty: exp.Properties.Location.UNSUPPORTED, 828 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 829 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 830 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 831 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 832 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 833 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 834 exp.SecurityIntegrationProperty: exp.Properties.Location.POST_CREATE, 835 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 836 exp.Set: exp.Properties.Location.POST_SCHEMA, 837 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 838 exp.SetProperty: exp.Properties.Location.POST_CREATE, 839 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 840 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 841 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 842 exp.TriggerProperties: exp.Properties.Location.POST_EXPRESSION, 843 exp.SortKeyProperty: exp.Properties.Location.UNSUPPORTED, 844 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 845 exp.SqlSecurityProperty: exp.Properties.Location.POST_SCHEMA, 846 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 847 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 848 exp.StorageProperty: exp.Properties.Location.UNSUPPORTED, 849 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 850 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 851 exp.Tags: exp.Properties.Location.POST_WITH, 852 exp.TableSpaceProperty: exp.Properties.Location.UNSUPPORTED, 853 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 854 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 855 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 856 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 857 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 858 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 859 exp.UsingProperty: exp.Properties.Location.POST_EXPRESSION, 860 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 861 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 862 exp.VirtualProperty: exp.Properties.Location.POST_CREATE, 863 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 864 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 865 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 866 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 867 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 868 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 869 exp.WithoutRowidProperty: exp.Properties.Location.UNSUPPORTED, 870 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 871 } 872 873 # Keywords that can't be used as unquoted identifier names 874 RESERVED_KEYWORDS: t.ClassVar[set[str]] = set() 875 876 # Exprs whose comments are separated from them for better formatting 877 WITH_SEPARATED_COMMENTS: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 878 exp.Command, 879 exp.Create, 880 exp.Describe, 881 exp.Delete, 882 exp.Drop, 883 exp.From, 884 exp.Insert, 885 exp.Join, 886 exp.MultitableInserts, 887 exp.Order, 888 exp.Group, 889 exp.Having, 890 exp.Select, 891 exp.SetOperation, 892 exp.Update, 893 exp.Where, 894 exp.With, 895 ) 896 897 # Exprs that should not have their comments generated in maybe_comment 898 EXCLUDE_COMMENTS: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 899 exp.Binary, 900 exp.SetOperation, 901 ) 902 903 # Exprs that can remain unwrapped when appearing in the context of an INTERVAL 904 UNWRAPPED_INTERVAL_VALUES: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 905 exp.Column, 906 exp.Literal, 907 exp.Neg, 908 exp.Paren, 909 ) 910 911 PARAMETERIZABLE_TEXT_TYPES: t.ClassVar = { 912 exp.DType.NVARCHAR, 913 exp.DType.VARCHAR, 914 exp.DType.CHAR, 915 exp.DType.NCHAR, 916 } 917 918 # Exprs that need to have all CTEs under them bubbled up to them 919 EXPRESSIONS_WITHOUT_NESTED_CTES: t.ClassVar[set[type[exp.Expr]]] = set() 920 921 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = () 922 923 MOD_OPERATOR = "%" 924 925 # Unqualified operators that can be written without OPERATOR(...). 926 BARE_OPERATORS: t.ClassVar[set[str]] = set() 927 928 # Infix operators that bind at least as tightly as %, so a Mod on their right side needs parentheses 929 MOD_PAREN_PARENT_TYPES: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 930 exp.Mul, 931 exp.Div, 932 exp.IntDiv, 933 exp.Mod, 934 ) 935 936 # ALTER options that follow the others without a comma, e.g. MySQL's 937 # ENGINE=InnoDB PARTITION BY LIST (...) or StarRocks' PARTITION BY ... DISTRIBUTED BY ... 938 ALTER_PARTITION_OPTIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = () 939 940 SAFE_JSON_PATH_KEY_RE: t.ClassVar = exp.SAFE_IDENTIFIER_RE 941 942 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 943 944 __slots__ = ( 945 "pretty", 946 "identify", 947 "normalize", 948 "pad", 949 "_indent", 950 "normalize_functions", 951 "unsupported_level", 952 "max_unsupported", 953 "leading_comma", 954 "max_text_width", 955 "comments", 956 "dialect", 957 "unsupported_messages", 958 "_escaped_quote_end", 959 "_escaped_byte_quote_end", 960 "_escaped_identifier_end", 961 "_identifier_escaped_sequences", 962 "_next_name", 963 "_identifier_start", 964 "_identifier_end", 965 "_quote_json_path_key_using_brackets", 966 "_dispatch", 967 ) 968 969 def __init__( 970 self, 971 pretty: bool | int | None = None, 972 identify: str | bool = False, 973 normalize: bool = False, 974 pad: int = 2, 975 indent: int = 2, 976 normalize_functions: str | bool | None = None, 977 unsupported_level: ErrorLevel = ErrorLevel.WARN, 978 max_unsupported: int = 3, 979 leading_comma: bool = False, 980 max_text_width: int = 80, 981 comments: bool = True, 982 dialect: DialectType = None, 983 ): 984 import sqlglot 985 import sqlglot.dialects.dialect 986 987 self.pretty = pretty if pretty is not None else sqlglot.pretty 988 self.identify = identify 989 self.normalize = normalize 990 self.pad = pad 991 self._indent = indent 992 self.unsupported_level = unsupported_level 993 self.max_unsupported = max_unsupported 994 self.leading_comma = leading_comma 995 self.max_text_width = max_text_width 996 self.comments = comments 997 self.dialect = sqlglot.dialects.dialect.Dialect.get_or_raise(dialect) 998 999 # This is both a Dialect property and a Generator argument, so we prioritize the latter 1000 self.normalize_functions = ( 1001 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 1002 ) 1003 1004 self.unsupported_messages: list[str] = [] 1005 self._escaped_quote_end: str = ( 1006 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 1007 ) 1008 self._escaped_byte_quote_end: str = ( 1009 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.BYTE_END 1010 if self.dialect.BYTE_END 1011 else "" 1012 ) 1013 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 1014 self._identifier_escaped_sequences = self.dialect.IDENTIFIER_ESCAPED_SEQUENCES 1015 1016 self._next_name = name_sequence("_t") 1017 1018 self._identifier_start = self.dialect.IDENTIFIER_START 1019 self._identifier_end = self.dialect.IDENTIFIER_END 1020 1021 self._quote_json_path_key_using_brackets = True 1022 1023 cls = type(self) 1024 dispatch = _DISPATCH_CACHE.get(cls) 1025 if dispatch is None: 1026 dispatch = _build_dispatch(cls) 1027 _DISPATCH_CACHE[cls] = dispatch 1028 self._dispatch = dispatch 1029 1030 def generate(self, expression: exp.Expr, copy: bool = True) -> str: 1031 """ 1032 Generates the SQL string corresponding to the given syntax tree. 1033 1034 Args: 1035 expression: The syntax tree. 1036 copy: Whether to copy the expression. The generator performs mutations so 1037 it is safer to copy. 1038 1039 Returns: 1040 The SQL string corresponding to `expression`. 1041 """ 1042 if copy: 1043 expression = expression.copy() 1044 1045 expression = self.preprocess(expression) 1046 1047 self.unsupported_messages = [] 1048 sql = self.sql(expression) 1049 # A trailing newline in a raw command can terminate a line comment. 1050 sql = sql.lstrip() if isinstance(expression, exp.Command) else sql.strip() 1051 1052 if self.pretty: 1053 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 1054 1055 if self.unsupported_level == ErrorLevel.IGNORE: 1056 return sql 1057 1058 if self.unsupported_level == ErrorLevel.WARN: 1059 for msg in self.unsupported_messages: 1060 logger.warning(msg) 1061 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 1062 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 1063 1064 return sql 1065 1066 def preprocess(self, expression: exp.Expr) -> exp.Expr: 1067 """Apply generic preprocessing transformations to a given expression.""" 1068 expression = self._move_ctes_to_top_level(expression) 1069 1070 if self.ENSURE_BOOLS: 1071 import sqlglot.transforms 1072 1073 expression = sqlglot.transforms.ensure_bools(expression) 1074 1075 return expression 1076 1077 def _move_ctes_to_top_level(self, expression: E) -> E: 1078 if ( 1079 not expression.parent 1080 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 1081 and any(node.parent is not expression for node in expression.find_all(exp.With)) 1082 ): 1083 import sqlglot.transforms 1084 1085 expression = sqlglot.transforms.move_ctes_to_top_level(expression) 1086 return expression 1087 1088 def _warn_unsupported_arg( 1089 self, expression: exp.Expr, arg_name: str, diagnostic: str | None = None 1090 ) -> None: 1091 if expression.args.get(arg_name): 1092 self.unsupported( 1093 diagnostic 1094 or UNSUPPORTED_TEMPLATE.format( 1095 arg_name, expression.__class__.__name__, self.dialect.__class__.__name__ 1096 ) 1097 ) 1098 1099 def unsupported(self, message: str) -> None: 1100 if self.unsupported_level == ErrorLevel.IMMEDIATE: 1101 raise UnsupportedError(message) 1102 self.unsupported_messages.append(message) 1103 1104 def sep(self, sep: str = " ") -> str: 1105 return f"{sep.strip()}\n" if self.pretty else sep 1106 1107 def seg(self, sql: str, sep: str = " ") -> str: 1108 return f"{self.sep(sep)}{sql}" 1109 1110 def sanitize_comment(self, comment: str) -> str: 1111 comment = " " + comment if comment[0].strip() else comment 1112 comment = comment + " " if comment[-1].strip() else comment 1113 1114 # Escape block comment markers to prevent premature closure or unintended nesting. 1115 # This is necessary because single-line comments (--) are converted to block comments 1116 # (/* */) on output, and any */ in the original text would close the comment early. 1117 comment = comment.replace("*/", "* /").replace("/*", "/ *") 1118 1119 return comment 1120 1121 def maybe_comment( 1122 self, 1123 sql: str, 1124 expression: exp.Expr | None = None, 1125 comments: list[str] | None = None, 1126 separated: bool = False, 1127 ) -> str: 1128 comments = ( 1129 ((expression and expression.comments) if comments is None else comments) # type: ignore 1130 if self.comments 1131 else None 1132 ) 1133 1134 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 1135 return sql 1136 1137 comments_list = [ 1138 f"/*{self._replace_line_breaks(self.sanitize_comment(comment))}*/" 1139 for comment in comments 1140 if comment 1141 ] 1142 1143 if not comments_list: 1144 return sql 1145 1146 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 1147 comments_sql = self.sep().join(comments_list) 1148 return ( 1149 f"{self.sep()}{comments_sql}{sql}" 1150 if not sql or sql[0].isspace() 1151 else f"{comments_sql}{self.sep()}{sql}" 1152 ) 1153 1154 return f"{sql} {' '.join(comments_list)}" 1155 1156 def wrap(self, expression: exp.Expr | str) -> str: 1157 this_sql = ( 1158 self.sql(expression) 1159 if isinstance(expression, exp.UNWRAPPED_QUERIES) 1160 else self.sql(expression, "this") 1161 ) 1162 if not this_sql: 1163 return "()" 1164 1165 this_sql = self.indent(this_sql, level=1, pad=0) 1166 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 1167 1168 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 1169 original = self.identify 1170 self.identify = False 1171 result = func(*args, **kwargs) 1172 self.identify = original 1173 return result 1174 1175 def normalize_func(self, name: str) -> str: 1176 if self.normalize_functions == "upper" or self.normalize_functions is True: 1177 return name.upper() 1178 if self.normalize_functions == "lower": 1179 return name.lower() 1180 return name 1181 1182 def indent( 1183 self, 1184 sql: str, 1185 level: int = 0, 1186 pad: int | None = None, 1187 skip_first: bool = False, 1188 skip_last: bool = False, 1189 ) -> str: 1190 if not self.pretty or not sql: 1191 return sql 1192 1193 pad = self.pad if pad is None else pad 1194 lines = sql.split("\n") 1195 1196 return "\n".join( 1197 ( 1198 line 1199 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 1200 else f"{' ' * (level * self._indent + pad)}{line}" 1201 ) 1202 for i, line in enumerate(lines) 1203 ) 1204 1205 def sql( 1206 self, 1207 expression: str | exp.Expr | None, 1208 key: str | None = None, 1209 comment: bool = True, 1210 ) -> str: 1211 if not expression: 1212 return "" 1213 1214 if isinstance(expression, str): 1215 return expression 1216 1217 if key: 1218 value = expression.args.get(key) 1219 if value: 1220 return self.sql(value) 1221 return "" 1222 1223 handler = self._dispatch.get(expression.__class__) 1224 1225 if handler: 1226 sql = handler(self, expression) 1227 elif isinstance(expression, exp.Func): 1228 sql = self.function_fallback_sql(expression) 1229 elif isinstance(expression, exp.Property): 1230 sql = self.property_sql(expression) 1231 else: 1232 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 1233 1234 return self.maybe_comment(sql, expression) if self.comments and comment else sql 1235 1236 def uncache_sql(self, expression: exp.Uncache) -> str: 1237 table = self.sql(expression, "this") 1238 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 1239 return f"UNCACHE TABLE{exists_sql} {table}" 1240 1241 def cache_sql(self, expression: exp.Cache) -> str: 1242 lazy = " LAZY" if expression.args.get("lazy") else "" 1243 table = self.sql(expression, "this") 1244 options = expression.args.get("options") 1245 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 1246 sql = self.sql(expression, "expression") 1247 sql = f" AS{self.sep()}{sql}" if sql else "" 1248 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 1249 return self.prepend_ctes(expression, sql) 1250 1251 def characterset_sql(self, expression: exp.CharacterSet) -> str: 1252 default = "DEFAULT " if expression.args.get("default") else "" 1253 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 1254 1255 def column_parts(self, expression: exp.Column) -> str: 1256 if expression.args.get("shadow") and self.dialect.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES: 1257 # The qualifier would be captured by a colliding projection alias (see qualify_columns) 1258 return self.sql(expression, "this") 1259 1260 return ".".join( 1261 self.sql(part) 1262 for part in ( 1263 expression.args.get("catalog"), 1264 expression.args.get("db"), 1265 expression.args.get("table"), 1266 expression.args.get("this"), 1267 ) 1268 if part 1269 ) 1270 1271 def column_sql(self, expression: exp.Column) -> str: 1272 join_mark = " (+)" if expression.args.get("join_mark") else "" 1273 1274 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 1275 join_mark = "" 1276 self.unsupported("Outer join syntax using the (+) operator is not supported.") 1277 1278 return f"{self.column_parts(expression)}{join_mark}" 1279 1280 def pseudocolumn_sql(self, expression: exp.Pseudocolumn) -> str: 1281 return self.column_sql(expression) 1282 1283 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 1284 this = self.sql(expression, "this") 1285 this = f" {this}" if this else "" 1286 position = self.sql(expression, "position") 1287 return f"{position}{this}" 1288 1289 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 1290 column = self.sql(expression, "this") 1291 kind = self.sql(expression, "kind") 1292 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 1293 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 1294 kind = f"{sep}{kind}" if kind else "" 1295 constraints = f" {constraints}" if constraints else "" 1296 position = self.sql(expression, "position") 1297 position = f" {position}" if position else "" 1298 1299 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1300 kind = "" 1301 1302 return f"{exists}{column}{kind}{constraints}{position}" 1303 1304 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 1305 this = self.sql(expression, "this") 1306 kind_sql = self.sql(expression, "kind").strip() 1307 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 1308 1309 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1310 this = self.sql(expression, "this") 1311 if expression.args.get("not_null"): 1312 persisted = " PERSISTED NOT NULL" 1313 elif expression.args.get("persisted"): 1314 persisted = " PERSISTED" 1315 else: 1316 persisted = "" 1317 1318 return f"AS {this}{persisted}" 1319 1320 def autoincrementcolumnconstraint_sql(self, _: exp.AutoIncrementColumnConstraint) -> str: 1321 return self.token_sql(TokenType.AUTO_INCREMENT) 1322 1323 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1324 if isinstance(expression.this, list): 1325 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1326 else: 1327 this = self.sql(expression, "this") 1328 1329 return f"COMPRESS {this}" 1330 1331 def generatedasidentitycolumnconstraint_sql( 1332 self, expression: exp.GeneratedAsIdentityColumnConstraint 1333 ) -> str: 1334 this = "" 1335 if expression.this is not None: 1336 on_null = " ON NULL" if expression.args.get("on_null") else "" 1337 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1338 1339 start = expression.args.get("start") 1340 start = f"START WITH {start}" if start else "" 1341 increment = expression.args.get("increment") 1342 increment = f" INCREMENT BY {increment}" if increment else "" 1343 minvalue = expression.args.get("minvalue") 1344 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1345 maxvalue = expression.args.get("maxvalue") 1346 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1347 cycle = expression.args.get("cycle") 1348 cycle_sql = "" 1349 1350 if cycle is not None: 1351 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1352 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1353 1354 sequence_opts = "" 1355 if start or increment or cycle_sql: 1356 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1357 sequence_opts = f" ({sequence_opts.strip()})" 1358 1359 expr = self.sql(expression, "expression") 1360 expr = f"({expr})" if expr else "IDENTITY" 1361 1362 return f"GENERATED{this} AS {expr}{sequence_opts}" 1363 1364 def generatedasrowcolumnconstraint_sql( 1365 self, expression: exp.GeneratedAsRowColumnConstraint 1366 ) -> str: 1367 start = "START" if expression.args.get("start") else "END" 1368 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1369 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1370 1371 def periodforsystemtimeconstraint_sql( 1372 self, expression: exp.PeriodForSystemTimeConstraint 1373 ) -> str: 1374 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1375 1376 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1377 on_conflict = self.sql(expression, "on_conflict") 1378 on_conflict = f" {on_conflict}" if on_conflict else "" 1379 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL{on_conflict}" 1380 1381 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1382 on_conflict = self.sql(expression, "on_conflict") 1383 on_conflict = f" {on_conflict}" if on_conflict else "" 1384 desc = expression.args.get("desc") 1385 if desc is not None: 1386 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}{on_conflict}" 1387 options = self.expressions(expression, key="options", flat=True, sep=" ") 1388 options = f" {options}" if options else "" 1389 include = self.sql(expression, "include") 1390 return f"PRIMARY KEY{on_conflict}{include}{options}" 1391 1392 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1393 this = self.sql(expression, "this") 1394 this = f" {this}" if this else "" 1395 index_type = expression.args.get("index_type") 1396 index_type = f" USING {index_type}" if index_type else "" 1397 on_conflict = self.sql(expression, "on_conflict") 1398 on_conflict = f" {on_conflict}" if on_conflict else "" 1399 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1400 options = self.expressions(expression, key="options", flat=True, sep=" ") 1401 options = f" {options}" if options else "" 1402 include = self.sql(expression, "include") 1403 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{include}{options}" 1404 1405 def inoutcolumnconstraint_sql(self, expression: exp.InOutColumnConstraint) -> str: 1406 input_ = expression.args.get("input_") 1407 output = expression.args.get("output") 1408 variadic = expression.args.get("variadic") 1409 1410 # VARIADIC is mutually exclusive with IN/OUT/INOUT 1411 if variadic: 1412 return "VARIADIC" 1413 1414 if input_ and output: 1415 return f"IN{self.INOUT_SEPARATOR}OUT" 1416 if input_: 1417 return "IN" 1418 if output: 1419 return "OUT" 1420 1421 return "" 1422 1423 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1424 return self.sql(expression, "this") 1425 1426 def create_sql(self, expression: exp.Create) -> str: 1427 kind = self.sql(expression, "kind") 1428 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1429 1430 properties = expression.args.get("properties") 1431 1432 if ( 1433 kind == "TRIGGER" 1434 and properties 1435 and properties.expressions 1436 and isinstance(properties.expressions[0], exp.TriggerProperties) 1437 and properties.expressions[0].args.get("constraint") 1438 ): 1439 kind = f"CONSTRAINT {kind}" 1440 1441 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1442 1443 this = self.createable_sql(expression, properties_locs) 1444 1445 properties_sql = "" 1446 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1447 exp.Properties.Location.POST_WITH 1448 ): 1449 props_ast = exp.Properties( 1450 expressions=[ 1451 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1452 *properties_locs[exp.Properties.Location.POST_WITH], 1453 ] 1454 ) 1455 props_ast.parent = expression 1456 properties_sql = self.sql(props_ast) 1457 1458 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1459 properties_sql = self.sep() + properties_sql 1460 elif not self.pretty: 1461 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1462 properties_sql = f" {properties_sql}" 1463 1464 begin = " BEGIN" if expression.args.get("begin") else "" 1465 1466 expression_sql = self.sql(expression, "expression") 1467 if expression_sql: 1468 expression_sql = f"{begin}{self.sep()}{expression_sql}" 1469 1470 if not isinstance(expression.expression, exp.MacroOverloads) and ( 1471 self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return) 1472 ): 1473 postalias_props_sql = "" 1474 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1475 postalias_props_sql = self.properties( 1476 exp.Properties( 1477 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1478 ), 1479 wrapped=False, 1480 ) 1481 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1482 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1483 1484 postindex_props_sql = "" 1485 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1486 postindex_props_sql = self.properties( 1487 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1488 wrapped=False, 1489 prefix=" ", 1490 ) 1491 1492 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1493 indexes = f" {indexes}" if indexes else "" 1494 index_sql = indexes + postindex_props_sql 1495 1496 replace = " OR REPLACE" if expression.args.get("replace") else "" 1497 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1498 unique = " UNIQUE" if expression.args.get("unique") else "" 1499 1500 clustered = expression.args.get("clustered") 1501 if clustered is None: 1502 clustered_sql = "" 1503 elif clustered: 1504 clustered_sql = " CLUSTERED COLUMNSTORE" 1505 else: 1506 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1507 1508 postcreate_props_sql = "" 1509 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1510 postcreate_props_sql = self.properties( 1511 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1512 sep=" ", 1513 prefix=" ", 1514 wrapped=False, 1515 ) 1516 1517 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1518 1519 postexpression_props_sql = "" 1520 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1521 postexpression_props_sql = self.properties( 1522 exp.Properties( 1523 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1524 ), 1525 sep=" ", 1526 prefix=" ", 1527 wrapped=False, 1528 ) 1529 1530 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1531 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1532 no_schema_binding = ( 1533 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1534 ) 1535 1536 clone = self.sql(expression, "clone") 1537 clone = f" {clone}" if clone else "" 1538 1539 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1540 properties_expression = f"{expression_sql}{properties_sql}" 1541 else: 1542 properties_expression = f"{properties_sql}{expression_sql}" 1543 1544 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1545 return self.prepend_ctes(expression, expression_sql) 1546 1547 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1548 start = self.sql(expression, "start") 1549 start = f"START WITH {start}" if start else "" 1550 increment = self.sql(expression, "increment") 1551 increment = f" INCREMENT BY {increment}" if increment else "" 1552 minvalue = self.sql(expression, "minvalue") 1553 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1554 maxvalue = self.sql(expression, "maxvalue") 1555 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1556 owned = self.sql(expression, "owned") 1557 owned = f" OWNED BY {owned}" if owned else "" 1558 1559 cache = expression.args.get("cache") 1560 if cache is None: 1561 cache_str = "" 1562 elif cache is True: 1563 cache_str = " CACHE" 1564 else: 1565 cache_str = f" CACHE {cache}" 1566 1567 options = self.expressions(expression, key="options", flat=True, sep=" ") 1568 options = f" {options}" if options else "" 1569 1570 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1571 1572 def triggerproperties_sql(self, expression: exp.TriggerProperties) -> str: 1573 timing = expression.args.get("timing", "") 1574 events = " OR ".join(self.sql(event) for event in expression.args.get("events") or []) 1575 timing_events = f"{timing} {events}".strip() if timing or events else "" 1576 1577 parts = [timing_events, "ON", self.sql(expression, "table")] 1578 1579 if referenced_table := expression.args.get("referenced_table"): 1580 parts.extend(["FROM", self.sql(referenced_table)]) 1581 1582 if deferrable := expression.args.get("deferrable"): 1583 parts.append(deferrable) 1584 1585 if initially := expression.args.get("initially"): 1586 parts.append(f"INITIALLY {initially}") 1587 1588 if referencing := expression.args.get("referencing"): 1589 parts.append(self.sql(referencing)) 1590 1591 if for_each := expression.args.get("for_each"): 1592 parts.append(f"FOR EACH {for_each}") 1593 1594 if when := expression.args.get("when"): 1595 parts.append(f"WHEN ({self.sql(when)})") 1596 1597 parts.append(self.sql(expression, "execute")) 1598 1599 return self.sep().join(parts) 1600 1601 def triggerreferencing_sql(self, expression: exp.TriggerReferencing) -> str: 1602 parts = [] 1603 1604 if old_alias := expression.args.get("old"): 1605 parts.append(f"OLD TABLE AS {self.sql(old_alias)}") 1606 1607 if new_alias := expression.args.get("new"): 1608 parts.append(f"NEW TABLE AS {self.sql(new_alias)}") 1609 1610 return f"REFERENCING {' '.join(parts)}" 1611 1612 def triggerevent_sql(self, expression: exp.TriggerEvent) -> str: 1613 columns = expression.args.get("columns") 1614 if columns: 1615 return f"{expression.this} OF {self.expressions(expression, key='columns', flat=True)}" 1616 1617 return self.sql(expression, "this") 1618 1619 def clone_sql(self, expression: exp.Clone) -> str: 1620 this = self.sql(expression, "this") 1621 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1622 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1623 return f"{shallow}{keyword} {this}" 1624 1625 def describe_sql(self, expression: exp.Describe) -> str: 1626 style = expression.args.get("style") 1627 style = f" {style}" if style else "" 1628 partition = self.sql(expression, "partition") 1629 partition = f" {partition}" if partition else "" 1630 format = self.sql(expression, "format") 1631 format = f" {format}" if format else "" 1632 as_json = " AS JSON" if expression.args.get("as_json") else "" 1633 1634 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}{as_json}" 1635 1636 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1637 tag = self.sql(expression, "tag") 1638 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1639 1640 def prepend_ctes(self, expression: exp.Expr, sql: str) -> str: 1641 with_ = self.sql(expression, "with_") 1642 if with_: 1643 sql = f"{with_}{self.sep()}{sql}" 1644 return sql 1645 1646 def with_sql(self, expression: exp.With) -> str: 1647 udfs = self.expressions(expression, key="udfs", flat=True) 1648 udfs = f"WITH {udfs}" if udfs else "" 1649 1650 sql = self.expressions(expression, flat=True) 1651 1652 recursive = ( 1653 "RECURSIVE " 1654 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1655 else "" 1656 ) 1657 search = self.sql(expression, "search") 1658 search = f" {search}" if search else "" 1659 cycle = self.sql(expression, "cycle") 1660 cycle = f" {cycle}" if cycle else "" 1661 1662 sql = f"WITH {recursive}{sql}{search}{cycle}" if sql else "" 1663 return f"{udfs} {sql}" if udfs and sql else f"{udfs}{sql}" 1664 1665 def cte_sql(self, expression: exp.CTE) -> str: 1666 alias = expression.args.get("alias") 1667 if alias: 1668 alias.add_comments(expression.pop_comments()) 1669 1670 alias_sql = self.sql(expression, "alias") 1671 1672 materialized = expression.args.get("materialized") 1673 if materialized is False: 1674 materialized = "NOT MATERIALIZED " 1675 elif materialized: 1676 materialized = "MATERIALIZED " 1677 1678 key_expressions = self.expressions(expression, key="key_expressions", flat=True) 1679 key_expressions = f" USING KEY ({key_expressions})" if key_expressions else "" 1680 1681 return f"{alias_sql}{key_expressions} AS {materialized or ''}{self.wrap(expression)}" 1682 1683 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1684 alias = self.sql(expression, "this") 1685 columns = self.expressions(expression, key="columns", flat=True) 1686 columns = f"({columns})" if columns else "" 1687 1688 if ( 1689 columns 1690 and not self.SUPPORTS_TABLE_ALIAS_COLUMNS 1691 and not (self.SUPPORTS_NAMED_CTE_COLUMNS and isinstance(expression.parent, exp.CTE)) 1692 ): 1693 columns = "" 1694 self.unsupported("Named columns are not supported in table alias.") 1695 1696 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1697 alias = self._next_name() 1698 1699 return f"{alias}{columns}" 1700 1701 def bitstring_sql(self, expression: exp.BitString) -> str: 1702 this = self.sql(expression, "this") 1703 if self.dialect.BIT_START: 1704 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1705 return f"{int(this, 2)}" 1706 1707 def hexstring_sql( 1708 self, expression: exp.HexString, binary_function_repr: str | None = None 1709 ) -> str: 1710 if expression.args.get("is_character"): 1711 self.unsupported("Hexadecimal character literals are only supported in Teradata") 1712 this = expression.this.replace("'", "''") 1713 return f"'{this}'XC" 1714 1715 this = self.sql(expression, "this") 1716 is_integer_type = expression.args.get("is_integer") 1717 1718 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1719 not self.dialect.HEX_START and not binary_function_repr 1720 ): 1721 # Integer representation will be returned if: 1722 # - The read dialect treats the hex value as integer literal but not the write 1723 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1724 return f"{int(this, 16)}" 1725 1726 if not is_integer_type: 1727 # Read dialect treats the hex value as BINARY/BLOB 1728 if binary_function_repr: 1729 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1730 return self.func(binary_function_repr, exp.Literal.string(this)) 1731 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1732 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1733 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1734 1735 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1736 1737 def bytestring_sql(self, expression: exp.ByteString) -> str: 1738 this = self.sql(expression, "this") 1739 is_bytes = bool(expression.args.get("is_bytes")) 1740 if is_bytes and self.BYTE_STRING_FUNCTION: 1741 # Hex digits can be quoted directly without escaping. 1742 return self.func(self.BYTE_STRING_FUNCTION, f"'{this.encode('latin-1').hex()}'") 1743 1744 if self.dialect.BYTE_START: 1745 escaped_byte_string = self.escape_str( 1746 this, 1747 escape_backslash=bool( 1748 self.dialect.tokenizer_class.NUMERIC_ESCAPES 1749 or self.dialect.tokenizer_class.DROP_UNKNOWN_ESCAPES 1750 ), 1751 delimiter=self.dialect.BYTE_END, 1752 escaped_delimiter=self._escaped_byte_quote_end, 1753 is_byte_string=True, 1754 is_bytes=is_bytes, 1755 ) 1756 delimited_byte_string = ( 1757 f"{self.dialect.BYTE_START}{escaped_byte_string}{self.dialect.BYTE_END}" 1758 ) 1759 if is_bytes and not self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1760 return self.sql( 1761 exp.cast(delimited_byte_string, exp.DType.BINARY, dialect=self.dialect) 1762 ) 1763 if not is_bytes and self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1764 return self.sql( 1765 exp.cast(delimited_byte_string, exp.DType.VARCHAR, dialect=self.dialect) 1766 ) 1767 1768 return delimited_byte_string 1769 1770 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1771 return self.sql(exp.Literal.string(this)) 1772 1773 self.unsupported(f"Byte strings are not supported for {self.dialect.__class__.__name__}") 1774 return "" 1775 1776 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1777 this = self.sql(expression, "this") 1778 escape = expression.args.get("escape") 1779 unicode_start = self.dialect.UNICODE_START 1780 1781 if unicode_start: 1782 escape_substitute = r"\\\1" 1783 left_quote, right_quote = unicode_start, self.dialect.UNICODE_END or "" 1784 else: 1785 escape_substitute = r"\\u\1" 1786 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1787 1788 if escape: 1789 escape_pattern = re.compile(rf"{re.escape(escape.name)}(\d+)") 1790 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1791 else: 1792 escape_pattern = ESCAPED_UNICODE_RE 1793 escape_sql = "" 1794 1795 if not unicode_start or (escape and not self.SUPPORTS_UESCAPE): 1796 this = escape_pattern.sub(self.UNICODE_SUBSTITUTE or escape_substitute, this) 1797 1798 if unicode_start: 1799 # A Unicode literal only escapes its delimiter by doubling it; the escape character 1800 # introduces a code point, so the dialect's ordinary string escapes don't apply here 1801 this = self._replace_line_breaks(this).replace(right_quote, right_quote * 2) 1802 else: 1803 this = self.escape_str(this, escape_backslash=False) 1804 1805 return f"{left_quote}{this}{right_quote}{escape_sql}" 1806 1807 def rawstring_sql(self, expression: exp.RawString) -> str: 1808 string = expression.this 1809 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1810 string = string.replace("\\", "\\\\") 1811 1812 string = self.escape_str(string, escape_backslash=False) 1813 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1814 1815 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1816 this = self.sql(expression, "this") 1817 specifier = self.sql(expression, "expression") 1818 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1819 return f"{this}{specifier}" 1820 1821 def datatype_param_bound_limiter( 1822 self, 1823 expression: exp.DataType, 1824 type_value: exp.DType, 1825 defaults: tuple[int, ...], 1826 bounds: tuple[int | None, ...], 1827 ) -> exp.DataType: 1828 params = expression.expressions 1829 1830 if not params: 1831 if defaults: 1832 expression.set( 1833 "expressions", 1834 [exp.DataTypeParam(this=exp.Literal.number(d)) for d in defaults], 1835 ) 1836 return expression 1837 1838 if not bounds: 1839 return expression 1840 1841 for i, param in enumerate(params): 1842 bound = bounds[i] if i < len(bounds) else None 1843 if bound is None: 1844 continue 1845 1846 param_value = param.this if isinstance(param, exp.DataTypeParam) else param 1847 value = ( 1848 param_value.to_py() 1849 if isinstance(param_value, exp.Literal) and param_value.is_number 1850 else None 1851 ) 1852 if isinstance(value, (int, Decimal)) and value > bound: 1853 self.unsupported( 1854 f"{type_value.value} parameter {param_value.name} exceeds " 1855 f"{self.dialect.__class__.__name__}'s maximum of {bound}; capping" 1856 ) 1857 params[i] = exp.DataTypeParam(this=exp.Literal.number(bound)) 1858 1859 return expression 1860 1861 def datatype_sql(self, expression: exp.DataType) -> str: 1862 nested = "" 1863 values = "" 1864 1865 expr_nested = expression.args.get("nested") 1866 type_value = expression.this 1867 1868 if ( 1869 not expr_nested 1870 and isinstance(type_value, exp.DType) 1871 and (settings := self.TYPE_PARAM_SETTINGS.get(type_value)) 1872 ): 1873 expression = self.datatype_param_bound_limiter(expression, type_value, *settings) 1874 1875 interior = ( 1876 self.expressions( 1877 expression, dynamic=True, new_line=True, skip_first=True, skip_last=True 1878 ) 1879 if expr_nested and self.pretty 1880 else self.expressions(expression, flat=True) 1881 ) 1882 1883 if type_value in self.UNSUPPORTED_TYPES: 1884 self.unsupported( 1885 f"Data type {type_value.value} is not supported when targeting {self.dialect.__class__.__name__}" 1886 ) 1887 1888 type_sql: t.Any = "" 1889 if type_value == exp.DType.USERDEFINED and expression.args.get("kind"): 1890 type_sql = self.sql(expression, "kind") 1891 elif type_value == exp.DType.CHARACTER_SET: 1892 char = f"CHAR({interior})" if interior else "CHAR" 1893 return f"{char} CHARACTER SET {self.sql(expression, 'kind')}" 1894 else: 1895 type_sql = ( 1896 self.TYPE_MAPPING.get(type_value, type_value.value) 1897 if isinstance(type_value, exp.DType) 1898 else type_value 1899 ) 1900 1901 if interior: 1902 if expr_nested: 1903 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1904 if expression.args.get("values") is not None: 1905 delimiters = ("[", "]") if type_value == exp.DType.ARRAY else ("(", ")") 1906 values = self.expressions(expression, key="values", flat=True) 1907 values = f"{delimiters[0]}{values}{delimiters[1]}" 1908 elif type_value == exp.DType.INTERVAL: 1909 nested = f" {interior}" 1910 else: 1911 nested = f"({interior})" 1912 1913 type_sql = f"{type_sql}{nested}{values}" 1914 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1915 exp.DType.TIMETZ, 1916 exp.DType.TIMESTAMPTZ, 1917 ): 1918 type_sql = f"{type_sql} WITH TIME ZONE" 1919 1920 collate = self.sql(expression, "collate") 1921 if collate: 1922 type_sql = f"{type_sql} COLLATE {collate}" 1923 1924 return type_sql 1925 1926 def directory_sql(self, expression: exp.Directory) -> str: 1927 local = "LOCAL " if expression.args.get("local") else "" 1928 row_format = self.sql(expression, "row_format") 1929 row_format = f" {row_format}" if row_format else "" 1930 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1931 1932 def delete_sql(self, expression: exp.Delete) -> str: 1933 hint = self.sql(expression, "hint") 1934 this = self.sql(expression, "this") 1935 this = f" FROM {this}" if this else "" 1936 using = self.expressions(expression, key="using") 1937 using = f" USING {using}" if using else "" 1938 cluster = self.sql(expression, "cluster") 1939 cluster = f" {cluster}" if cluster else "" 1940 where = self.sql(expression, "where") 1941 returning = self.sql(expression, "returning") 1942 order = self.sql(expression, "order") 1943 limit = self.sql(expression, "limit") 1944 tables = self.expressions(expression, key="tables") 1945 tables = f" {tables}" if tables else "" 1946 if self.RETURNING_END: 1947 expression_sql = f"{this}{using}{cluster}{where}{returning}{order}{limit}" 1948 else: 1949 expression_sql = f"{returning}{this}{using}{cluster}{where}{order}{limit}" 1950 return self.prepend_ctes(expression, f"DELETE{hint}{tables}{expression_sql}") 1951 1952 def drop_sql(self, expression: exp.Drop) -> str: 1953 tables = self.expressions(expression, key="tables", flat=True) 1954 expressions = self.expressions(expression, flat=True) 1955 expressions = f" ({expressions})" if expressions else "" 1956 kind = expression.args["kind"] 1957 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1958 iceberg = ( 1959 " ICEBERG" 1960 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 1961 else "" 1962 ) 1963 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1964 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1965 on_cluster = self.sql(expression, "cluster") 1966 on_cluster = f" {on_cluster}" if on_cluster else "" 1967 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1968 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1969 cascade = " CASCADE" if expression.args.get("cascade") else "" 1970 restrict = " RESTRICT" if expression.args.get("restrict") else "" 1971 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1972 purge = " PURGE" if expression.args.get("purge") else "" 1973 sync = " SYNC" if expression.args.get("sync") else "" 1974 force = " FORCE" if expression.args.get("force") else "" 1975 return f"DROP{temporary}{materialized}{iceberg} {kind}{concurrently_sql}{exists_sql}{tables}{on_cluster}{expressions}{cascade}{restrict}{constraints}{purge}{sync}{force}" 1976 1977 def set_operation(self, expression: exp.SetOperation) -> str: 1978 op_type = type(expression) 1979 op_name = op_type.key.upper() 1980 1981 distinct = expression.args.get("distinct") 1982 if ( 1983 distinct is False 1984 and op_type in (exp.Except, exp.Intersect) 1985 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1986 ): 1987 self.unsupported(f"{op_name} ALL is not supported") 1988 1989 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1990 1991 if distinct is None: 1992 distinct = default_distinct 1993 if distinct is None: 1994 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1995 1996 if distinct is default_distinct: 1997 distinct_or_all = "" 1998 else: 1999 distinct_or_all = " DISTINCT" if distinct else " ALL" 2000 2001 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 2002 side_kind = f"{side_kind} " if side_kind else "" 2003 2004 by_name = " BY NAME" if expression.args.get("by_name") else "" 2005 on = self.expressions(expression, key="on", flat=True) 2006 on = f" ON ({on})" if on else "" 2007 2008 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}" 2009 2010 def set_operations(self, expression: exp.SetOperation) -> str: 2011 if not self.SET_OP_MODIFIERS: 2012 limit = expression.args.get("limit") 2013 order = expression.args.get("order") 2014 offset = expression.args.get("offset") 2015 2016 if limit or order or offset: 2017 select = self._move_ctes_to_top_level( 2018 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 2019 ) 2020 2021 for arg in ("limit", "order", "offset"): 2022 if value := expression.args.get(arg): 2023 select.set(arg, value.pop()) 2024 return self.sql(select) 2025 2026 sqls: list[str] = [] 2027 stack: list[str | exp.Expr | int | None] = [expression] 2028 depth = 0 2029 open_parens = "" 2030 2031 while stack: 2032 node = stack.pop() 2033 2034 if isinstance(node, int): 2035 # Closes a plain grouping opened below, restoring its depth 2036 depth = node 2037 sqls[-1] += self.sep("") + self.indent(")", level=depth, pad=0) 2038 elif isinstance(node, exp.SetOperation): 2039 stack.append(node.expression) 2040 stack.append( 2041 self.maybe_comment( 2042 self.set_operation(node), comments=node.comments, separated=True 2043 ) 2044 ) 2045 left = node.this 2046 if ( 2047 not self.SET_OP_PARENTHESIZED_OPERANDS 2048 and not self.dialect.INTERSECT_BINDS_TIGHTER_THAN_UNION_AND_EXCEPT 2049 ): 2050 # Left grouping is implicit, so skip the `SELECT * FROM (...)` wrapper: 2051 # it renames duplicate columns and deepens recursion. Inner CTEs and 2052 # modifiers still need the wrapper. 2053 wrappers: list[exp.Subquery] = [] 2054 inner = left 2055 while isinstance(inner, exp.Subquery) and inner.is_wrapper: 2056 wrappers.append(inner) 2057 inner = inner.this 2058 2059 if ( 2060 isinstance(inner, exp.SetOperation) 2061 and not inner.args.get("with_") 2062 and not any(inner.args.get(key) for key in exp.QUERY_MODIFIERS) 2063 ): 2064 for wrapper in wrappers: 2065 inner.add_comments(wrapper.pop_comments()) 2066 left = inner 2067 elif ( 2068 self.SET_OP_PARENTHESIZED_OPERANDS 2069 and isinstance(left, exp.Subquery) 2070 and left.is_wrapper 2071 and not left.comments 2072 and isinstance(left.this, exp.SetOperation) 2073 and not left.this.args.get("with_") 2074 and not any(left.this.args.get(key) for key in exp.QUERY_MODIFIERS) 2075 ): 2076 # Write a plain grouping's parentheses here rather than recursing through 2077 # subquery_sql: left-to-right chains nest one grouping per INTERSECT, and 2078 # long ones would exhaust the stack. The depth pushed here marks the close. 2079 open_parens += self.indent("(", level=depth, pad=0) + self.sep("") 2080 stack.append(depth) 2081 depth += 1 2082 left = left.this 2083 stack.append(left) 2084 else: 2085 if ( 2086 not self.SET_OP_LIMITS 2087 and isinstance(node, exp.Select) 2088 and node.args.get("limit") 2089 ): 2090 node = node.subquery(copy=False) 2091 if not self.SET_OP_PARENTHESIZED_OPERANDS and isinstance(node, exp.Subquery): 2092 node = exp.select("*").from_(node, copy=False) 2093 sqls.append(open_parens + self.indent(self.sql(node), level=depth, pad=0)) 2094 open_parens = "" 2095 2096 this = self.sep().join(sqls) 2097 this = self.query_modifiers(expression, this) 2098 return self.prepend_ctes(expression, this) 2099 2100 def fetch_sql(self, expression: exp.Fetch) -> str: 2101 direction = expression.args.get("direction") 2102 direction = f" {direction}" if direction else "" 2103 count = self.sql(expression, "count") 2104 count = f" {count}" if count else "" 2105 limit_options = self.sql(expression, "limit_options") 2106 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 2107 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 2108 2109 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 2110 percent = " PERCENT" if expression.args.get("percent") else "" 2111 rows = " ROWS" if expression.args.get("rows") else "" 2112 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 2113 if not with_ties and rows: 2114 with_ties = " ONLY" 2115 return f"{percent}{rows}{with_ties}" 2116 2117 def filter_sql(self, expression: exp.Filter) -> str: 2118 this = self.sql(expression, "this") 2119 where = self.sql(expression, "expression").strip() 2120 return f"{this} FILTER({where})" 2121 2122 def per_sql(self, expression: exp.Per) -> str: 2123 keys = ", ".join( 2124 f"{self.sql(key, 'this')} {self.sql(key, 'with_fill')}" 2125 if isinstance(key, exp.Ordered) and key.args.get("with_fill") 2126 else self.sql(key) 2127 for key in expression.expressions 2128 ) 2129 return f"{self.sql(expression, 'this')} PER ({keys})" 2130 2131 def hint_sql(self, expression: exp.Hint) -> str: 2132 if not self.QUERY_HINTS: 2133 self.unsupported("Hints are not supported") 2134 return "" 2135 2136 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 2137 2138 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 2139 using = self.sql(expression, "using") 2140 using = f" USING {using}" if using else "" 2141 columns = self.expressions(expression, key="columns", flat=True) 2142 columns = f"({columns})" if columns else "" 2143 partition_by = self.expressions(expression, key="partition_by", flat=True) 2144 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 2145 where = self.sql(expression, "where") 2146 include = self.expressions(expression, key="include", flat=True) 2147 if include: 2148 include = f" INCLUDE ({include})" 2149 with_storage = self.expressions(expression, key="with_storage", flat=True) 2150 with_storage = f" WITH ({with_storage})" if with_storage else "" 2151 tablespace = self.sql(expression, "tablespace") 2152 if tablespace: 2153 prefix = "" if isinstance(expression.parent, exp.Index) else " USING INDEX" 2154 tablespace = f"{prefix} TABLESPACE {tablespace}" 2155 on = self.sql(expression, "on") 2156 on = f" ON {on}" if on else "" 2157 2158 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 2159 2160 def index_sql(self, expression: exp.Index) -> str: 2161 unique = "UNIQUE " if expression.args.get("unique") else "" 2162 primary = "PRIMARY " if expression.args.get("primary") else "" 2163 amp = "AMP " if expression.args.get("amp") else "" 2164 name = self.sql(expression, "this") 2165 name = f"{name} " if name else "" 2166 table = self.sql(expression, "table") 2167 table = f"{self.INDEX_ON} {table}" if table else "" 2168 2169 index = "INDEX " if not table else "" 2170 2171 params = self.sql(expression, "params") 2172 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 2173 2174 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 2175 this = expression.this 2176 if this and this.is_string: 2177 resolved = maybe_parse(this.name).sql(self.dialect) 2178 if "expressions" in expression.args: 2179 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 2180 # We can't safely emit the call to other dialects since name/arg semantics may differ 2181 self.unsupported( 2182 "Transpiling dynamically-invoked IDENTIFIER() functions is unsupported" 2183 ) 2184 return resolved 2185 self.unsupported("IDENTIFIER() with non-literal arguments is not supported") 2186 return self.func("IDENTIFIER", this) 2187 2188 def identifier_sql(self, expression: exp.Identifier) -> str: 2189 text = expression.name 2190 lower = text.lower() 2191 quoted = expression.quoted 2192 text = lower if self.normalize and not quoted else text 2193 if self._identifier_escaped_sequences: 2194 for char, escaped in self._identifier_escaped_sequences.items(): 2195 text = text.replace(char, escaped) 2196 text = text.replace(self._identifier_end, self._escaped_identifier_end) 2197 if ( 2198 quoted 2199 or self.dialect.can_quote(expression, self.identify) 2200 or lower in self.RESERVED_KEYWORDS 2201 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 2202 ): 2203 text = ( 2204 f"{self._identifier_start}{self._replace_line_breaks(text)}{self._identifier_end}" 2205 ) 2206 return text 2207 2208 def hex_sql(self, expression: exp.Hex) -> str: 2209 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 2210 if self.dialect.HEX_LOWERCASE: 2211 text = self.func("LOWER", text) 2212 2213 return text 2214 2215 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 2216 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 2217 if not self.dialect.HEX_LOWERCASE: 2218 text = self.func("LOWER", text) 2219 return text 2220 2221 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 2222 input_format = self.sql(expression, "input_format") 2223 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 2224 output_format = self.sql(expression, "output_format") 2225 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 2226 return self.sep().join((input_format, output_format)) 2227 2228 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 2229 string = self.sql(exp.Literal.string(expression.name)) 2230 return f"{prefix}{string}" 2231 2232 def partition_sql(self, expression: exp.Partition) -> str: 2233 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 2234 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 2235 2236 def properties_sql(self, expression: exp.Properties) -> str: 2237 root_properties = [] 2238 with_properties = [] 2239 2240 for p in expression.expressions: 2241 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2242 if p_loc == exp.Properties.Location.POST_WITH: 2243 with_properties.append(p) 2244 elif p_loc == exp.Properties.Location.POST_SCHEMA: 2245 root_properties.append(p) 2246 2247 root_props_ast = exp.Properties(expressions=root_properties) 2248 root_props_ast.parent = expression.parent 2249 2250 with_props_ast = exp.Properties(expressions=with_properties) 2251 with_props_ast.parent = expression.parent 2252 2253 root_props = self.root_properties(root_props_ast) 2254 with_props = self.with_properties(with_props_ast) 2255 2256 if root_props and with_props and not self.pretty: 2257 with_props = " " + with_props 2258 2259 return root_props + with_props 2260 2261 def root_properties(self, properties: exp.Properties) -> str: 2262 if properties.expressions: 2263 return self.expressions(properties, indent=False, sep=" ") 2264 return "" 2265 2266 def properties( 2267 self, 2268 properties: exp.Properties, 2269 prefix: str = "", 2270 sep: str = ", ", 2271 suffix: str = "", 2272 wrapped: bool = True, 2273 ) -> str: 2274 if properties.expressions: 2275 expressions = self.expressions(properties, sep=sep, indent=False) 2276 if expressions: 2277 expressions = self.wrap(expressions) if wrapped else expressions 2278 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 2279 return "" 2280 2281 def with_properties(self, properties: exp.Properties) -> str: 2282 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 2283 2284 def locate_properties(self, properties: exp.Properties) -> defaultdict: 2285 properties_locs = defaultdict(list) 2286 for p in properties.expressions: 2287 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2288 if p_loc != exp.Properties.Location.UNSUPPORTED: 2289 properties_locs[p_loc].append(p) 2290 else: 2291 self.unsupported(f"Unsupported property {p.key}") 2292 2293 return properties_locs 2294 2295 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 2296 if isinstance(expression.this, exp.Dot): 2297 return self.sql(expression, "this") 2298 return self.sql(exp.Literal.string(expression.name)) if string_key else expression.name 2299 2300 def property_sql(self, expression: exp.Property) -> str: 2301 property_cls = expression.__class__ 2302 if property_cls == exp.Property: 2303 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 2304 2305 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 2306 if not property_name: 2307 self.unsupported(f"Unsupported property {expression.key}") 2308 return "" 2309 2310 return f"{property_name}={self.sql(expression, 'this')}" 2311 2312 def uuidproperty_sql(self, expression: exp.UuidProperty) -> str: 2313 return f"UUID {self.sql(expression, 'this')}" 2314 2315 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 2316 if self.SUPPORTS_CREATE_TABLE_LIKE: 2317 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 2318 options = f" {options}" if options else "" 2319 2320 like = f"LIKE {self.sql(expression, 'this')}{options}" 2321 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 2322 like = f"({like})" 2323 2324 return like 2325 2326 if expression.expressions: 2327 self.unsupported("Transpilation of LIKE property options is unsupported") 2328 2329 select = exp.select("*").from_(expression.this).limit(0) 2330 return f"AS {self.sql(select)}" 2331 2332 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 2333 no = "NO " if expression.args.get("no") else "" 2334 protection = " PROTECTION" if expression.args.get("protection") else "" 2335 return f"{no}FALLBACK{protection}" 2336 2337 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 2338 no = "NO " if expression.args.get("no") else "" 2339 local = expression.args.get("local") 2340 local = f"{local} " if local else "" 2341 dual = "DUAL " if expression.args.get("dual") else "" 2342 before = "BEFORE " if expression.args.get("before") else "" 2343 after = "AFTER " if expression.args.get("after") else "" 2344 return f"{no}{local}{dual}{before}{after}JOURNAL" 2345 2346 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 2347 freespace = self.sql(expression, "this") 2348 percent = " PERCENT" if expression.args.get("percent") else "" 2349 return f"FREESPACE={freespace}{percent}" 2350 2351 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 2352 if expression.args.get("default"): 2353 property = "DEFAULT" 2354 elif expression.args.get("on"): 2355 property = "ON" 2356 else: 2357 property = "OFF" 2358 return f"CHECKSUM={property}" 2359 2360 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 2361 if expression.args.get("no"): 2362 return "NO MERGEBLOCKRATIO" 2363 if expression.args.get("default"): 2364 return "DEFAULT MERGEBLOCKRATIO" 2365 2366 percent = " PERCENT" if expression.args.get("percent") else "" 2367 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 2368 2369 def moduleproperty_sql(self, expression: exp.ModuleProperty) -> str: 2370 expressions = self.expressions(expression, flat=True) 2371 expressions = f"({expressions})" if expressions else "" 2372 return f"USING {self.sql(expression, 'this')}{expressions}" 2373 2374 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 2375 default = expression.args.get("default") 2376 minimum = expression.args.get("minimum") 2377 maximum = expression.args.get("maximum") 2378 if default or minimum or maximum: 2379 if default: 2380 prop = "DEFAULT" 2381 elif minimum: 2382 prop = "MINIMUM" 2383 else: 2384 prop = "MAXIMUM" 2385 return f"{prop} DATABLOCKSIZE" 2386 units = expression.args.get("units") 2387 units = f" {units}" if units else "" 2388 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 2389 2390 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 2391 autotemp = expression.args.get("autotemp") 2392 always = expression.args.get("always") 2393 default = expression.args.get("default") 2394 manual = expression.args.get("manual") 2395 never = expression.args.get("never") 2396 2397 if autotemp is not None: 2398 prop = f"AUTOTEMP({self.expressions(autotemp)})" 2399 elif always: 2400 prop = "ALWAYS" 2401 elif default: 2402 prop = "DEFAULT" 2403 elif manual: 2404 prop = "MANUAL" 2405 elif never: 2406 prop = "NEVER" 2407 return f"BLOCKCOMPRESSION={prop}" 2408 2409 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 2410 no = expression.args.get("no") 2411 no = " NO" if no else "" 2412 concurrent = expression.args.get("concurrent") 2413 concurrent = " CONCURRENT" if concurrent else "" 2414 target = self.sql(expression, "target") 2415 target = f" {target}" if target else "" 2416 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 2417 2418 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 2419 if isinstance(expression.this, list): 2420 return f"IN ({self.expressions(expression, key='this', flat=True)})" 2421 if expression.this: 2422 modulus = self.sql(expression, "this") 2423 remainder = self.sql(expression, "expression") 2424 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 2425 2426 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 2427 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 2428 return f"FROM ({from_expressions}) TO ({to_expressions})" 2429 2430 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 2431 this = self.sql(expression, "this") 2432 2433 for_values_or_default = expression.expression 2434 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 2435 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 2436 else: 2437 for_values_or_default = " DEFAULT" 2438 2439 return f"PARTITION OF {this}{for_values_or_default}" 2440 2441 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 2442 kind = expression.args.get("kind") 2443 this = f" {self.sql(expression, 'this')}" if expression.this else "" 2444 for_or_in = expression.args.get("for_or_in") 2445 for_or_in = f" {for_or_in}" if for_or_in else "" 2446 lock_type = expression.args.get("lock_type") 2447 override = " OVERRIDE" if expression.args.get("override") else "" 2448 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 2449 2450 def lockingstatement_sql(self, expression: exp.LockingStatement) -> str: 2451 self.unsupported("LOCKING request modifier is not supported") 2452 return self.sql(expression, "expression") 2453 2454 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 2455 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 2456 statistics = expression.args.get("statistics") 2457 statistics_sql = "" 2458 if statistics is not None: 2459 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 2460 return f"{data_sql}{statistics_sql}" 2461 2462 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 2463 this = self.sql(expression, "this") 2464 this = f"HISTORY_TABLE={this}" if this else "" 2465 data_consistency: str | None = self.sql(expression, "data_consistency") 2466 data_consistency = ( 2467 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 2468 ) 2469 retention_period: str | None = self.sql(expression, "retention_period") 2470 retention_period = ( 2471 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 2472 ) 2473 2474 if this: 2475 on_sql = self.func("ON", this, data_consistency, retention_period) 2476 else: 2477 on_sql = "ON" if expression.args.get("on") else "OFF" 2478 2479 sql = f"SYSTEM_VERSIONING={on_sql}" 2480 2481 return f"WITH({sql})" if expression.args.get("with_") else sql 2482 2483 def insert_sql(self, expression: exp.Insert) -> str: 2484 hint = self.sql(expression, "hint") 2485 overwrite = expression.args.get("overwrite") 2486 2487 if isinstance(expression.this, exp.Directory): 2488 this = " OVERWRITE" if overwrite else " INTO" 2489 else: 2490 this = self.INSERT_OVERWRITE if overwrite else " INTO" 2491 2492 stored = self.sql(expression, "stored") 2493 stored = f" {stored}" if stored else "" 2494 alternative = expression.args.get("alternative") 2495 alternative = f" OR {alternative}" if alternative else "" 2496 ignore = " IGNORE" if expression.args.get("ignore") else "" 2497 is_function = expression.args.get("is_function") 2498 if is_function: 2499 this = f"{this} FUNCTION" 2500 this = f"{this} {self.sql(expression, 'this')}" 2501 2502 exists = " IF EXISTS" if expression.args.get("exists") else "" 2503 where = self.sql(expression, "where") 2504 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 2505 using = self.expressions(expression, key="using", flat=True) 2506 using = f"{self.sep()}REPLACE USING ({using})" if using else "" 2507 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 2508 on_conflict = self.sql(expression, "conflict") 2509 on_conflict = f" {on_conflict}" if on_conflict else "" 2510 by_name = " BY NAME" if expression.args.get("by_name") else "" 2511 default_values = "DEFAULT VALUES" if expression.args.get("default") else "" 2512 returning = self.sql(expression, "returning") 2513 2514 if self.RETURNING_END: 2515 expression_sql = f"{expression_sql}{on_conflict}{default_values}{returning}" 2516 else: 2517 expression_sql = f"{returning}{expression_sql}{on_conflict}" 2518 2519 partition_by = self.sql(expression, "partition") 2520 partition_by = f" {partition_by}" if partition_by else "" 2521 settings = self.sql(expression, "settings") 2522 settings = f" {settings}" if settings else "" 2523 2524 source = self.sql(expression, "source") 2525 source = f"TABLE {source}" if source else "" 2526 2527 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{using}{expression_sql}{source}" 2528 return self.prepend_ctes(expression, sql) 2529 2530 def introducer_sql(self, expression: exp.Introducer) -> str: 2531 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 2532 2533 def kill_sql(self, expression: exp.Kill) -> str: 2534 kind = self.sql(expression, "kind") 2535 kind = f" {kind}" if kind else "" 2536 this = self.sql(expression, "this") 2537 this = f" {this}" if this else "" 2538 return f"KILL{kind}{this}" 2539 2540 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 2541 return expression.name 2542 2543 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 2544 return expression.name 2545 2546 def onconflict_sql(self, expression: exp.OnConflict) -> str: 2547 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 2548 2549 constraint = self.sql(expression, "constraint") 2550 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 2551 2552 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 2553 if conflict_keys: 2554 conflict_keys = f"({conflict_keys})" 2555 2556 index_predicate = self.sql(expression, "index_predicate") 2557 conflict_keys = f"{conflict_keys}{index_predicate} " 2558 2559 action = self.sql(expression, "action") 2560 2561 expressions = self.expressions(expression, flat=True) 2562 if expressions: 2563 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 2564 expressions = f" {set_keyword}{expressions}" 2565 2566 where = self.sql(expression, "where") 2567 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 2568 2569 def returning_sql(self, expression: exp.Returning) -> str: 2570 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 2571 2572 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 2573 fields = self.sql(expression, "fields") 2574 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 2575 escaped = self.sql(expression, "escaped") 2576 escaped = f" ESCAPED BY {escaped}" if escaped else "" 2577 items = self.sql(expression, "collection_items") 2578 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 2579 keys = self.sql(expression, "map_keys") 2580 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 2581 lines = self.sql(expression, "lines") 2582 lines = f" LINES TERMINATED BY {lines}" if lines else "" 2583 null = self.sql(expression, "null") 2584 null = f" NULL DEFINED AS {null}" if null else "" 2585 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 2586 2587 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 2588 return f"WITH ({self.expressions(expression, flat=True)})" 2589 2590 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 2591 this = f"{self.sql(expression, 'this')} INDEX" 2592 target = self.sql(expression, "target") 2593 target = f" FOR {target}" if target else "" 2594 return f"{this}{target} ({self.expressions(expression, flat=True)})" 2595 2596 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 2597 this = self.sql(expression, "this") 2598 kind = self.sql(expression, "kind") 2599 expr = self.sql(expression, "expression") 2600 return f"{this} ({kind} => {expr})" 2601 2602 def table_parts(self, expression: exp.Table) -> str: 2603 return ".".join( 2604 self.sql(part) 2605 for part in ( 2606 expression.args.get("catalog"), 2607 expression.args.get("db"), 2608 expression.args.get("this"), 2609 ) 2610 if part is not None 2611 ) 2612 2613 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 2614 table = self.table_parts(expression) 2615 only = "ONLY " if expression.args.get("only") else "" 2616 partition = self.sql(expression, "partition") 2617 partition = f" {partition}" if partition else "" 2618 version = self.sql(expression, "version") 2619 version = f" {version}" if version else "" 2620 alias = self.sql(expression, "alias") 2621 alias = f"{sep}{alias}" if alias else "" 2622 2623 sample = self.sql(expression, "sample") 2624 post_alias = "" 2625 pre_alias = "" 2626 2627 if self.dialect.ALIAS_POST_TABLESAMPLE: 2628 pre_alias = sample 2629 else: 2630 post_alias = sample 2631 2632 if self.dialect.ALIAS_POST_VERSION: 2633 pre_alias = f"{pre_alias}{version}" 2634 else: 2635 post_alias = f"{post_alias}{version}" 2636 2637 hints = self.expressions(expression, key="hints", sep=" ") 2638 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2639 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2640 joins = self.indent( 2641 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2642 ) 2643 laterals = self.expressions(expression, key="laterals", sep="") 2644 2645 file_format = self.sql(expression, "format") 2646 pattern = self.sql(expression, "pattern") 2647 if file_format: 2648 pattern = f", PATTERN => {pattern}" if pattern else "" 2649 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2650 elif pattern: 2651 file_format = f" (PATTERN => {pattern})" 2652 2653 ordinality = expression.args.get("ordinality") or "" 2654 if ordinality: 2655 ordinality = f" WITH ORDINALITY{alias}" 2656 alias = "" 2657 2658 when = self.sql(expression, "when") 2659 if when: 2660 if self.HISTORICAL_DATA_POST_ALIAS: 2661 alias = f"{alias} {when}" 2662 else: 2663 table = f"{table} {when}" 2664 2665 changes = self.sql(expression, "changes") 2666 changes = f" {changes}" if changes else "" 2667 2668 rows_from = self.expressions(expression, key="rows_from") 2669 if rows_from: 2670 table = f"ROWS FROM {self.wrap(rows_from)}" 2671 2672 indexed = expression.args.get("indexed") 2673 if indexed is not None: 2674 indexed = f" INDEXED BY {self.sql(indexed)}" if indexed else " NOT INDEXED" 2675 else: 2676 indexed = "" 2677 2678 return f"{only}{table}{changes}{partition}{file_format}{pre_alias}{alias}{indexed}{hints}{pivots}{post_alias}{joins}{laterals}{ordinality}" 2679 2680 def tableargument_sql(self, expression: exp.TableArgument) -> str: 2681 table = expression.this 2682 return f"TABLE {self.maybe_comment(self.table_parts(table), table)}" 2683 2684 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2685 table = self.func("TABLE", expression.this) 2686 alias = self.sql(expression, "alias") 2687 alias = f" AS {alias}" if alias else "" 2688 sample = self.sql(expression, "sample") 2689 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2690 joins = self.indent( 2691 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2692 ) 2693 return f"{table}{alias}{pivots}{sample}{joins}" 2694 2695 def tablesample_sql( 2696 self, 2697 expression: exp.TableSample, 2698 tablesample_keyword: str | None = None, 2699 ) -> str: 2700 if expression.expressions: 2701 self.unsupported("Multiple sample sets are not supported") 2702 return "" 2703 2704 method = self.sql(expression, "method") 2705 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2706 numerator = self.sql(expression, "bucket_numerator") 2707 denominator = self.sql(expression, "bucket_denominator") 2708 field = self.sql(expression, "bucket_field") 2709 field = f" ON {field}" if field else "" 2710 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2711 seed = self.sql(expression, "seed") 2712 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2713 2714 size = self.sql(expression, "size") 2715 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2716 size = f"{size} ROWS" 2717 2718 percent = self.sql(expression, "percent") 2719 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2720 percent = f"{percent} PERCENT" 2721 2722 expr = f"{bucket}{percent}{size}" 2723 if self.TABLESAMPLE_REQUIRES_PARENS: 2724 expr = f"({expr})" 2725 2726 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2727 2728 def _pivot_in_value_aliases(self, expression: exp.Pivot) -> list[exp.Expression] | None: 2729 # Returns the rewritten field.expressions list with PivotAlias wrappers injected where 2730 # the stored column name differs from the target dialect's natural output. 2731 columns = expression.args.get("columns") 2732 if not columns or len(expression.fields) != 1: 2733 return None 2734 2735 args = expression.args 2736 parser_cls = self.dialect.parser_class 2737 2738 tgt_identify_pivot_strings = parser_cls.IDENTIFY_PIVOT_STRINGS 2739 tgt_prefixed_pivot_columns = parser_cls.PREFIXED_PIVOT_COLUMNS 2740 tgt_pivot_column_naming = parser_cls.PIVOT_COLUMN_NAMING 2741 2742 src_identify_pivot_strings = args.get("identify_pivot_strings", tgt_identify_pivot_strings) 2743 src_prefixed_pivot_columns = args.get("prefixed_pivot_columns", tgt_prefixed_pivot_columns) 2744 src_pivot_column_naming = args.get("pivot_column_naming", tgt_pivot_column_naming) 2745 2746 if ( 2747 src_identify_pivot_strings == tgt_identify_pivot_strings 2748 and src_prefixed_pivot_columns == tgt_prefixed_pivot_columns 2749 and src_pivot_column_naming == tgt_pivot_column_naming 2750 ): 2751 return None 2752 2753 in_exprs = expression.fields[0].expressions 2754 step = len(columns) // len(in_exprs) 2755 2756 suffix = "" 2757 if len(expression.expressions) != 1 or expression.expressions[0].alias: 2758 # Derive the per-value suffix from the first stored column vs the first IN-list value. 2759 # This correctly handles dialects (e.g. Spark single-agg) that ignore agg aliases. 2760 first_base = ( 2761 in_exprs[0].sql() if src_identify_pivot_strings else in_exprs[0].alias_or_name 2762 ) 2763 first_stored = columns[0].name 2764 2765 # exit if only suffix matches, not prefix. (e.g. BigQuery, which cannot be fixed) 2766 if not first_stored.startswith(first_base): 2767 return None 2768 2769 suffix = first_stored[len(first_base) :] 2770 2771 # Whether the target dialect would append an agg-name suffix for this pivot. 2772 # Spark single-agg uniquely drops the agg alias entirely. 2773 target_has_suffix = ( 2774 len(expression.expressions) > 1 or tgt_pivot_column_naming != "agg_name_if_multiple" 2775 ) and any(a.alias for a in expression.expressions) 2776 source_has_suffix = suffix != "" 2777 2778 new_exprs: list[exp.Expression] = [] 2779 modified = False 2780 for val_idx, e in enumerate(in_exprs): 2781 if isinstance(e, exp.PivotAlias): 2782 new_exprs.append(e) 2783 continue 2784 2785 i = val_idx * step 2786 stored_full = columns[i].name 2787 stored_value = stored_full[: -len(suffix)] if suffix else stored_full 2788 target_value = e.sql() if tgt_identify_pivot_strings else e.alias_or_name 2789 2790 # Source had a suffix, but target won't apply one 2791 if source_has_suffix and not target_has_suffix: 2792 new_exprs.append( 2793 exp.PivotAlias(this=e, alias=exp.to_identifier(stored_full, quoted=True)) 2794 ) 2795 modified = True 2796 # Value-part mismatch (e.g. Snowflake's literal-style values vs others). 2797 elif stored_value != target_value: 2798 new_exprs.append( 2799 exp.PivotAlias(this=e, alias=exp.to_identifier(stored_value, quoted=True)) 2800 ) 2801 modified = True 2802 else: 2803 new_exprs.append(e) 2804 2805 return new_exprs if modified else None 2806 2807 def pivot_sql(self, expression: exp.Pivot) -> str: 2808 expressions = self.expressions(expression, flat=True) 2809 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2810 2811 group = self.sql(expression, "group") 2812 2813 if expression.this: 2814 this = self.sql(expression, "this") 2815 if not expressions: 2816 sql = f"UNPIVOT {this}" 2817 else: 2818 on = f"{self.seg('ON')} {expressions}" 2819 into = self.sql(expression, "into") 2820 into = f"{self.seg('INTO')} {into}" if into else "" 2821 using = self.expressions(expression, key="using", flat=True) 2822 using = f"{self.seg('USING')} {using}" if using else "" 2823 sql = f"{direction} {this}{on}{into}{using}{group}" 2824 return self.prepend_ctes(expression, sql) 2825 2826 if not expression.unpivot: 2827 # Wrap IN-list values with explicit aliases where the target dialect would differ 2828 new_field_exprs = self._pivot_in_value_aliases(expression) 2829 if new_field_exprs is not None: 2830 expression.fields[0].set("expressions", new_field_exprs) 2831 2832 alias = self.sql(expression, "alias") 2833 if alias: 2834 alias = f" AS {alias}" if self.PIVOT_ALIAS_WITH_AS else f" {alias}" 2835 2836 fields = self.expressions( 2837 expression, 2838 "fields", 2839 sep=" ", 2840 dynamic=True, 2841 new_line=True, 2842 skip_first=True, 2843 skip_last=True, 2844 ) 2845 2846 include_nulls = expression.args.get("include_nulls") 2847 if include_nulls is not None: 2848 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2849 else: 2850 nulls = "" 2851 2852 default_on_null = self.sql(expression, "default_on_null") 2853 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2854 sql = f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}" 2855 return self.prepend_ctes(expression, sql) 2856 2857 def version_sql(self, expression: exp.Version) -> str: 2858 this = f"FOR {expression.name}" 2859 kind = expression.text("kind") 2860 expr = self.sql(expression, "expression") 2861 return f"{this} {kind} {expr}" 2862 2863 def tuple_sql(self, expression: exp.Tuple) -> str: 2864 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2865 2866 def _update_from_joins_sql(self, expression: exp.Update) -> tuple[str, str]: 2867 """ 2868 Returns (join_sql, from_sql) for UPDATE statements. 2869 - join_sql: placed after UPDATE table, before SET 2870 - from_sql: placed after SET clause (standard position) 2871 Dialects like MySQL need to convert FROM to JOIN syntax. 2872 """ 2873 if self.UPDATE_STATEMENT_SUPPORTS_FROM or not (from_expr := expression.args.get("from_")): 2874 return ("", self.sql(expression, "from_")) 2875 2876 # Qualify unqualified columns in SET clause with the target table 2877 # MySQL requires qualified column names in multi-table UPDATE to avoid ambiguity 2878 target_table = expression.this 2879 if isinstance(target_table, exp.Table): 2880 target_name = exp.to_identifier(target_table.alias_or_name) 2881 for eq in expression.expressions: 2882 col = eq.this 2883 if isinstance(col, exp.Column) and not col.table: 2884 col.set("table", target_name) 2885 2886 table = from_expr.this 2887 if nested_joins := table.args.get("joins", []): 2888 table.set("joins", None) 2889 2890 join_sql = self.sql(exp.Join(this=table, on=exp.true())) 2891 for nested in nested_joins: 2892 if not nested.args.get("on") and not nested.args.get("using"): 2893 nested.set("on", exp.true()) 2894 join_sql += self.sql(nested) 2895 2896 return (join_sql, "") 2897 2898 def update_sql(self, expression: exp.Update) -> str: 2899 hint = self.sql(expression, "hint") 2900 alternative = self.sql(expression, "alternative") 2901 if alternative: 2902 if self.dialect.SUPPORTS_UPDATE_OR or self.dialect == "": 2903 alternative = f" OR {alternative}" 2904 else: 2905 self.unsupported(f"UPDATE OR {alternative} is not supported") 2906 alternative = "" 2907 this = self.sql(expression, "this") 2908 join_sql, from_sql = self._update_from_joins_sql(expression) 2909 set_sql = self.expressions(expression, flat=True) 2910 where_sql = self.sql(expression, "where") 2911 returning = self.sql(expression, "returning") 2912 order = self.sql(expression, "order") 2913 limit = self.sql(expression, "limit") 2914 if self.RETURNING_END: 2915 expression_sql = f"{from_sql}{where_sql}{returning}" 2916 else: 2917 expression_sql = f"{returning}{from_sql}{where_sql}" 2918 options = self.expressions(expression, key="options") 2919 options = f" OPTION({options})" if options else "" 2920 sql = f"UPDATE{hint}{alternative} {this}{join_sql} SET {set_sql}{expression_sql}{order}{limit}{options}" 2921 return self.prepend_ctes(expression, sql) 2922 2923 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2924 values_as_table = values_as_table and self.VALUES_AS_TABLE 2925 2926 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2927 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2928 args = self.expressions(expression) 2929 alias = self.sql(expression, "alias") 2930 values = f"VALUES{self.seg('')}{args}" 2931 values = ( 2932 f"({values})" 2933 if self.WRAP_DERIVED_VALUES 2934 and ( 2935 alias 2936 or isinstance(expression.parent, (exp.From, exp.Table, exp.MatchRecognize)) 2937 ) 2938 else values 2939 ) 2940 values = self.query_modifiers(expression, values) 2941 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2942 return f"{values} AS {alias}{pivots}" if alias else f"{values}{pivots}" 2943 2944 # Converts `VALUES...` expression into a series of select unions. 2945 alias_node = expression.args.get("alias") 2946 column_names = alias_node and alias_node.columns 2947 2948 selects: list[exp.Query] = [] 2949 2950 for i, tup in enumerate(expression.expressions): 2951 row = tup.expressions 2952 2953 if i == 0 and column_names: 2954 row = [ 2955 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2956 ] 2957 2958 selects.append(exp.Select(expressions=row)) 2959 2960 if self.pretty: 2961 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2962 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2963 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2964 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2965 for key in ("order", "limit", "offset"): 2966 if value := expression.args.get(key): 2967 query.set(key, value.pop()) 2968 subquery = query.subquery(alias_node and alias_node.this, copy=False) 2969 subquery.set("pivots", expression.args.pop("pivots", None)) 2970 return self.subquery_sql(subquery) 2971 2972 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2973 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2974 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2975 return f"({self.query_modifiers(expression, unions)}){alias}{pivots}" 2976 2977 def var_sql(self, expression: exp.Var) -> str: 2978 return self.sql(expression, "this") 2979 2980 @unsupported_args("expressions") 2981 def into_sql(self, expression: exp.Into) -> str: 2982 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2983 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2984 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2985 2986 def from_sql(self, expression: exp.From) -> str: 2987 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2988 2989 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2990 grouping_sets = self.expressions(expression, indent=False) 2991 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2992 2993 def rollup_sql(self, expression: exp.Rollup) -> str: 2994 expressions = self.expressions(expression, indent=False) 2995 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2996 2997 def rollupindex_sql(self, expression: exp.RollupIndex) -> str: 2998 this = self.sql(expression, "this") 2999 3000 columns = self.expressions(expression, flat=True) 3001 3002 from_sql = self.sql(expression, "from_index") 3003 from_sql = f" FROM {from_sql}" if from_sql else "" 3004 3005 properties = expression.args.get("properties") 3006 properties_sql = ( 3007 f" {self.properties(properties, prefix='PROPERTIES')}" if properties else "" 3008 ) 3009 3010 return f"{this}({columns}){from_sql}{properties_sql}" 3011 3012 def rollupproperty_sql(self, expression: exp.RollupProperty) -> str: 3013 return f"ROLLUP ({self.expressions(expression, flat=True)})" 3014 3015 def cube_sql(self, expression: exp.Cube) -> str: 3016 expressions = self.expressions(expression, indent=False) 3017 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 3018 3019 def group_sql(self, expression: exp.Group) -> str: 3020 group_by_all = expression.args.get("all") 3021 if group_by_all is True: 3022 modifier = " ALL" 3023 elif group_by_all is False: 3024 modifier = " DISTINCT" 3025 else: 3026 modifier = "" 3027 3028 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 3029 3030 grouping_sets = self.expressions(expression, key="grouping_sets") 3031 cube = self.expressions(expression, key="cube") 3032 rollup = self.expressions(expression, key="rollup") 3033 3034 groupings = csv( 3035 self.seg(grouping_sets) if grouping_sets else "", 3036 self.seg(cube) if cube else "", 3037 self.seg(rollup) if rollup else "", 3038 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 3039 sep=self.GROUPINGS_SEP, 3040 ) 3041 3042 if ( 3043 expression.expressions 3044 and groupings 3045 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 3046 ): 3047 add_separator = True 3048 3049 if grouping_sets: 3050 if self.SUPPORTS_GROUPING_SETS_AS_SUFFIX: 3051 add_separator = False 3052 else: 3053 self.unsupported( 3054 "GROUPING SETS without a comma after GROUP BY expressions is not supported" 3055 ) 3056 3057 if add_separator: 3058 group_by = f"{group_by}{self.GROUPINGS_SEP}" 3059 3060 return f"{group_by}{groupings}" 3061 3062 def having_sql(self, expression: exp.Having) -> str: 3063 this = self.indent(self.sql(expression, "this")) 3064 return f"{self.seg('HAVING')}{self.sep()}{this}" 3065 3066 def connectto_sql(self, expression: exp.ConnectTo) -> str: 3067 return f"CONNECT {self.sql(expression, 'this')}" 3068 3069 def disconnect_sql(self, expression: exp.Disconnect) -> str: 3070 return "DISCONNECT" 3071 3072 def connect_sql(self, expression: exp.Connect) -> str: 3073 start = self.sql(expression, "start") 3074 start = self.seg(f"START WITH {start}") if start else "" 3075 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 3076 connect = self.sql(expression, "connect") 3077 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 3078 return start + connect 3079 3080 def prior_sql(self, expression: exp.Prior) -> str: 3081 return f"PRIOR {self.sql(expression, 'this')}" 3082 3083 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3084 if ( 3085 match_condition := expression.args.get("match_condition") 3086 ) and not self.SUPPORTS_MATCH_CONDITION: 3087 if self.MATCH_CONDITION_IN_ON and not expression.args.get("using"): 3088 expression = expression.on(match_condition) 3089 expression.set("match_condition", None) 3090 # Snowflake ASOF joins preserve unmatched left rows. 3091 expression.set("side", "LEFT") 3092 else: 3093 self.unsupported("MATCH_CONDITION is not supported") 3094 3095 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 3096 side = None 3097 else: 3098 side = expression.side 3099 3100 op_sql = " ".join( 3101 op 3102 for op in ( 3103 expression.method, 3104 "GLOBAL" if expression.args.get("global_") else None, 3105 side, 3106 expression.kind, 3107 expression.hint if self.JOIN_HINTS else None, 3108 "DIRECTED" if expression.args.get("directed") and self.DIRECTED_JOINS else None, 3109 ) 3110 if op 3111 ) 3112 match_cond = self.sql(expression, "match_condition") 3113 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 3114 nearest = self.sql(expression, "nearest") 3115 nearest = f" {nearest}" if nearest else "" 3116 on_sql = self.sql(expression, "on") 3117 using = expression.args.get("using") 3118 3119 if not on_sql and using: 3120 on_sql = csv(*(self.sql(column) for column in using)) 3121 3122 this = expression.this 3123 this_sql = self.sql(this) 3124 3125 exprs = self.expressions(expression) 3126 if exprs: 3127 this_sql = f"{this_sql},{self.seg(exprs)}" 3128 3129 if on_sql: 3130 on_sql = self.indent(on_sql, skip_first=True) 3131 space = self.seg(" " * self.pad) if self.pretty else " " 3132 if using: 3133 on_sql = f"{space}USING ({on_sql})" 3134 else: 3135 on_sql = f"{space}ON {on_sql}" 3136 elif not op_sql and not nearest: 3137 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 3138 return f" {this_sql}" 3139 3140 return f", {this_sql}" 3141 3142 if join_op: 3143 op_sql = join_op 3144 elif op_sql != "STRAIGHT_JOIN": 3145 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 3146 3147 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3148 return f"{self.seg(op_sql)} {this_sql}{match_cond}{nearest}{on_sql}{pivots}" 3149 3150 def nearest_sql(self, expression: exp.Nearest) -> str: 3151 if not self.SUPPORTS_NEAREST_JOIN: 3152 self.unsupported("NEAREST joins are not supported") 3153 3154 approximate = "APPROX " if expression.args.get("approximate") else "" 3155 metric = "SIMILARITY" if expression.args.get("similarity") else "DISTANCE" 3156 return f"{approximate}NEAREST {self.sql(expression, 'count')} BY {metric} {self.sql(expression, 'this')}" 3157 3158 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->", wrap: bool = True) -> str: 3159 args = self.expressions(expression, flat=True) 3160 args = f"({args})" if wrap and len(args.split(",")) > 1 else args 3161 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 3162 3163 def lateral_op(self, expression: exp.Lateral) -> str: 3164 cross_apply = expression.args.get("cross_apply") 3165 3166 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 3167 if cross_apply is True: 3168 op = "INNER JOIN " 3169 elif cross_apply is False: 3170 op = "LEFT JOIN " 3171 else: 3172 op = "" 3173 3174 return f"{op}LATERAL" 3175 3176 def lateral_sql(self, expression: exp.Lateral) -> str: 3177 this = self.sql(expression, "this") 3178 3179 if expression.args.get("view"): 3180 alias = expression.args["alias"] 3181 columns = self.expressions(alias, key="columns", flat=True) 3182 table = f" {alias.name}" if alias.name else "" 3183 columns = f" AS {columns}" if columns else "" 3184 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 3185 return f"{op_sql}{self.sep()}{this}{table}{columns}" 3186 3187 table_alias = expression.args.get("alias") 3188 offset = expression.this.args.get("offset") 3189 3190 if ( 3191 self.UNNEST_WITH_ORDINALITY 3192 and table_alias 3193 and isinstance(expression.this, exp.Unnest) 3194 and isinstance(offset, exp.Identifier) 3195 ): 3196 # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset 3197 table_alias = table_alias.copy() 3198 table_alias.append("columns", offset.copy()) 3199 3200 alias = self.sql(table_alias) 3201 alias = f" AS {alias}" if alias else "" 3202 3203 ordinality = expression.args.get("ordinality") or "" 3204 if ordinality: 3205 ordinality = f" WITH ORDINALITY{alias}" 3206 alias = "" 3207 3208 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}" 3209 3210 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 3211 this = self.sql(expression, "this") 3212 3213 if expression.is_limit_all and not self.dialect.SUPPORTS_LIMIT_ALL: 3214 return this 3215 3216 args = [ 3217 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 3218 for e in (expression.args.get(k) for k in ("offset", "expression")) 3219 if e 3220 ] 3221 3222 args_sql = ", ".join(self.sql(e) for e in args) 3223 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 3224 expressions = self.expressions(expression, flat=True) 3225 limit_options = self.sql(expression, "limit_options") 3226 expressions = f" BY {expressions}" if expressions else "" 3227 3228 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 3229 3230 def offset_sql(self, expression: exp.Offset) -> str: 3231 this = self.sql(expression, "this") 3232 value = expression.expression 3233 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 3234 expressions = self.expressions(expression, flat=True) 3235 expressions = f" BY {expressions}" if expressions else "" 3236 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 3237 3238 def setitem_sql(self, expression: exp.SetItem) -> str: 3239 kind = self.sql(expression, "kind") 3240 if not self.SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD and kind == "VARIABLE": 3241 kind = "" 3242 else: 3243 kind = f"{kind} " if kind else "" 3244 this = self.sql(expression, "this") 3245 expressions = self.expressions(expression) 3246 collate = self.sql(expression, "collate") 3247 collate = f" COLLATE {collate}" if collate else "" 3248 global_ = "GLOBAL " if expression.args.get("global_") else "" 3249 return f"{global_}{kind}{this}{expressions}{collate}" 3250 3251 def set_sql(self, expression: exp.Set) -> str: 3252 expressions = f" {self.expressions(expression, flat=True)}" 3253 tag = " TAG" if expression.args.get("tag") else "" 3254 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 3255 3256 def queryband_sql(self, expression: exp.QueryBand) -> str: 3257 this = self.sql(expression, "this") 3258 update = " UPDATE" if expression.args.get("update") else "" 3259 scope = self.sql(expression, "scope") 3260 scope = f" FOR {scope}" if scope else "" 3261 3262 return f"QUERY_BAND = {this}{update}{scope}" 3263 3264 def pragma_sql(self, expression: exp.Pragma) -> str: 3265 return f"PRAGMA {self.sql(expression, 'this')}" 3266 3267 def lock_sql(self, expression: exp.Lock) -> str: 3268 if not self.LOCKING_READS_SUPPORTED: 3269 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 3270 return "" 3271 3272 update = expression.args["update"] 3273 key = expression.args.get("key") 3274 if update: 3275 lock_type = "FOR NO KEY UPDATE" if key else "FOR UPDATE" 3276 else: 3277 lock_type = "FOR KEY SHARE" if key else "FOR SHARE" 3278 expressions = self.expressions(expression, flat=True) 3279 expressions = f" OF {expressions}" if expressions else "" 3280 wait = expression.args.get("wait") 3281 3282 if wait is not None: 3283 if isinstance(wait, exp.Literal): 3284 wait = f" WAIT {self.sql(wait)}" 3285 else: 3286 wait = " NOWAIT" if wait else " SKIP LOCKED" 3287 3288 return f"{lock_type}{expressions}{wait or ''}" 3289 3290 def literal_sql(self, expression: exp.Literal) -> str: 3291 text = expression.this or "" 3292 if expression.is_string: 3293 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 3294 return text 3295 3296 def escape_str( 3297 self, 3298 text: str, 3299 escape_backslash: bool = True, 3300 delimiter: str | None = None, 3301 escaped_delimiter: str | None = None, 3302 is_byte_string: bool = False, 3303 is_bytes: bool = False, 3304 ) -> str: 3305 if is_byte_string: 3306 supports_escape_sequences = self.dialect.BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES 3307 else: 3308 supports_escape_sequences = self.dialect.STRINGS_SUPPORT_ESCAPED_SEQUENCES 3309 3310 if supports_escape_sequences: 3311 text = "".join( 3312 self.dialect.ESCAPED_SEQUENCES.get(ch, ch) if escape_backslash or ch != "\\" else ch 3313 for ch in text 3314 ) 3315 3316 if is_bytes and "x" in self.dialect.tokenizer_class.NUMERIC_ESCAPES: 3317 # Escape high bytes so they aren't re-encoded as UTF-8 characters. 3318 text = _HIGH_BYTE_RE.sub(lambda m: f"\\x{ord(m.group()):02x}", text) 3319 3320 delimiter = delimiter or self.dialect.QUOTE_END 3321 escaped_delimiter = escaped_delimiter or self._escaped_quote_end 3322 3323 return self._replace_line_breaks(text).replace(delimiter, escaped_delimiter) 3324 3325 def loaddata_sql(self, expression: exp.LoadData) -> str: 3326 is_overwrite = expression.args.get("overwrite") 3327 overwrite = " OVERWRITE" if is_overwrite else "" 3328 this = self.sql(expression, "this") 3329 3330 files = expression.args.get("files") 3331 if files: 3332 files_sql = self.expressions(files, flat=True) 3333 files_sql = f"FILES{self.wrap(files_sql)}" 3334 if is_overwrite: 3335 this = f" {this}" 3336 elif expression.args.get("temp"): 3337 this = f" INTO TEMP TABLE {this}" 3338 else: 3339 this = f" INTO TABLE {this}" 3340 return f"LOAD DATA{overwrite}{this} FROM {files_sql}" 3341 3342 local = " LOCAL" if expression.args.get("local") else "" 3343 inpath = f" INPATH {self.sql(expression, 'inpath')}" 3344 this = f" INTO TABLE {this}" 3345 partition = self.sql(expression, "partition") 3346 partition = f" {partition}" if partition else "" 3347 input_format = self.sql(expression, "input_format") 3348 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 3349 serde = self.sql(expression, "serde") 3350 serde = f" SERDE {serde}" if serde else "" 3351 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 3352 3353 def null_sql(self, *_) -> str: 3354 return "NULL" 3355 3356 def boolean_sql(self, expression: exp.Boolean) -> str: 3357 return "TRUE" if expression.this else "FALSE" 3358 3359 def booland_sql(self, expression: exp.Booland) -> str: 3360 return f"(({self.sql(expression, 'this')}) AND ({self.sql(expression, 'expression')}))" 3361 3362 def boolor_sql(self, expression: exp.Boolor) -> str: 3363 return f"(({self.sql(expression, 'this')}) OR ({self.sql(expression, 'expression')}))" 3364 3365 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 3366 this = self.sql(expression, "this") 3367 this = f"{this} " if this else this 3368 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 3369 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=bool(this) or flat) 3370 3371 def withfill_sql(self, expression: exp.WithFill) -> str: 3372 from_sql = self.sql(expression, "from_") 3373 from_sql = f" FROM {from_sql}" if from_sql else "" 3374 to_sql = self.sql(expression, "to") 3375 to_sql = f" TO {to_sql}" if to_sql else "" 3376 step_sql = self.sql(expression, "step") 3377 step_sql = f" STEP {step_sql}" if step_sql else "" 3378 interpolated_values = [ 3379 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 3380 if isinstance(e, exp.Alias) 3381 else self.sql(e, "this") 3382 for e in expression.args.get("interpolate") or [] 3383 ] 3384 interpolate = ( 3385 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 3386 ) 3387 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 3388 3389 def cluster_sql(self, expression: exp.Cluster) -> str: 3390 return self.op_expressions("CLUSTER BY", expression) 3391 3392 def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str: 3393 if expression.this: 3394 self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}") 3395 return "" 3396 expressions = self.expressions(expression, flat=True) 3397 return f"CLUSTER BY ({expressions})" 3398 3399 def distribute_sql(self, expression: exp.Distribute) -> str: 3400 return self.op_expressions("DISTRIBUTE BY", expression) 3401 3402 def sort_sql(self, expression: exp.Sort) -> str: 3403 return self.op_expressions("SORT BY", expression) 3404 3405 def _resolve_ordered_for_null_ordering_simulation( 3406 self, expression: exp.Ordered 3407 ) -> exp.Expr | None: 3408 """Resolve a bare ORDER BY name against the enclosing SELECT projection. 3409 3410 Returns the underlying expression of the uniquely-matching projection 3411 (Alias-stripped) for substitution into the NULLS FIRST/LAST CASE 3412 simulation, since the CASE is evaluated in FROM-clause scope rather 3413 than alias scope (MySQL error 1052). Returns None if no safe 3414 substitution applies, leaving the original behaviour unchanged. 3415 """ 3416 this = expression.this 3417 if not (isinstance(this, exp.Column) and not this.table): 3418 return None 3419 3420 # Only a query's own ORDER BY can reference its projection aliases 3421 order = expression.parent 3422 ancestor = order.parent if isinstance(order, exp.Order) else None 3423 if not isinstance(ancestor, exp.Select): 3424 return None 3425 3426 column_name = this.name 3427 matched: list[exp.Expr] = [ 3428 p.this if isinstance(p, exp.Alias) else p 3429 for p in ancestor.selects 3430 if p.output_name == column_name 3431 ] 3432 match = matched[0] if len(matched) == 1 else None 3433 3434 # Skip the substitution when it would be identical to the existing 3435 # reference (e.g. ``SELECT col FROM t ORDER BY col``). 3436 if isinstance(match, exp.Column) and not match.table and match.name == column_name: 3437 return None 3438 3439 return match 3440 3441 def ordered_sql(self, expression: exp.Ordered) -> str: 3442 desc = expression.args.get("desc") 3443 asc = not desc 3444 3445 nulls_first = expression.args.get("nulls_first") 3446 nulls_last = not nulls_first 3447 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 3448 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 3449 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 3450 3451 this = self.sql(expression, "this") 3452 3453 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 3454 nulls_sort_change = "" 3455 if nulls_first and ( 3456 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 3457 ): 3458 nulls_sort_change = " NULLS FIRST" 3459 elif ( 3460 nulls_last 3461 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 3462 and not nulls_are_last 3463 ): 3464 nulls_sort_change = " NULLS LAST" 3465 3466 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 3467 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 3468 window = expression.find_ancestor(exp.Window, exp.Select) 3469 3470 if isinstance(window, exp.Window): 3471 window_this = window.this 3472 if isinstance(window_this, (exp.IgnoreNulls, exp.RespectNulls)): 3473 window_this = window_this.this 3474 spec = window.args.get("spec") 3475 else: 3476 window_this = None 3477 spec = None 3478 3479 # Some window functions (e.g. LAST_VALUE, RANK) support NULLS FIRST/LAST 3480 # without a spec or with a ROWS spec, but not with RANGE 3481 if not ( 3482 isinstance(window_this, self.WINDOW_FUNCS_WITH_NULL_ORDERING) 3483 and (not spec or spec.text("kind").upper() == "ROWS") 3484 ): 3485 if window_this and spec: 3486 self.unsupported( 3487 f"'{nulls_sort_change.strip()}' translation not supported in window function {window_this.sql_name()}" 3488 ) 3489 nulls_sort_change = "" 3490 elif self.NULL_ORDERING_SUPPORTED is False and ( 3491 (asc and nulls_sort_change == " NULLS LAST") 3492 or (desc and nulls_sort_change == " NULLS FIRST") 3493 ): 3494 # BigQuery does not allow these ordering/nulls combinations when used under 3495 # an aggregation func or under a window containing one 3496 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 3497 3498 if isinstance(ancestor, exp.Window): 3499 ancestor = ancestor.this 3500 if isinstance(ancestor, exp.AggFunc): 3501 self.unsupported( 3502 f"'{nulls_sort_change.strip()}' translation not supported for aggregate function {ancestor.sql_name()} with {sort_order} sort order" 3503 ) 3504 nulls_sort_change = "" 3505 elif self.NULL_ORDERING_SUPPORTED is None: 3506 if expression.this.is_int: 3507 self.unsupported( 3508 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 3509 ) 3510 elif not isinstance(expression.this, exp.Rand): 3511 resolved = self._resolve_ordered_for_null_ordering_simulation(expression) 3512 target = self.sql(resolved) if resolved is not None else this 3513 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 3514 this = f"CASE WHEN {target} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {target}" 3515 nulls_sort_change = "" 3516 3517 with_fill = self.sql(expression, "with_fill") 3518 with_fill = f" {with_fill}" if with_fill else "" 3519 3520 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 3521 3522 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 3523 window_frame = self.sql(expression, "window_frame") 3524 window_frame = f"{window_frame} " if window_frame else "" 3525 3526 this = self.sql(expression, "this") 3527 3528 return f"{window_frame}{this}" 3529 3530 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 3531 partition = self.partition_by_sql(expression) 3532 order = self.sql(expression, "order") 3533 measures = self.expressions(expression, key="measures") 3534 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 3535 rows = self.sql(expression, "rows") 3536 rows = self.seg(rows) if rows else "" 3537 after = self.sql(expression, "after") 3538 after = self.seg(after) if after else "" 3539 pattern = self.sql(expression, "pattern") 3540 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 3541 subset = self.expressions(expression, key="subset") 3542 subset = self.seg(f"SUBSET{self.seg(subset)}") if subset else "" 3543 definition_sqls = [ 3544 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 3545 for definition in expression.args.get("define") or [] 3546 ] 3547 definitions = self.expressions(sqls=definition_sqls) 3548 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 3549 body = "".join( 3550 ( 3551 partition, 3552 order, 3553 measures, 3554 rows, 3555 after, 3556 pattern, 3557 subset, 3558 define, 3559 ) 3560 ).lstrip() 3561 alias = self.sql(expression, "alias") 3562 alias = f" {alias}" if alias else "" 3563 sample = self.sql(expression, "sample") 3564 joins = self.indent( 3565 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 3566 ) 3567 source = self.sql(expression, "this") 3568 return f"{source}{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}{sample}{joins}" 3569 3570 def query_modifiers(self, expression: exp.Expr, *sqls: str) -> str: 3571 limit = expression.args.get("limit") 3572 3573 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 3574 count = limit.args.get("count") 3575 # "FETCH FIRST ROWS ONLY" without a count means one row per the SQL 3576 # standard; emitting a bare "LIMIT" here would produce invalid SQL. 3577 limit = exp.Limit( 3578 expression=exp.maybe_copy(count) if count is not None else exp.Literal.number(1) 3579 ) 3580 elif ( 3581 self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit) and not limit.is_limit_all 3582 ): 3583 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 3584 3585 return csv( 3586 *sqls, 3587 *[self.sql(join) for join in expression.args.get("joins") or []], 3588 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 3589 self.sql(expression, "prewhere"), 3590 self.sql(expression, "where"), 3591 self.sql(expression, "connect"), 3592 self.sql(expression, "group"), 3593 self.sql(expression, "having"), 3594 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 3595 self.sql(expression, "order"), 3596 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 3597 *self.after_limit_modifiers(expression), 3598 self.sql(expression, "for_"), 3599 self.options_modifier(expression), 3600 sep="", 3601 ) 3602 3603 def options_modifier(self, expression: exp.Expr) -> str: 3604 options = self.expressions(expression, key="options") 3605 return f" {options}" if options else "" 3606 3607 def forclause_sql(self, expression: exp.ForClause) -> str: 3608 kind = expression.args["kind"] 3609 if kind == "BROWSE": 3610 return f"{self.sep()}FOR BROWSE" 3611 # FOR XML/JSON always carry at least AUTO/PATH. An empty rendering means 3612 # the target dialect doesn't support QueryOption, so we drop the clause. 3613 options = self.expressions(expression, key="expressions") 3614 if not options: 3615 return "" 3616 return f"{self.sep()}FOR {kind}{self.seg(options)}" 3617 3618 def queryoption_sql(self, expression: exp.QueryOption) -> str: 3619 self.unsupported("Unsupported query option.") 3620 return "" 3621 3622 def offset_limit_modifiers( 3623 self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None 3624 ) -> list[str]: 3625 return [ 3626 self.sql(expression, "offset") if fetch else self.sql(limit), 3627 self.sql(limit) if fetch else self.sql(expression, "offset"), 3628 ] 3629 3630 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 3631 locks = self.expressions(expression, key="locks", sep=" ") 3632 locks = f" {locks}" if locks else "" 3633 return [locks, self.sql(expression, "sample")] 3634 3635 def select_sql(self, expression: exp.Select) -> str: 3636 into = expression.args.get("into") 3637 if not self.SUPPORTS_SELECT_INTO and into: 3638 into.pop() 3639 3640 hint = self.sql(expression, "hint") 3641 distinct = self.sql(expression, "distinct") 3642 distinct = f" {distinct}" if distinct else "" 3643 kind = self.sql(expression, "kind") 3644 3645 limit = expression.args.get("limit") 3646 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 3647 top = self.limit_sql(limit, top=True) 3648 limit.pop() 3649 else: 3650 top = "" 3651 3652 expressions = self.expressions(expression) 3653 3654 if kind: 3655 if kind in self.SELECT_KINDS: 3656 kind = f" AS {kind}" 3657 else: 3658 if kind == "STRUCT": 3659 expressions = self.expressions( 3660 sqls=[ 3661 self.sql( 3662 exp.Struct( 3663 expressions=[ 3664 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 3665 if isinstance(e, exp.Alias) 3666 else e 3667 for e in expression.expressions 3668 ] 3669 ) 3670 ) 3671 ] 3672 ) 3673 kind = "" 3674 3675 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 3676 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 3677 3678 exclude = expression.args.get("exclude") 3679 3680 if not self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3681 exclude_sql = self.expressions(sqls=exclude, flat=True) 3682 expressions = f"{expressions}{self.seg('EXCLUDE')} ({exclude_sql})" 3683 3684 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 3685 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 3686 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 3687 expressions = f"{self.sep()}{expressions}" if expressions else expressions 3688 sql = self.query_modifiers( 3689 expression, 3690 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 3691 self.sql(expression, "into", comment=False), 3692 self.sql(expression, "from_", comment=False), 3693 ) 3694 3695 # If both the CTE and SELECT clauses have comments, generate the latter earlier 3696 if expression.args.get("with_"): 3697 sql = self.maybe_comment(sql, expression) 3698 expression.pop_comments() 3699 3700 sql = self.prepend_ctes(expression, sql) 3701 3702 if self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3703 expression.set("exclude", None) 3704 subquery = expression.subquery(copy=False) 3705 star = exp.Star(except_=exclude) 3706 sql = self.sql(exp.select(star).from_(subquery, copy=False)) 3707 3708 if not self.SUPPORTS_SELECT_INTO and into: 3709 if into.args.get("temporary"): 3710 table_kind = " TEMPORARY" 3711 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 3712 table_kind = " UNLOGGED" 3713 else: 3714 table_kind = "" 3715 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 3716 3717 return sql 3718 3719 def schema_sql(self, expression: exp.Schema) -> str: 3720 this = self.sql(expression, "this") 3721 sql = self.schema_columns_sql(expression) 3722 return f"{this} {sql}" if this and sql else this or sql 3723 3724 def schema_columns_sql(self, expression: exp.Expr) -> str: 3725 if expression.expressions: 3726 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 3727 return "" 3728 3729 def star_sql(self, expression: exp.Star) -> str: 3730 except_ = self.expressions(expression, key="except_", flat=True) 3731 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 3732 replace = self.expressions(expression, key="replace", flat=True) 3733 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 3734 rename = self.expressions(expression, key="rename", flat=True) 3735 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 3736 ilike = self.sql(expression, "ilike") 3737 ilike = f"{self.seg('ILIKE')} {ilike}" if ilike else "" 3738 return f"*{ilike}{except_}{replace}{rename}" 3739 3740 def parameter_sql(self, expression: exp.Parameter) -> str: 3741 this = self.sql(expression, "this") 3742 return f"{self.PARAMETER_TOKEN}{this}" 3743 3744 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 3745 this = self.sql(expression, "this") 3746 kind = expression.text("kind") 3747 if kind: 3748 kind = f"{kind}." 3749 return f"@@{kind}{this}" 3750 3751 def placeholder_sql(self, expression: exp.Placeholder) -> str: 3752 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 3753 3754 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 3755 alias = self.sql(expression, "alias") 3756 alias = f"{sep}{alias}" if alias else "" 3757 sample = self.sql(expression, "sample") 3758 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 3759 alias = f"{sample}{alias}" 3760 3761 # Set to None so it's not generated again by self.query_modifiers() 3762 expression.set("sample", None) 3763 3764 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3765 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 3766 return self.prepend_ctes(expression, sql) 3767 3768 def qualify_sql(self, expression: exp.Qualify) -> str: 3769 this = self.indent(self.sql(expression, "this")) 3770 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 3771 3772 def unnest_sql(self, expression: exp.Unnest) -> str: 3773 args = self.expressions(expression, flat=True) 3774 3775 alias = expression.args.get("alias") 3776 offset = expression.args.get("offset") 3777 3778 if self.UNNEST_WITH_ORDINALITY: 3779 if alias and isinstance(offset, exp.Expr): 3780 alias.append("columns", offset) 3781 expression.set("offset", None) 3782 3783 if alias and self.dialect.UNNEST_COLUMN_ONLY: 3784 columns = alias.columns 3785 alias = self.sql(columns[0]) if columns else "" 3786 else: 3787 alias = self.sql(alias) 3788 3789 alias = f" AS {alias}" if alias else alias 3790 if self.UNNEST_WITH_ORDINALITY: 3791 suffix = f" WITH ORDINALITY{alias}" if offset else alias 3792 else: 3793 if isinstance(offset, exp.Expr): 3794 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 3795 elif offset: 3796 suffix = f"{alias} WITH OFFSET" 3797 else: 3798 suffix = alias 3799 3800 return f"UNNEST({args}){suffix}" 3801 3802 def prewhere_sql(self, expression: exp.PreWhere) -> str: 3803 return "" 3804 3805 def where_sql(self, expression: exp.Where) -> str: 3806 this = self.indent(self.sql(expression, "this")) 3807 return f"{self.seg('WHERE')}{self.sep()}{this}" 3808 3809 def window_sql(self, expression: exp.Window) -> str: 3810 if ( 3811 isinstance(expression.this, exp.Variance) 3812 and expression.this.args.get("single_value_returns_zero") 3813 and expression.text("over") != "KEEP" 3814 and not self.VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE 3815 ): 3816 return self.variance_sql(expression.this, window=expression) 3817 3818 this = self.sql(expression, "this") 3819 partition = self.partition_by_sql(expression) 3820 order = expression.args.get("order") 3821 if not order and self.WINDOW_FUNCS_REQUIRING_ORDER and not expression.args.get("alias"): 3822 func = expression.this 3823 if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)): 3824 func = func.this 3825 if isinstance(func, self.WINDOW_FUNCS_REQUIRING_ORDER): 3826 # Without an ordering all rows of a partition are peers, which is 3827 # also the case when ordering by the partition keys themselves 3828 partition_by = expression.args.get("partition_by") 3829 order = exp.Order( 3830 expressions=[e.copy() for e in partition_by] if partition_by else [exp.null()] 3831 ) 3832 order = self.order_sql(order, flat=True) if order else "" 3833 spec = self.sql(expression, "spec") 3834 alias = self.sql(expression, "alias") 3835 over = self.sql(expression, "over") or "OVER" 3836 3837 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 3838 3839 first = expression.args.get("first") 3840 if first is None: 3841 first = "" 3842 else: 3843 first = "FIRST" if first else "LAST" 3844 3845 if not partition and not order and not spec and alias: 3846 # WINDOW w2 AS w1 is unparseable in DuckDB/Postgres; parens are required. 3847 if expression.arg_key == "windows": 3848 return f"{this} ({alias})" 3849 return f"{this} {alias}" 3850 3851 args = self.format_args( 3852 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 3853 ) 3854 return f"{this} ({args})" 3855 3856 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 3857 partition = self.expressions(expression, key="partition_by", flat=True) 3858 return f"PARTITION BY {partition}" if partition else "" 3859 3860 def partitionbyexcluding_sql(self, expression: exp.PartitionByExcluding) -> str: 3861 return f"EXCLUDING {self.expressions(expression, flat=True)}" 3862 3863 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 3864 kind = self.sql(expression, "kind") 3865 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 3866 end = ( 3867 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 3868 or "CURRENT ROW" 3869 ) 3870 3871 window_spec = f"{kind} BETWEEN {start} AND {end}" 3872 3873 exclude = self.sql(expression, "exclude") 3874 if exclude: 3875 if self.SUPPORTS_WINDOW_EXCLUDE: 3876 window_spec += f" EXCLUDE {exclude}" 3877 else: 3878 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 3879 3880 return window_spec 3881 3882 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 3883 this = self.sql(expression, "this") 3884 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 3885 return f"{this} WITHIN GROUP ({expression_sql})" 3886 3887 def between_sql(self, expression: exp.Between) -> str: 3888 this = self.sql(expression, "this") 3889 low = self.sql(expression, "low") 3890 high = self.sql(expression, "high") 3891 symmetric = expression.args.get("symmetric") 3892 3893 if symmetric and not self.SUPPORTS_BETWEEN_FLAGS: 3894 return f"({this} BETWEEN {low} AND {high} OR {this} BETWEEN {high} AND {low})" 3895 3896 flag = ( 3897 " SYMMETRIC" 3898 if symmetric 3899 else " ASYMMETRIC" 3900 if symmetric is False and self.SUPPORTS_BETWEEN_FLAGS 3901 else "" # silently drop ASYMMETRIC – semantics identical 3902 ) 3903 return f"{this} BETWEEN{flag} {low} AND {high}" 3904 3905 def bracket_offset_expressions( 3906 self, expression: exp.Bracket, index_offset: int | None = None 3907 ) -> list[exp.Expr]: 3908 if expression.args.get("json_access"): 3909 return expression.expressions 3910 3911 return apply_index_offset( 3912 expression.this, 3913 expression.expressions, 3914 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 3915 dialect=self.dialect, 3916 ) 3917 3918 def bracket_sql(self, expression: exp.Bracket) -> str: 3919 expressions = self.bracket_offset_expressions(expression) 3920 expressions_sql = ", ".join(self.sql(e) for e in expressions) 3921 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 3922 3923 def all_sql(self, expression: exp.All) -> str: 3924 this = self.sql(expression, "this") 3925 if not isinstance(expression.this, (exp.Tuple, exp.Paren)): 3926 this = self.wrap(this) 3927 return f"ALL {this}" 3928 3929 def any_sql(self, expression: exp.Any) -> str: 3930 this = self.sql(expression, "this") 3931 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 3932 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 3933 this = self.wrap(this) 3934 return f"ANY{this}" 3935 return f"ANY {this}" 3936 3937 def exists_sql(self, expression: exp.Exists) -> str: 3938 predicate = expression.expression 3939 if not predicate: 3940 return f"EXISTS{self.wrap(expression)}" 3941 3942 # Spark's EXISTS(array, lambda) 3943 if self.CAN_IMPLEMENT_ARRAY_ANY: 3944 filtered = exp.ArrayFilter(this=expression.this, expression=predicate) 3945 return self.sql(exp.paren(exp.ArraySize(this=filtered).neq(0))) 3946 3947 self.unsupported("EXISTS with a lambda predicate is unsupported") 3948 return self.function_fallback_sql(expression) 3949 3950 def case_sql(self, expression: exp.Case) -> str: 3951 this = self.sql(expression, "this") 3952 statements = [f"CASE {this}" if this else "CASE"] 3953 3954 for e in expression.args["ifs"]: 3955 statements.append(f"WHEN {self.sql(e, 'this')}") 3956 statements.append(f"THEN {self.sql(e, 'true')}") 3957 3958 default = self.sql(expression, "default") 3959 3960 if default: 3961 statements.append(f"ELSE {default}") 3962 3963 statements.append("END") 3964 3965 if self.pretty and self.too_wide(statements): 3966 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 3967 3968 return " ".join(statements) 3969 3970 def constraint_sql(self, expression: exp.Constraint) -> str: 3971 this = self.sql(expression, "this") 3972 expressions = self.expressions(expression, flat=True) 3973 return f"CONSTRAINT {this} {expressions}" 3974 3975 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 3976 order = expression.args.get("order") 3977 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 3978 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 3979 3980 def dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 3981 if bool(expression.args.get("zero_based")) == self.DAYOFWEEK_ZERO_BASED: 3982 return self._native_dayofweek_sql(expression) 3983 3984 adjusted = expression + 1 if self.DAYOFWEEK_ZERO_BASED else expression - 1 3985 adjusted.this.set("zero_based", self.DAYOFWEEK_ZERO_BASED) 3986 # The outer DayOfWeek already emits the function's comments. 3987 adjusted.this.pop_comments() 3988 return self.sql(exp.paren(adjusted, copy=False)) 3989 3990 def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 3991 return self.func(self.DAYOFWEEK_NAME or self.function_name(expression), expression.this) 3992 3993 def extract_date_part(self, part: exp.Expr) -> exp.Expr: 3994 mapping = self.dialect.EXTRACT_DATE_PART_MAPPING 3995 if self.NORMALIZE_EXTRACT_DATE_PARTS and part.name.upper() not in mapping: 3996 mapping = self.dialect.DATE_PART_MAPPING 3997 if mapping: 3998 import sqlglot.dialects.dialect 3999 4000 return sqlglot.dialects.dialect.map_date_part(part, mapping=mapping) 4001 return part 4002 4003 def extract_sql(self, expression: exp.Extract) -> str: 4004 this = self.extract_date_part(expression.this) 4005 if self.EXTRACT_ALLOWS_QUOTES: 4006 this_sql = self.sql(this) 4007 elif isinstance(this, exp.WeekStart): 4008 this_sql = self.weekstart_name(this) 4009 else: 4010 this_sql = this.name 4011 expression_sql = self.sql(expression, "expression") 4012 4013 return f"EXTRACT({this_sql} FROM {expression_sql})" 4014 4015 def trim_sql(self, expression: exp.Trim) -> str: 4016 trim_type = self.sql(expression, "position") 4017 4018 if trim_type == "LEADING": 4019 func_name = "LTRIM" 4020 elif trim_type == "TRAILING": 4021 func_name = "RTRIM" 4022 else: 4023 func_name = "TRIM" 4024 4025 return self.func(func_name, expression.this, expression.expression) 4026 4027 def convert_concat_args(self, expression: exp.Func) -> list[exp.Expr]: 4028 args = expression.expressions 4029 if isinstance(expression, exp.ConcatWs): 4030 args = args[1:] # Skip the delimiter 4031 4032 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 4033 args = [exp.cast(e, exp.DType.TEXT) for e in args] 4034 4035 concat_coalesce = ( 4036 self.dialect.CONCAT_WS_COALESCE 4037 if isinstance(expression, exp.ConcatWs) 4038 else self.dialect.CONCAT_COALESCE 4039 ) 4040 4041 if not concat_coalesce and expression.args.get("coalesce"): 4042 4043 def _wrap_with_coalesce(e: exp.Expr) -> exp.Expr: 4044 if not e.type: 4045 import sqlglot.optimizer.annotate_types 4046 4047 e = sqlglot.optimizer.annotate_types.annotate_types(e, dialect=self.dialect) 4048 4049 if e.is_string or e.is_type(exp.DType.ARRAY): 4050 return e 4051 4052 return exp.func("coalesce", e, exp.Literal.string("")) 4053 4054 args = [_wrap_with_coalesce(e) for e in args] 4055 4056 return args 4057 4058 def concat_sql(self, expression: exp.Concat) -> str: 4059 if self.dialect.CONCAT_COALESCE and not expression.args.get("coalesce"): 4060 # Dialect's CONCAT function coalesces NULLs to empty strings, but the expression does not. 4061 # Transpile to double pipe operators, which typically returns NULL if any args are NULL 4062 # instead of coalescing them to empty string. 4063 import sqlglot.dialects.dialect 4064 4065 return sqlglot.dialects.dialect.concat_to_dpipe_sql(self, expression) 4066 4067 expressions = self.convert_concat_args(expression) 4068 4069 # Some dialects don't allow a single-argument CONCAT call 4070 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 4071 return self.sql(expressions[0]) 4072 4073 return self.func("CONCAT", *expressions) 4074 4075 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4076 if self.dialect.CONCAT_WS_COALESCE and not expression.args.get("coalesce"): 4077 # Dialect's CONCAT_WS function skips NULL args, but the expression does not. 4078 # Wrap the entire call in a CASE expression that returns NULL if any input IS NULL. 4079 all_args = expression.expressions 4080 expression.set("coalesce", True) 4081 return self.sql( 4082 exp.case() 4083 .when(exp.or_(*(arg.is_(exp.null()) for arg in all_args)), exp.null()) 4084 .else_(expression) 4085 ) 4086 4087 return self.func( 4088 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 4089 ) 4090 4091 def check_sql(self, expression: exp.Check) -> str: 4092 this = self.sql(expression, key="this") 4093 return f"CHECK ({this})" 4094 4095 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 4096 this = self.sql(expression, "this") 4097 this = f" {this}" if this else "" 4098 expressions = self.expressions(expression, flat=True) 4099 expressions = f" ({expressions})" if expressions else "" 4100 reference = self.sql(expression, "reference") 4101 reference = f" {reference}" if reference else "" 4102 delete = self.sql(expression, "delete") 4103 delete = f" ON DELETE {delete}" if delete else "" 4104 update = self.sql(expression, "update") 4105 update = f" ON UPDATE {update}" if update else "" 4106 options = self.expressions(expression, key="options", flat=True, sep=" ") 4107 options = f" {options}" if options else "" 4108 return f"FOREIGN KEY{this}{expressions}{reference}{delete}{update}{options}" 4109 4110 def primarykey_sql(self, expression: exp.PrimaryKey) -> str: 4111 this = self.sql(expression, "this") 4112 this = f" {this}" if this else "" 4113 expressions = self.expressions(expression, flat=True) 4114 include = self.sql(expression, "include") 4115 options = self.expressions(expression, key="options", flat=True, sep=" ") 4116 options = f" {options}" if options else "" 4117 return f"PRIMARY KEY{this} ({expressions}){include}{options}" 4118 4119 def timeserieskey_sql(self, expression: exp.TimeseriesKey) -> str: 4120 self.unsupported("TIMESERIES primary key columns are not supported") 4121 return self.sql(expression, "this") 4122 4123 def if_sql(self, expression: exp.If) -> str: 4124 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 4125 4126 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 4127 if self.MATCH_AGAINST_TABLE_PREFIX: 4128 expressions = [] 4129 for expr in expression.expressions: 4130 if isinstance(expr, exp.Table): 4131 expressions.append(f"TABLE {self.sql(expr)}") 4132 else: 4133 expressions.append(expr) 4134 else: 4135 expressions = expression.expressions 4136 4137 modifier = expression.args.get("modifier") 4138 modifier = f" {modifier}" if modifier else "" 4139 return ( 4140 f"{self.func('MATCH', *expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 4141 ) 4142 4143 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 4144 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 4145 4146 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 4147 path = self.expressions(expression, sep="", flat=True).lstrip(".") 4148 4149 if self.QUOTE_JSON_PATH: 4150 path = self.escape_str(path) 4151 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 4152 4153 return path 4154 4155 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 4156 if isinstance(expression, exp.JSONPathPart): 4157 transform = self.TRANSFORMS.get(expression.__class__) 4158 if not callable(transform): 4159 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 4160 return "" 4161 4162 return transform(self, expression) 4163 4164 if isinstance(expression, int): 4165 return str(expression) 4166 4167 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 4168 escaped = expression.replace("'", "\\'") 4169 escaped = f"'{escaped}'" 4170 else: 4171 escaped = expression.replace('"', '\\"') 4172 escaped = f'"{escaped}"' 4173 4174 return escaped 4175 4176 def format_sql(self, expression: exp.Format) -> str: 4177 if ( 4178 expression.args.get("is_fmt") 4179 and expression.this.is_string 4180 and not expression.expressions 4181 and not any(c in expression.name for c in "{}") 4182 ): 4183 return self.sql(expression.this) 4184 4185 self._warn_unsupported_arg(expression, "is_fmt") 4186 return self.function_fallback_sql(expression) 4187 4188 def formatjson_sql(self, expression: exp.FormatJson) -> str: 4189 return f"{self.sql(expression, 'this')} FORMAT JSON" 4190 4191 def formatphrase_sql(self, expression: exp.FormatPhrase) -> str: 4192 # Output the Teradata column FORMAT override. 4193 # https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT 4194 this = self.sql(expression, "this") 4195 fmt = self.sql(expression, "format") 4196 return f"{this} (FORMAT {fmt})" 4197 4198 def teradataconversion_sql(self, expression: exp.TeradataConversion) -> str: 4199 self.unsupported("Teradata postfix conversion semantics are not supported") 4200 return self.sql(exp.cast(expression.this, expression.args["to"])) 4201 4202 def teradatatitle_sql(self, expression: exp.TeradataTitle) -> str: 4203 self.unsupported("Teradata TITLE display headings are not supported") 4204 return self.sql(expression, "this") 4205 4206 def teradatanamed_sql(self, expression: exp.TeradataNamed) -> str: 4207 self.unsupported("Teradata NAMED on subexpressions is not supported") 4208 return self.sql(expression, "this") 4209 4210 def _jsonobject_sql( 4211 self, expression: exp.JSONObject | exp.JSONObjectAgg, name: str = "" 4212 ) -> str: 4213 null_handling = expression.args.get("null_handling") 4214 null_handling = f" {null_handling}" if null_handling else "" 4215 4216 unique_keys = expression.args.get("unique_keys") 4217 if unique_keys is not None: 4218 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 4219 else: 4220 unique_keys = "" 4221 4222 return_type = self.sql(expression, "return_type") 4223 return_type = f" RETURNING {return_type}" if return_type else "" 4224 encoding = self.sql(expression, "encoding") 4225 encoding = f" ENCODING {encoding}" if encoding else "" 4226 4227 if not name: 4228 name = "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG" 4229 4230 return self.func( 4231 name, 4232 *expression.expressions, 4233 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 4234 ) 4235 4236 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 4237 null_handling = expression.args.get("null_handling") 4238 null_handling = f" {null_handling}" if null_handling else "" 4239 return_type = self.sql(expression, "return_type") 4240 return_type = f" RETURNING {return_type}" if return_type else "" 4241 strict = " STRICT" if expression.args.get("strict") else "" 4242 return self.func( 4243 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 4244 ) 4245 4246 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 4247 this = self.sql(expression, "this") 4248 order = self.sql(expression, "order") 4249 null_handling = expression.args.get("null_handling") 4250 null_handling = f" {null_handling}" if null_handling else "" 4251 return_type = self.sql(expression, "return_type") 4252 return_type = f" RETURNING {return_type}" if return_type else "" 4253 strict = " STRICT" if expression.args.get("strict") else "" 4254 return self.func( 4255 "JSON_ARRAYAGG", 4256 this, 4257 suffix=f"{order}{null_handling}{return_type}{strict})", 4258 ) 4259 4260 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 4261 path = self.sql(expression, "path") 4262 path = f" PATH {path}" if path else "" 4263 nested_schema = self.sql(expression, "nested_schema") 4264 4265 if nested_schema: 4266 return f"NESTED{path} {nested_schema}" 4267 4268 this = self.sql(expression, "this") 4269 kind = self.sql(expression, "kind") 4270 kind = f" {kind}" if kind else "" 4271 format_json = " FORMAT JSON" if expression.args.get("format_json") else "" 4272 4273 ordinality = " FOR ORDINALITY" if expression.args.get("ordinality") else "" 4274 return f"{this}{kind}{format_json}{path}{ordinality}" 4275 4276 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 4277 return self.func("COLUMNS", *expression.expressions) 4278 4279 def jsontable_sql(self, expression: exp.JSONTable) -> str: 4280 this = self.sql(expression, "this") 4281 path = self.sql(expression, "path") 4282 path = f", {path}" if path else "" 4283 error_handling = expression.args.get("error_handling") 4284 error_handling = f" {error_handling}" if error_handling else "" 4285 empty_handling = expression.args.get("empty_handling") 4286 empty_handling = f" {empty_handling}" if empty_handling else "" 4287 schema = self.sql(expression, "schema") 4288 return self.func( 4289 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 4290 ) 4291 4292 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 4293 this = self.sql(expression, "this") 4294 kind = self.sql(expression, "kind") 4295 path = self.sql(expression, "path") 4296 path = f" {path}" if path else "" 4297 as_json = " AS JSON" if expression.args.get("as_json") else "" 4298 return f"{this} {kind}{path}{as_json}" 4299 4300 def openjson_sql(self, expression: exp.OpenJSON) -> str: 4301 this = self.sql(expression, "this") 4302 path = self.sql(expression, "path") 4303 path = f", {path}" if path else "" 4304 expressions = self.expressions(expression) 4305 with_ = ( 4306 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 4307 if expressions 4308 else "" 4309 ) 4310 return f"OPENJSON({this}{path}){with_}" 4311 4312 def in_sql(self, expression: exp.In) -> str: 4313 query = expression.args.get("query") 4314 unnest = expression.args.get("unnest") 4315 field = expression.args.get("field") 4316 is_global = " GLOBAL" if expression.args.get("is_global") else "" 4317 4318 if query: 4319 in_sql = self.sql(query) 4320 elif unnest: 4321 in_sql = self.in_unnest_op(unnest) 4322 elif field: 4323 in_sql = self.sql(field) 4324 else: 4325 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 4326 4327 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 4328 4329 def in_unnest_op(self, unnest: exp.Unnest) -> str: 4330 return f"(SELECT {self.sql(unnest)})" 4331 4332 def interval_sql(self, expression: exp.Interval) -> str: 4333 include_keyword = not self.AUTO_REFRESH_BARE_INTERVALS or not isinstance( 4334 expression.find_ancestor(exp.AutoRefreshProperty, exp.Select), 4335 exp.AutoRefreshProperty, 4336 ) 4337 interval_keyword = "INTERVAL" if include_keyword else "" 4338 unit_expression = expression.args.get("unit") 4339 unit = self.sql(unit_expression) if unit_expression else "" 4340 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 4341 unit = self.TIME_PART_SINGULARS.get(unit, unit) 4342 unit = f" {unit}" if unit else "" 4343 4344 if self.SINGLE_STRING_INTERVAL: 4345 this = expression.this.name if expression.this else "" 4346 if this: 4347 interval_keyword = f"{interval_keyword} " if interval_keyword else "" 4348 if unit_expression and isinstance(unit_expression, exp.IntervalSpan): 4349 return f"{interval_keyword}{self.sql(exp.Literal.string(this))}{unit}" 4350 return f"{interval_keyword}{self.sql(exp.Literal.string(f'{this}{unit}'))}" 4351 return f"{interval_keyword}{unit}" 4352 4353 this = self.sql(expression, "this") 4354 if this: 4355 if not include_keyword and expression.this.is_string: 4356 this = expression.this.name 4357 if not isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES): 4358 this = f"({this})" 4359 if include_keyword: 4360 this = f" {this}" 4361 4362 return f"{interval_keyword}{this}{unit}" 4363 4364 def return_sql(self, expression: exp.Return) -> str: 4365 return f"RETURN {self.sql(expression, 'this')}" 4366 4367 def reference_sql(self, expression: exp.Reference) -> str: 4368 this = self.sql(expression, "this") 4369 expressions = self.expressions(expression, flat=True) 4370 expressions = f"({expressions})" if expressions else "" 4371 options = self.expressions(expression, key="options", flat=True, sep=" ") 4372 options = f" {options}" if options else "" 4373 return f"REFERENCES {this}{expressions}{options}" 4374 4375 def anonymous_sql(self, expression: exp.Anonymous) -> str: 4376 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 4377 parent = expression.parent 4378 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 4379 4380 return self.func( 4381 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 4382 ) 4383 4384 def paren_sql(self, expression: exp.Paren) -> str: 4385 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 4386 return f"({sql}{self.seg(')', sep='')}" 4387 4388 def pos_sql(self, expression: exp.Pos) -> str: 4389 return f"+{self.sql(expression, 'this')}" 4390 4391 def neg_sql(self, expression: exp.Neg) -> str: 4392 # This makes sure we don't convert "- - 5" to "--5", which is a comment 4393 this_sql = self.sql(expression, "this") 4394 sep = " " if this_sql[0] == "-" else "" 4395 return f"-{sep}{this_sql}" 4396 4397 def not_sql(self, expression: exp.Not) -> str: 4398 return f"NOT {self.sql(expression, 'this')}" 4399 4400 def alias_sql(self, expression: exp.Alias) -> str: 4401 alias = self.sql(expression, "alias") 4402 alias = f" AS {alias}" if alias else "" 4403 return f"{self.sql(expression, 'this')}{alias}" 4404 4405 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 4406 alias = expression.args["alias"] 4407 4408 parent = expression.parent 4409 pivot = parent and parent.parent 4410 4411 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 4412 identifier_alias = isinstance(alias, exp.Identifier) 4413 literal_alias = isinstance(alias, exp.Literal) 4414 4415 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4416 alias.replace(exp.Literal.string(alias.output_name)) 4417 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4418 alias.replace(exp.to_identifier(alias.output_name)) 4419 4420 return self.alias_sql(expression) 4421 4422 def aliases_sql(self, expression: exp.Aliases) -> str: 4423 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 4424 4425 def atindex_sql(self, expression: exp.AtIndex) -> str: 4426 this = self.sql(expression, "this") 4427 index = self.sql(expression, "expression") 4428 return f"{this} AT {index}" 4429 4430 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 4431 this = self.sql(expression, "this") 4432 zone = self.sql(expression, "zone") 4433 return f"{this} AT TIME ZONE {zone}" 4434 4435 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 4436 this = self.sql(expression, "this") 4437 zone = self.sql(expression, "zone") 4438 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 4439 4440 def fromiso8601date_sql(self, expression: exp.FromISO8601Date) -> str: 4441 return self.sql(exp.cast(expression.this, exp.DType.DATE)) 4442 4443 def fromiso8601timestamp_sql(self, expression: exp.FromISO8601Timestamp) -> str: 4444 return self.sql(exp.cast(expression.this, exp.DType.TIMESTAMPTZ)) 4445 4446 def fromiso8601timestampnanos_sql(self, expression: exp.FromISO8601TimestampNanos) -> str: 4447 return self.sql(exp.cast(expression.this, exp.DType.TIMESTAMPTZ)) 4448 4449 def add_sql(self, expression: exp.Add) -> str: 4450 return self.binary(expression, "+") 4451 4452 def and_sql(self, expression: exp.And, stack: list[str | exp.Expr] | None = None) -> str: 4453 return self.connector_sql(expression, "AND", stack) 4454 4455 def or_sql(self, expression: exp.Or, stack: list[str | exp.Expr] | None = None) -> str: 4456 return self.connector_sql(expression, "OR", stack) 4457 4458 def xor_sql(self, expression: exp.Xor, stack: list[str | exp.Expr] | None = None) -> str: 4459 return self.connector_sql(expression, "XOR", stack) 4460 4461 def connector_sql( 4462 self, 4463 expression: exp.Connector, 4464 op: str, 4465 stack: list[str | exp.Expr] | None = None, 4466 ) -> str: 4467 if stack is not None: 4468 stack.append(expression.right) 4469 if expression.comments and self.comments: 4470 op = self.maybe_comment(op, comments=expression.comments) 4471 4472 stack.extend((op, expression.left)) 4473 return op 4474 4475 stack = [expression] 4476 sqls: list[str] = [] 4477 ops = set() 4478 4479 while stack: 4480 node = stack.pop() 4481 if isinstance(node, exp.Connector): 4482 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 4483 else: 4484 sql = self.sql(node) 4485 if sqls and sqls[-1] in ops: 4486 sqls[-1] += f" {sql}" 4487 else: 4488 sqls.append(sql) 4489 4490 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 4491 return sep.join(sqls) 4492 4493 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 4494 return self.binary(expression, "&") 4495 4496 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 4497 return self.binary(expression, "<<") 4498 4499 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 4500 return f"~{self.sql(expression, 'this')}" 4501 4502 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 4503 return self.binary(expression, "|") 4504 4505 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 4506 return self.binary(expression, ">>") 4507 4508 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 4509 return self.binary(expression, "^") 4510 4511 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 4512 format_sql = self.sql(expression, "format") 4513 format_sql = f" FORMAT {format_sql}" if format_sql else "" 4514 to_sql = self.sql(expression, "to") 4515 to_sql = f" {to_sql}" if to_sql else "" 4516 action = self.sql(expression, "action") 4517 action = f" {action}" if action else "" 4518 default = self.sql(expression, "default") 4519 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 4520 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 4521 4522 # Base implementation that excludes safe, zone, and target_type metadata args 4523 def strtotime_sql(self, expression: exp.StrToTime) -> str: 4524 return self.func("STR_TO_TIME", expression.this, expression.args.get("format")) 4525 4526 # Base implementation that excludes the safe and default_year metadata args 4527 def strtodate_sql(self, expression: exp.StrToDate) -> str: 4528 return self.func("STR_TO_DATE", expression.this, expression.args.get("format")) 4529 4530 def parsedatetime_sql(self, expression: exp.ParseDatetime) -> str: 4531 return self.func( 4532 "PARSE_DATETIME", 4533 expression.this, 4534 expression.args.get("format"), 4535 expression.args.get("zone"), 4536 ) 4537 4538 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 4539 zone = self.sql(expression, "this") 4540 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 4541 4542 def collate_sql(self, expression: exp.Collate) -> str: 4543 if self.COLLATE_IS_FUNC: 4544 return self.function_fallback_sql(expression) 4545 return self.binary(expression, "COLLATE") 4546 4547 def command_sql(self, expression: exp.Command) -> str: 4548 args = expression.text("expression").lstrip() 4549 return f"{self.sql(expression, 'this')} {args}".rstrip(" \t") 4550 4551 def optimize_sql(self, expression: exp.Optimize) -> str: 4552 if not self.SUPPORTS_OPTIMIZE: 4553 self.unsupported("OPTIMIZE is only supported in Databricks") 4554 full = " FULL" if expression.args.get("full") else "" 4555 where = self.sql(expression, "where") 4556 columns = self.expressions(expression, key="zorder", flat=True) 4557 zorder = self.seg(f"ZORDER BY ({columns})") if columns else "" 4558 return f"OPTIMIZE {self.sql(expression, 'this')}{full}{where}{zorder}" 4559 4560 def comment_sql(self, expression: exp.Comment) -> str: 4561 this = self.sql(expression, "this") 4562 kind = expression.args["kind"] 4563 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 4564 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 4565 expression_sql = self.sql(expression, "expression") 4566 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 4567 4568 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 4569 this = self.sql(expression, "this") 4570 delete = " DELETE" if expression.args.get("delete") else "" 4571 recompress = self.sql(expression, "recompress") 4572 recompress = f" RECOMPRESS {recompress}" if recompress else "" 4573 to_disk = self.sql(expression, "to_disk") 4574 to_disk = f" TO DISK {to_disk}" if to_disk else "" 4575 to_volume = self.sql(expression, "to_volume") 4576 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 4577 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 4578 4579 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 4580 where = self.sql(expression, "where") 4581 group = self.sql(expression, "group") 4582 aggregates = self.expressions(expression, key="aggregates") 4583 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 4584 4585 if not (where or group or aggregates) and len(expression.expressions) == 1: 4586 return f"TTL {self.expressions(expression, flat=True)}" 4587 4588 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 4589 4590 def transaction_sql(self, expression: exp.Transaction) -> str: 4591 modes = self.expressions(expression, key="modes") 4592 modes = f" {modes}" if modes else "" 4593 return f"BEGIN{modes}" 4594 4595 def commit_sql(self, expression: exp.Commit) -> str: 4596 chain = expression.args.get("chain") 4597 if chain is not None: 4598 chain = " AND CHAIN" if chain else " AND NO CHAIN" 4599 4600 return f"COMMIT{chain or ''}" 4601 4602 def rollback_sql(self, expression: exp.Rollback) -> str: 4603 savepoint = expression.args.get("savepoint") 4604 savepoint = f" TO {savepoint}" if savepoint else "" 4605 return f"ROLLBACK{savepoint}" 4606 4607 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 4608 this = self.sql(expression, "this") 4609 4610 exists = "" 4611 if expression.args.get("exists"): 4612 if self.SUPPORTS_ALTER_COLUMN_IF_EXISTS: 4613 exists = " IF EXISTS" 4614 else: 4615 self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect") 4616 4617 dtype = self.sql(expression, "dtype") 4618 if dtype: 4619 collate = self.sql(expression, "collate") 4620 collate = f" COLLATE {collate}" if collate else "" 4621 using = self.sql(expression, "using") 4622 using = f" USING {using}" if using else "" 4623 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 4624 null_constraint = self._alter_column_null_constraint_sql(expression) 4625 4626 return ( 4627 f"ALTER COLUMN{exists} {this} {alter_set_type}{dtype}" 4628 f"{collate}{using}{null_constraint}" 4629 ) 4630 4631 default = self.sql(expression, "default") 4632 if default: 4633 return f"ALTER COLUMN{exists} {this} SET DEFAULT {default}" 4634 4635 comment = self.sql(expression, "comment") 4636 if comment: 4637 return f"ALTER COLUMN{exists} {this} COMMENT {comment}" 4638 4639 visible = expression.args.get("visible") 4640 if visible: 4641 return f"ALTER COLUMN{exists} {this} SET {visible}" 4642 4643 allow_null = expression.args.get("allow_null") 4644 drop = expression.args.get("drop") 4645 4646 if not drop and not allow_null: 4647 self.unsupported("Unsupported ALTER COLUMN syntax") 4648 4649 if allow_null is not None: 4650 keyword = "DROP" if drop else "SET" 4651 return f"ALTER COLUMN{exists} {this} {keyword} NOT NULL" 4652 4653 return f"ALTER COLUMN{exists} {this} DROP DEFAULT" 4654 4655 def _alter_column_null_constraint_sql(self, expression: exp.AlterColumn) -> str: 4656 allow_null = expression.args.get("allow_null") 4657 if allow_null is None: 4658 return "" 4659 4660 if not self.SUPPORTS_ALTER_COLUMN_NULLABILITY: 4661 self.unsupported("ALTER COLUMN cannot set nullability along with a type") 4662 return "" 4663 4664 return " NULL" if allow_null else " NOT NULL" 4665 4666 def modifycolumn_sql(self, expression: exp.ModifyColumn) -> str: 4667 this = self.sql(expression, "this") 4668 rename_from = self.sql(expression, "rename_from") 4669 if rename_from: 4670 if not self.SUPPORTS_CHANGE_COLUMN: 4671 self.unsupported("CHANGE COLUMN is not supported in this dialect") 4672 return f"CHANGE COLUMN {rename_from} {this}" 4673 if not self.SUPPORTS_MODIFY_COLUMN: 4674 self.unsupported("MODIFY COLUMN is not supported in this dialect") 4675 return f"MODIFY COLUMN {this}" 4676 4677 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 4678 this = self.sql(expression, "this") 4679 4680 visible = expression.args.get("visible") 4681 visible_sql = "VISIBLE" if visible else "INVISIBLE" 4682 4683 return f"ALTER INDEX {this} {visible_sql}" 4684 4685 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 4686 this = self.sql(expression, "this") 4687 if not isinstance(expression.this, exp.Var): 4688 this = f"KEY DISTKEY {this}" 4689 return f"ALTER DISTSTYLE {this}" 4690 4691 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 4692 compound = " COMPOUND" if expression.args.get("compound") else "" 4693 this = self.sql(expression, "this") 4694 expressions = self.expressions(expression, flat=True) 4695 expressions = f"({expressions})" if expressions else "" 4696 return f"ALTER{compound} SORTKEY {this or expressions}" 4697 4698 def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str: 4699 if not self.RENAME_TABLE_WITH_DB: 4700 # Remove db from tables 4701 expression = expression.transform( 4702 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 4703 ).assert_is(exp.AlterRename) 4704 this = self.sql(expression, "this") 4705 to_kw = " TO" if include_to else "" 4706 return f"RENAME{to_kw} {this}" 4707 4708 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 4709 exists = " IF EXISTS" if expression.args.get("exists") else "" 4710 old_column = self.sql(expression, "this") 4711 new_column = self.sql(expression, "to") 4712 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 4713 4714 def alterset_sql(self, expression: exp.AlterSet) -> str: 4715 exprs = self.expressions(expression, flat=True) 4716 if self.ALTER_SET_WRAPPED: 4717 exprs = f"({exprs})" 4718 4719 return f"SET {exprs}" 4720 4721 def alter_sql(self, expression: exp.Alter) -> str: 4722 actions = expression.actions 4723 4724 if ( 4725 not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN 4726 and actions 4727 and isinstance(actions[0], exp.ColumnDef) 4728 ): 4729 actions_sql = self.expressions(expression, key="actions", flat=True) 4730 actions_sql = f"ADD {actions_sql}" 4731 else: 4732 actions_list = [] 4733 for action in actions: 4734 if isinstance(action, (exp.ColumnDef, exp.Schema)): 4735 action_sql = self.add_column_sql(action) 4736 else: 4737 action_sql = self.sql(action) 4738 if isinstance(action, exp.Query): 4739 action_sql = f"AS {action_sql}" 4740 4741 actions_list.append(action_sql) 4742 4743 actions_sql = self.format_args(*actions_list).lstrip("\n") 4744 4745 iceberg = ( 4746 "ICEBERG " 4747 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 4748 else "" 4749 ) 4750 exists = " IF EXISTS" if expression.args.get("exists") else "" 4751 on_cluster = self.sql(expression, "cluster") 4752 on_cluster = f" {on_cluster}" if on_cluster else "" 4753 only = " ONLY" if expression.args.get("only") else "" 4754 options = expression.args.get("options") or [] 4755 options_sql = self.expressions( 4756 sqls=[o for o in options if not isinstance(o, self.ALTER_PARTITION_OPTIONS)] 4757 ) 4758 options_sql = f", {options_sql}" if options_sql and actions_sql else options_sql 4759 partitions_sql = self.expressions( 4760 sqls=[o for o in options if isinstance(o, self.ALTER_PARTITION_OPTIONS)], 4761 sep=" ", 4762 flat=True, 4763 ) 4764 if partitions_sql and (actions_sql or options_sql): 4765 partitions_sql = f" {partitions_sql}" 4766 kind = self.sql(expression, "kind") 4767 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 4768 check = " WITH CHECK" if expression.args.get("check") else "" 4769 cascade = ( 4770 " CASCADE" 4771 if expression.args.get("cascade") and self.dialect.ALTER_TABLE_SUPPORTS_CASCADE 4772 else "" 4773 ) 4774 this = self.sql(expression, "this") 4775 this = f" {this}" if this else "" 4776 4777 return f"ALTER {iceberg}{kind}{exists}{only}{this}{on_cluster}{check}{self.sep()}{actions_sql}{not_valid}{options_sql}{partitions_sql}{cascade}" 4778 4779 def altersession_sql(self, expression: exp.AlterSession) -> str: 4780 items_sql = self.expressions(expression, flat=True) 4781 keyword = "UNSET" if expression.args.get("unset") else "SET" 4782 return f"{keyword} {items_sql}" 4783 4784 def add_column_sql(self, expression: exp.Expr) -> str: 4785 column_text = "" 4786 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 4787 if isinstance(expression, exp.ColumnDef): 4788 column_text = " COLUMN" 4789 elif isinstance(expression, exp.Schema): 4790 column_text = " COLUMNS" 4791 4792 if isinstance(expression, exp.Schema) and not self.ALTER_TABLE_ADD_COLUMNS_WRAPPED: 4793 sql = self.expressions(expression, flat=True) 4794 else: 4795 sql = self.sql(expression) 4796 4797 return f"ADD{column_text} {sql}" 4798 4799 def droppartition_sql(self, expression: exp.DropPartition) -> str: 4800 expressions = self.expressions(expression) 4801 exists = " IF EXISTS " if expression.args.get("exists") else " " 4802 return f"DROP{exists}{expressions}" 4803 4804 def dropprimarykey_sql(self, expression: exp.DropPrimaryKey) -> str: 4805 return "DROP PRIMARY KEY" 4806 4807 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 4808 return f"ADD {self.expressions(expression, indent=False)}" 4809 4810 def replacecolumns_sql(self, expression: exp.ReplaceColumns) -> str: 4811 return f"REPLACE COLUMNS ({self.expressions(expression, flat=True)})" 4812 4813 def addpartition_sql(self, expression: exp.AddPartition) -> str: 4814 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 4815 location = self.sql(expression, "location") 4816 location = f" {location}" if location else "" 4817 return f"ADD {exists}{self.sql(expression.this)}{location}" 4818 4819 def distinct_sql(self, expression: exp.Distinct) -> str: 4820 this = self.expressions(expression, flat=True) 4821 4822 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 4823 case = exp.case() 4824 for arg in expression.expressions: 4825 case = case.when(arg.is_(exp.null()), exp.null()) 4826 this = self.sql(case.else_(f"({this})")) 4827 4828 this = f" {this}" if this else "" 4829 4830 on = self.sql(expression, "on") 4831 on = f" ON {on}" if on else "" 4832 return f"DISTINCT{this}{on}" 4833 4834 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 4835 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 4836 4837 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 4838 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 4839 4840 def havingmax_sql(self, expression: exp.HavingMax) -> str: 4841 this_sql = self.sql(expression, "this") 4842 expression_sql = self.sql(expression, "expression") 4843 kind = "MAX" if expression.args.get("max") else "MIN" 4844 return f"{this_sql} HAVING {kind} {expression_sql}" 4845 4846 def intdiv_sql(self, expression: exp.IntDiv) -> str: 4847 if not self.INT_DIV_OPERATOR: 4848 return self._truncated_div_sql(expression.this, expression.expression) 4849 4850 # Integer division binds like %, so those operators chain on its left without parentheses 4851 node: exp.Expr = expression 4852 while isinstance(node, exp.IntDiv): 4853 this = node.this 4854 if not isinstance(this, self.MOD_PAREN_PARENT_TYPES): 4855 node.set("this", exp._wrap(this, exp.Binary)) 4856 node.set("expression", exp._wrap(node.expression, exp.Binary)) 4857 node = this 4858 4859 sql = self.binary(expression, self.INT_DIV_OPERATOR) 4860 4861 parent = expression.parent 4862 if isinstance(parent, (exp.Neg, exp.BitwiseNot)) or ( 4863 isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression 4864 ): 4865 return f"({sql})" 4866 4867 return sql 4868 4869 def _truncated_div_sql(self, this: exp.Expr, divisor: exp.Expr) -> str: 4870 div: exp.Expr = this / divisor 4871 if self.CAST_TO_INT_ROUNDS: 4872 div = exp.Trunc(this=div) 4873 4874 return self.sql(exp.Cast(this=div, to=exp.DataType(this=exp.DType.BIGINT))) 4875 4876 def dpipe_sql(self, expression: exp.DPipe) -> str: 4877 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 4878 return self.func("CONCAT", *(exp.cast(e, exp.DType.TEXT) for e in expression.flatten())) 4879 return self.binary(expression, "||") 4880 4881 def nullif_zero_divisor(self, expression: exp.Div | exp.Mod) -> None: 4882 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 4883 divisor = expression.right 4884 divisor.replace(exp.Nullif(this=divisor.copy(), expression=exp.Literal.number(0))) 4885 4886 def div_sql(self, expression: exp.Div) -> str: 4887 l, r = expression.left, expression.right 4888 self.nullif_zero_divisor(expression) 4889 4890 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 4891 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 4892 l.replace(exp.cast(l.copy(), to=exp.DType.DOUBLE)) 4893 4894 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 4895 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 4896 # Native integer division depends on the target's operand types, which may differ 4897 # from the source's (e.g. FLOOR(int) is DOUBLE in DuckDB), unless the operands are 4898 # integer literals or casts 4899 if all(e.is_int or isinstance(e, exp.Cast) for e in (l, r)) and ( 4900 expression.args.get("safe") or not self.SAFE_INT_DIVISION 4901 ): 4902 return self.sql(exp.IntDiv(this=l, expression=expression.right)) 4903 return self._truncated_div_sql(l, expression.right) 4904 4905 return self.binary(expression, "/") 4906 4907 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 4908 n = exp._wrap(expression.this, exp.Binary) 4909 d = exp._wrap(expression.expression, exp.Binary) 4910 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 4911 4912 def overlaps_sql(self, expression: exp.Overlaps) -> str: 4913 return self.binary(expression, "OVERLAPS") 4914 4915 def distance_sql(self, expression: exp.Distance) -> str: 4916 return self.binary(expression, "<->") 4917 4918 def distancend_sql(self, expression: exp.DistanceNd) -> str: 4919 return self.binary(expression, "<<->>") 4920 4921 def dot_sql(self, expression: exp.Dot) -> str: 4922 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 4923 4924 def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: 4925 if not self.SUPPORTS_NESTED_JSON_SELECT and self.dialect != "": 4926 self.unsupported("Selecting nested JSON objects with .^ is not supported") 4927 return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}" 4928 4929 def eq_sql(self, expression: exp.EQ) -> str: 4930 return self.binary(expression, "=") 4931 4932 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 4933 return self.binary(expression, ":=") 4934 4935 def escape_sql(self, expression: exp.Escape) -> str: 4936 this = expression.this 4937 if ( 4938 isinstance(this, (exp.Like, exp.ILike)) 4939 and isinstance(this.expression, (exp.All, exp.Any)) 4940 and not self.SUPPORTS_LIKE_QUANTIFIERS 4941 ): 4942 return self._like_sql(this, escape=expression) 4943 return self.binary(expression, "ESCAPE") 4944 4945 def glob_sql(self, expression: exp.Glob) -> str: 4946 return self.binary(expression, "GLOB") 4947 4948 def gt_sql(self, expression: exp.GT) -> str: 4949 return self.binary(expression, ">") 4950 4951 def gte_sql(self, expression: exp.GTE) -> str: 4952 return self.binary(expression, ">=") 4953 4954 def is_sql(self, expression: exp.Is) -> str: 4955 negate = expression.args.get("negate") 4956 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 4957 positive = bool(expression.expression.this) != bool(negate) 4958 return self.sql(expression.this if positive else exp.not_(expression.this)) 4959 return self.binary(expression, "IS NOT" if negate else "IS") 4960 4961 def _like_sql( 4962 self, 4963 expression: exp.Like | exp.ILike, 4964 escape: exp.Escape | None = None, 4965 ) -> str: 4966 this = expression.this 4967 rhs = expression.expression 4968 4969 if isinstance(expression, exp.Like): 4970 exp_class: type[exp.Like | exp.ILike] = exp.Like 4971 op = "LIKE" 4972 else: 4973 exp_class = exp.ILike 4974 op = "ILIKE" 4975 4976 if expression.args.get("negate"): 4977 op = f"NOT {op}" 4978 4979 if isinstance(rhs, (exp.All, exp.Any)) and not self.SUPPORTS_LIKE_QUANTIFIERS: 4980 exprs = rhs.this.unnest() 4981 4982 if isinstance(exprs, exp.Tuple): 4983 exprs = exprs.expressions 4984 else: 4985 exprs = [exprs] 4986 4987 connective = exp.or_ if isinstance(rhs, exp.Any) else exp.and_ 4988 4989 def _make_like(expr: exp.Expression) -> exp.Expression: 4990 like: exp.Expression = exp_class( 4991 this=this, expression=expr, negate=expression.args.get("negate") 4992 ) 4993 if escape: 4994 like = exp.Escape(this=like, expression=escape.expression.copy()) 4995 return like 4996 4997 like_expr: exp.Expr = _make_like(exprs[0]) 4998 for expr in exprs[1:]: 4999 like_expr = connective(like_expr, _make_like(expr), copy=False) 5000 5001 parent = escape.parent if escape else expression.parent 5002 if not isinstance(parent, (type(like_expr), exp.Paren)) and isinstance( 5003 parent, exp.Condition 5004 ): 5005 like_expr = exp.paren(like_expr, copy=False) 5006 5007 return self.sql(like_expr) 5008 5009 return self.binary(expression, op) 5010 5011 def like_sql(self, expression: exp.Like) -> str: 5012 return self._like_sql(expression) 5013 5014 def ilike_sql(self, expression: exp.ILike) -> str: 5015 return self._like_sql(expression) 5016 5017 def match_sql(self, expression: exp.Match) -> str: 5018 if expression.args.get("kind") or expression.args.get("analyzer"): 5019 self.unsupported("MATCH variants and USING ANALYZER are not supported in this dialect") 5020 return self.binary(expression, "MATCH") 5021 5022 def similarto_sql(self, expression: exp.SimilarTo) -> str: 5023 return self.binary(expression, "SIMILAR TO") 5024 5025 def lt_sql(self, expression: exp.LT) -> str: 5026 return self.binary(expression, "<") 5027 5028 def lte_sql(self, expression: exp.LTE) -> str: 5029 return self.binary(expression, "<=") 5030 5031 def mod_sql(self, expression: exp.Mod) -> str: 5032 self.nullif_zero_divisor(expression) 5033 this = self.sql(expression, "this") 5034 expr = self.sql(expression, "expression") 5035 sql = f"{this} {self.maybe_comment(self.MOD_OPERATOR, comments=expression.comments)} {expr}" 5036 5037 parent = expression.parent 5038 if isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression: 5039 return f"({sql})" 5040 5041 return sql 5042 5043 def mul_sql(self, expression: exp.Mul) -> str: 5044 return self.binary(expression, "*") 5045 5046 def neq_sql(self, expression: exp.NEQ) -> str: 5047 return self.binary(expression, "<>") 5048 5049 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 5050 return self.binary(expression, "IS NOT DISTINCT FROM") 5051 5052 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 5053 return self.binary(expression, "IS DISTINCT FROM") 5054 5055 def sub_sql(self, expression: exp.Sub) -> str: 5056 return self.binary(expression, "-") 5057 5058 def trycast_sql(self, expression: exp.TryCast) -> str: 5059 return self.cast_sql(expression, safe_prefix="TRY_") 5060 5061 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 5062 return self.cast_sql(expression) 5063 5064 def try_sql(self, expression: exp.Try) -> str: 5065 if not self.TRY_SUPPORTED: 5066 self.unsupported("Unsupported TRY function") 5067 return self.sql(expression, "this") 5068 5069 return self.func("TRY", expression.this) 5070 5071 def log_sql(self, expression: exp.Log) -> str: 5072 this = expression.this 5073 expr = expression.expression 5074 5075 if self.dialect.LOG_BASE_FIRST is False: 5076 this, expr = expr, this 5077 elif self.dialect.LOG_BASE_FIRST is None and expr: 5078 if this.name in ("2", "10"): 5079 return self.func(f"LOG{this.name}", expr) 5080 5081 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 5082 5083 return self.func("LOG", this, expr) 5084 5085 def use_sql(self, expression: exp.Use) -> str: 5086 kind = self.sql(expression, "kind") 5087 kind = f" {kind}" if kind else "" 5088 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 5089 this = f" {this}" if this else "" 5090 return f"USE{kind}{this}" 5091 5092 def binary(self, expression: exp.Binary, op: str) -> str: 5093 sqls: list[str] = [] 5094 stack: list[None | str | exp.Expr] = [expression] 5095 binary_type = type(expression) 5096 is_is = binary_type is exp.Is and op in ("IS", "IS NOT") 5097 negate = expression.args.get("negate") 5098 5099 while stack: 5100 node = stack.pop() 5101 5102 if type(node) is binary_type and ( 5103 node is expression 5104 or (is_is and not isinstance(node.expression, exp.Boolean)) 5105 or node.args.get("negate") == negate 5106 ): 5107 op_func = node.args.get("operator") 5108 if op_func: 5109 op = self.sql(op_func) 5110 if op not in self.BARE_OPERATORS: 5111 op = f"OPERATOR({op})" 5112 elif is_is: 5113 op = "IS NOT" if node.args.get("negate") else "IS" 5114 5115 stack.append(node.args.get("expression")) 5116 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 5117 stack.append(node.args.get("this")) 5118 else: 5119 sqls.append(self.sql(node)) 5120 5121 return "".join(sqls) 5122 5123 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 5124 to_clause = self.sql(expression, "to") 5125 if to_clause: 5126 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 5127 5128 return self.function_fallback_sql(expression) 5129 5130 def function_fallback_sql(self, expression: exp.Func) -> str: 5131 args = [] 5132 5133 for key in expression.arg_types: 5134 arg_value = expression.args.get(key) 5135 5136 if isinstance(arg_value, list): 5137 for value in arg_value: 5138 args.append(value) 5139 elif arg_value is not None: 5140 args.append(arg_value) 5141 5142 return self.func(self.function_name(expression), *args) 5143 5144 def function_name(self, expression: exp.Func) -> str: 5145 name_key = self.dialect.ORIGINAL_NAME_META_KEY 5146 return (expression.meta_get(name_key) if name_key else None) or expression.sql_name() 5147 5148 def func( 5149 self, 5150 name: str, 5151 *args: t.Any, 5152 prefix: str = "(", 5153 suffix: str = ")", 5154 normalize: bool = True, 5155 ) -> str: 5156 name = self.normalize_func(name) if normalize else name 5157 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 5158 5159 def format_args(self, *args: t.Any, sep: str = ", ") -> str: 5160 arg_sqls = tuple( 5161 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 5162 ) 5163 if self.pretty and self.too_wide(arg_sqls): 5164 return self.indent( 5165 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 5166 ) 5167 return sep.join(arg_sqls) 5168 5169 def too_wide(self, args: t.Iterable) -> bool: 5170 return sum(len(arg) for arg in args) > self.max_text_width 5171 5172 def format_time( 5173 self, 5174 expression: exp.Expr, 5175 inverse_time_mapping: dict[str, str] | None = None, 5176 inverse_time_trie: dict | None = None, 5177 ) -> str | None: 5178 return format_time( 5179 self.sql(expression, "format"), 5180 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 5181 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 5182 ) 5183 5184 def expressions( 5185 self, 5186 expression: exp.Expr | None = None, 5187 key: str | None = None, 5188 sqls: t.Collection[str | exp.Expr] | None = None, 5189 flat: bool = False, 5190 indent: bool = True, 5191 skip_first: bool = False, 5192 skip_last: bool = False, 5193 sep: str = ", ", 5194 prefix: str = "", 5195 dynamic: bool = False, 5196 new_line: bool = False, 5197 ) -> str: 5198 expressions = expression.args.get(key or "expressions") if expression else sqls 5199 5200 if not expressions: 5201 return "" 5202 5203 if flat: 5204 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 5205 5206 num_sqls = len(expressions) 5207 result_sqls = [] 5208 5209 for i, e in enumerate(expressions): 5210 sql = self.sql(e, comment=False) 5211 if not sql: 5212 continue 5213 5214 comments = self.maybe_comment("", e) if isinstance(e, exp.Expr) else "" 5215 5216 if self.pretty: 5217 if self.leading_comma: 5218 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 5219 else: 5220 result_sqls.append( 5221 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 5222 ) 5223 else: 5224 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 5225 5226 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 5227 if new_line: 5228 result_sqls.insert(0, "") 5229 result_sqls.append("") 5230 result_sql = "\n".join(s.rstrip() for s in result_sqls) 5231 else: 5232 result_sql = "".join(result_sqls) 5233 5234 return ( 5235 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 5236 if indent 5237 else result_sql 5238 ) 5239 5240 def op_expressions(self, op: str, expression: exp.Expr, flat: bool = False) -> str: 5241 flat = flat or isinstance(expression.parent, exp.Properties) 5242 expressions_sql = self.expressions(expression, flat=flat) 5243 if flat: 5244 return f"{op} {expressions_sql}" 5245 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 5246 5247 def naked_property(self, expression: exp.Property) -> str: 5248 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 5249 if not property_name: 5250 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 5251 return f"{property_name} {self.sql(expression, 'this')}" 5252 5253 def tag_sql(self, expression: exp.Tag) -> str: 5254 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 5255 5256 def token_sql(self, token_type: TokenType) -> str: 5257 return self.TOKEN_MAPPING.get(token_type, token_type.name) 5258 5259 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 5260 this = self.sql(expression, "this") 5261 expressions = self.no_identify(self.expressions, expression) 5262 expressions = ( 5263 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 5264 ) 5265 return f"{this}{expressions}" if expressions.strip() != "" else this 5266 5267 def macrooverloads_sql(self, expression: exp.MacroOverloads) -> str: 5268 return self.expressions(expression, flat=True) 5269 5270 def macrooverload_sql(self, expression: exp.MacroOverload) -> str: 5271 params = self.no_identify(self.expressions, expression, flat=True) 5272 body = self.sql(expression, "this") 5273 prefix = "TABLE " if expression.args.get("is_table") else "" 5274 return f"({params}) AS {prefix}{body}" 5275 5276 def joinhint_sql(self, expression: exp.JoinHint) -> str: 5277 this = self.sql(expression, "this") 5278 expressions = self.expressions(expression, flat=True) 5279 return f"{this}({expressions})" 5280 5281 def kwarg_sql(self, expression: exp.Kwarg) -> str: 5282 return self.binary(expression, "=>") 5283 5284 def when_sql(self, expression: exp.When) -> str: 5285 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 5286 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 5287 condition = self.sql(expression, "condition") 5288 condition = f" AND {condition}" if condition else "" 5289 5290 then_expression = expression.args.get("then") 5291 if isinstance(then_expression, exp.Insert): 5292 this = ( 5293 "ALL BY NAME" 5294 if self.MERGE_ALL_BY_NAME and isinstance(then_expression.this, exp.Star) 5295 else self.sql(then_expression, "this") 5296 ) 5297 this = f"INSERT {this}" if this else "INSERT" 5298 then = self.sql(then_expression, "expression") 5299 then = f"{this} VALUES {then}" if then else this 5300 elif isinstance(then_expression, exp.Update): 5301 if isinstance(then_expression.args.get("expressions"), exp.Star): 5302 then = ( 5303 "UPDATE ALL BY NAME" 5304 if self.MERGE_ALL_BY_NAME 5305 else f"UPDATE {self.sql(then_expression, 'expressions')}" 5306 ) 5307 elif ( 5308 self.MERGE_ALL_BY_NAME 5309 and len(then_expression.expressions) == 1 5310 and isinstance(then_expression.expressions[0], exp.Star) 5311 ): 5312 then = "UPDATE ALL BY NAME" 5313 else: 5314 expressions_sql = self.expressions(then_expression) 5315 then = f"UPDATE SET{self.sep()}{expressions_sql}" if expressions_sql else "UPDATE" 5316 else: 5317 then = self.sql(then_expression) 5318 5319 if isinstance(then_expression, (exp.Insert, exp.Update)): 5320 where = self.sql(then_expression, "where") 5321 if where and not self.SUPPORTS_MERGE_WHERE: 5322 kind = "INSERT" if isinstance(then_expression, exp.Insert) else "UPDATE" 5323 self.unsupported(f"WHERE clause in MERGE {kind} is not supported") 5324 where = "" 5325 then = f"{then}{where}" 5326 return f"WHEN {matched}{source}{condition} THEN {then}" 5327 5328 def whens_sql(self, expression: exp.Whens) -> str: 5329 return self.expressions(expression, sep=" ", indent=False) 5330 5331 def merge_sql(self, expression: exp.Merge) -> str: 5332 schema_evolution = "" 5333 if expression.args.get("schema_evolution"): 5334 min_version = self.MERGE_SCHEMA_EVOLUTION_MIN_VERSION 5335 if min_version and self.dialect.version >= min_version: 5336 schema_evolution = " WITH SCHEMA EVOLUTION" 5337 else: 5338 self.unsupported("MERGE WITH SCHEMA EVOLUTION is not supported") 5339 5340 table = expression.this 5341 table_alias = "" 5342 5343 hints = table.args.get("hints") 5344 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 5345 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 5346 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 5347 5348 this = self.sql(table) 5349 using = f"USING {self.sql(expression, 'using')}" 5350 whens = self.sql(expression, "whens") 5351 5352 on = self.sql(expression, "on") 5353 on = f"ON {on}" if on else "" 5354 5355 if not on: 5356 on = self.expressions(expression, key="using_cond") 5357 on = f"USING ({on})" if on else "" 5358 5359 returning = self.sql(expression, "returning") 5360 if returning: 5361 whens = f"{whens}{returning}" 5362 5363 sep = self.sep() 5364 5365 return self.prepend_ctes( 5366 expression, 5367 f"MERGE{schema_evolution} INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 5368 ) 5369 5370 @unsupported_args("format") 5371 def tochar_sql(self, expression: exp.ToChar) -> str: 5372 return self.sql(exp.cast(expression.this, exp.DType.TEXT)) 5373 5374 @unsupported_args("default") 5375 def tonumber_sql(self, expression: exp.ToNumber) -> str: 5376 if not self.SUPPORTS_TO_NUMBER: 5377 self.unsupported("Unsupported TO_NUMBER function") 5378 return self._tonumber_cast_sql(expression) 5379 5380 fmt = expression.args.get("format") 5381 if not fmt: 5382 self.unsupported("Conversion format is required for TO_NUMBER") 5383 return self._tonumber_cast_sql(expression) 5384 5385 return self.func("TO_NUMBER", expression.this, fmt) 5386 5387 def _tonumber_cast_sql(self, expression: exp.ToNumber) -> str: 5388 if expression.args.get("safe"): 5389 return self.sql(exp.TryCast(this=expression.this, to=exp.DataType.build("DOUBLE"))) 5390 return self.sql(exp.cast(expression.this, exp.DType.DOUBLE)) 5391 5392 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 5393 this = self.sql(expression, "this") 5394 kind = self.sql(expression, "kind") 5395 settings_sql = self.expressions(expression, key="settings", sep=" ") 5396 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 5397 return f"{this}({kind}{args})" 5398 5399 def dictrange_sql(self, expression: exp.DictRange) -> str: 5400 this = self.sql(expression, "this") 5401 max = self.sql(expression, "max") 5402 min = self.sql(expression, "min") 5403 return f"{this}(MIN {min} MAX {max})" 5404 5405 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 5406 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 5407 5408 def aggregatekeyproperty_sql(self, expression: exp.AggregateKeyProperty) -> str: 5409 return f"AGGREGATE KEY ({self.expressions(expression, flat=True)})" 5410 5411 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 5412 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 5413 5414 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 5415 def uniquekeyproperty_sql( 5416 self, expression: exp.UniqueKeyProperty, prefix: str = "UNIQUE KEY" 5417 ) -> str: 5418 return f"{prefix} ({self.expressions(expression, flat=True)})" 5419 5420 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 5421 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 5422 expressions = self.expressions(expression, flat=True) 5423 expressions = f" {self.wrap(expressions)}" if expressions else "" 5424 buckets = self.sql(expression, "buckets") 5425 kind = self.sql(expression, "kind") 5426 buckets = f" BUCKETS {buckets}" if buckets else "" 5427 order = self.sql(expression, "order") 5428 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 5429 5430 def oncluster_sql(self, expression: exp.OnCluster) -> str: 5431 return "" 5432 5433 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 5434 expressions = self.expressions(expression, key="expressions", flat=True) 5435 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 5436 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 5437 buckets = self.sql(expression, "buckets") 5438 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 5439 5440 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 5441 this = self.sql(expression, "this") 5442 having = self.sql(expression, "having") 5443 5444 if having: 5445 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 5446 5447 return self.func("ANY_VALUE", this) 5448 5449 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 5450 transform = self.func("TRANSFORM", *expression.expressions) 5451 row_format_before = self.sql(expression, "row_format_before") 5452 row_format_before = f" {row_format_before}" if row_format_before else "" 5453 record_writer = self.sql(expression, "record_writer") 5454 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 5455 using = f" USING {self.sql(expression, 'command_script')}" 5456 schema = self.sql(expression, "schema") 5457 schema = f" AS {schema}" if schema else "" 5458 row_format_after = self.sql(expression, "row_format_after") 5459 row_format_after = f" {row_format_after}" if row_format_after else "" 5460 record_reader = self.sql(expression, "record_reader") 5461 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 5462 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 5463 5464 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 5465 key_block_size = self.sql(expression, "key_block_size") 5466 if key_block_size: 5467 return f"KEY_BLOCK_SIZE = {key_block_size}" 5468 5469 using = self.sql(expression, "using") 5470 if using: 5471 return f"USING {using}" 5472 5473 parser = self.sql(expression, "parser") 5474 if parser: 5475 return f"WITH PARSER {parser}" 5476 5477 comment = self.sql(expression, "comment") 5478 if comment: 5479 return f"COMMENT {comment}" 5480 5481 visible = expression.args.get("visible") 5482 if visible is not None: 5483 return "VISIBLE" if visible else "INVISIBLE" 5484 5485 engine_attr = self.sql(expression, "engine_attr") 5486 if engine_attr: 5487 return f"ENGINE_ATTRIBUTE = {engine_attr}" 5488 5489 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 5490 if secondary_engine_attr: 5491 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 5492 5493 self.unsupported("Unsupported index constraint option.") 5494 return "" 5495 5496 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 5497 enforced = " ENFORCED" if expression.args.get("enforced") else "" 5498 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 5499 5500 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 5501 kind = self.sql(expression, "kind") 5502 kind = f"{kind} INDEX" if kind else "INDEX" 5503 this = self.sql(expression, "this") 5504 this = f" {this}" if this else "" 5505 index_type = self.sql(expression, "index_type") 5506 index_type = f" USING {index_type}" if index_type else "" 5507 expressions = self.expressions(expression, flat=True) 5508 expressions = f" ({expressions})" if expressions else "" 5509 options = self.expressions(expression, key="options", sep=" ") 5510 options = f" {options}" if options else "" 5511 return f"{kind}{this}{index_type}{expressions}{options}" 5512 5513 def nvl2_sql(self, expression: exp.Nvl2) -> str: 5514 if self.NVL2_SUPPORTED: 5515 return self.function_fallback_sql(expression) 5516 5517 case = exp.Case().when( 5518 expression.this.is_(exp.null()).not_(copy=False), 5519 expression.args["true"], 5520 copy=False, 5521 ) 5522 else_cond = expression.args.get("false") 5523 if else_cond: 5524 case.else_(else_cond, copy=False) 5525 5526 return self.sql(case) 5527 5528 def nthvalue_sql(self, expression: exp.NthValue) -> str: 5529 if expression.args.get("from_first") is False: 5530 self.unsupported("NTH_VALUE FROM LAST is not supported") 5531 5532 return self.function_fallback_sql(expression) 5533 5534 def comprehension_sql(self, expression: exp.Comprehension) -> str: 5535 this = self.sql(expression, "this") 5536 expr = self.sql(expression, "expression") 5537 position = self.sql(expression, "position") 5538 position = f", {position}" if position else "" 5539 iterator = self.sql(expression, "iterator") 5540 condition = self.sql(expression, "condition") 5541 condition = f" IF {condition}" if condition else "" 5542 return f"{this} FOR {expr}{position} IN {iterator}{condition}" 5543 5544 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 5545 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 5546 5547 def opclass_sql(self, expression: exp.Opclass) -> str: 5548 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 5549 5550 def _ml_sql(self, expression: exp.Func, name: str) -> str: 5551 model = self.sql(expression, "this") 5552 model = f"MODEL {model}" 5553 expr = expression.expression 5554 if expr: 5555 expr_sql = self.sql(expression, "expression") 5556 expr_sql = f"TABLE {expr_sql}" if isinstance(expr, exp.Table) else expr_sql 5557 else: 5558 expr_sql = None 5559 5560 parameters = self.sql(expression, "params_struct") or None 5561 5562 return self.func(name, model, expr_sql, parameters) 5563 5564 def predict_sql(self, expression: exp.Predict) -> str: 5565 return self._ml_sql(expression, "PREDICT") 5566 5567 def generateembedding_sql(self, expression: exp.GenerateEmbedding) -> str: 5568 name = "GENERATE_TEXT_EMBEDDING" if expression.args.get("is_text") else "GENERATE_EMBEDDING" 5569 return self._ml_sql(expression, name) 5570 5571 def generatetext_sql(self, expression: exp.GenerateText) -> str: 5572 return self._ml_sql(expression, "GENERATE_TEXT") 5573 5574 def generatetable_sql(self, expression: exp.GenerateTable) -> str: 5575 return self._ml_sql(expression, "GENERATE_TABLE") 5576 5577 def generatebool_sql(self, expression: exp.GenerateBool) -> str: 5578 return self._ml_sql(expression, "GENERATE_BOOL") 5579 5580 def generateint_sql(self, expression: exp.GenerateInt) -> str: 5581 return self._ml_sql(expression, "GENERATE_INT") 5582 5583 def generatedouble_sql(self, expression: exp.GenerateDouble) -> str: 5584 return self._ml_sql(expression, "GENERATE_DOUBLE") 5585 5586 def mltranslate_sql(self, expression: exp.MLTranslate) -> str: 5587 return self._ml_sql(expression, "TRANSLATE") 5588 5589 def mlforecast_sql(self, expression: exp.MLForecast) -> str: 5590 return self._ml_sql(expression, "FORECAST") 5591 5592 def aiforecast_sql(self, expression: exp.AIForecast) -> str: 5593 this_sql = self.sql(expression, "this") 5594 if isinstance(expression.this, exp.Table): 5595 this_sql = f"TABLE {this_sql}" 5596 5597 return self.func( 5598 "FORECAST", 5599 this_sql, 5600 expression.args.get("data_col"), 5601 expression.args.get("timestamp_col"), 5602 expression.args.get("model"), 5603 expression.args.get("id_cols"), 5604 expression.args.get("horizon"), 5605 expression.args.get("forecast_end_timestamp"), 5606 expression.args.get("confidence_level"), 5607 expression.args.get("output_historical_time_series"), 5608 expression.args.get("context_window"), 5609 ) 5610 5611 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 5612 this_sql = self.sql(expression, "this") 5613 if isinstance(expression.this, exp.Table): 5614 this_sql = f"TABLE {this_sql}" 5615 5616 return self.func( 5617 "FEATURES_AT_TIME", 5618 this_sql, 5619 expression.args.get("time"), 5620 expression.args.get("num_rows"), 5621 expression.args.get("ignore_feature_nulls"), 5622 ) 5623 5624 def vectorsearch_sql(self, expression: exp.VectorSearch) -> str: 5625 this_sql = self.sql(expression, "this") 5626 if isinstance(expression.this, exp.Table): 5627 this_sql = f"TABLE {this_sql}" 5628 5629 query_table = self.sql(expression, "query_table") 5630 if isinstance(expression.args["query_table"], exp.Table): 5631 query_table = f"TABLE {query_table}" 5632 5633 return self.func( 5634 "VECTOR_SEARCH", 5635 this_sql, 5636 expression.args.get("column_to_search"), 5637 query_table, 5638 expression.args.get("query_column_to_search"), 5639 expression.args.get("top_k"), 5640 expression.args.get("distance_type"), 5641 expression.args.get("options"), 5642 ) 5643 5644 def forin_sql(self, expression: exp.ForIn) -> str: 5645 this = self.sql(expression, "this") 5646 expression_sql = self.sql(expression, "expression") 5647 return f"FOR {this} DO {expression_sql}" 5648 5649 @unsupported_args("partition_start", "partition_end", "force", "mode") 5650 def refresh_sql(self, expression: exp.Refresh) -> str: 5651 this = self.sql(expression, "this") 5652 kind = "" if isinstance(expression.this, exp.Literal) else f"{expression.text('kind')} " 5653 return f"REFRESH {kind}{this}" 5654 5655 def toarray_sql(self, expression: exp.ToArray) -> str: 5656 arg = expression.this 5657 if not arg.type: 5658 import sqlglot.optimizer.annotate_types 5659 5660 arg = sqlglot.optimizer.annotate_types.annotate_types(arg, dialect=self.dialect) 5661 5662 if arg.is_type(exp.DType.ARRAY): 5663 return self.sql(arg) 5664 5665 cond_for_null = arg.is_(exp.null()) 5666 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 5667 5668 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 5669 this = expression.this 5670 time_format = self.format_time(expression) 5671 5672 if time_format: 5673 return self.sql( 5674 exp.cast( 5675 exp.StrToTime(this=this, format=expression.args["format"]), 5676 exp.DType.TIME, 5677 ) 5678 ) 5679 5680 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 5681 return self.sql(this) 5682 5683 return self.sql(exp.cast(this, exp.DType.TIME)) 5684 5685 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 5686 this = expression.this 5687 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DType.TIMESTAMP): 5688 return self.sql(this) 5689 5690 return self.sql(exp.cast(this, exp.DType.TIMESTAMP, dialect=self.dialect)) 5691 5692 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 5693 this = expression.this 5694 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DType.DATETIME): 5695 return self.sql(this) 5696 5697 return self.sql(exp.cast(this, exp.DType.DATETIME, dialect=self.dialect)) 5698 5699 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 5700 this = expression.this 5701 time_format = self.format_time(expression) 5702 safe = expression.args.get("safe") 5703 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 5704 return self.sql( 5705 exp.cast( 5706 exp.StrToTime(this=this, format=expression.args["format"], safe=safe), 5707 exp.DType.DATE, 5708 ) 5709 ) 5710 5711 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DType.DATE): 5712 return self.sql(this) 5713 5714 if safe: 5715 return self.sql(exp.TryCast(this=this, to=exp.DataType(this=exp.DType.DATE))) 5716 5717 return self.sql(exp.cast(this, exp.DType.DATE)) 5718 5719 def unixdate_sql(self, expression: exp.UnixDate) -> str: 5720 return self.sql( 5721 exp.func( 5722 "DATEDIFF", 5723 expression.this, 5724 exp.cast(exp.Literal.string("1970-01-01"), exp.DType.DATE), 5725 "day", 5726 ) 5727 ) 5728 5729 def lastday_sql(self, expression: exp.LastDay) -> str: 5730 if self.LAST_DAY_SUPPORTS_DATE_PART: 5731 return self.function_fallback_sql(expression) 5732 5733 unit = expression.args.get("unit") 5734 if unit and unit.name.upper() != "MONTH": 5735 self.unsupported("Date parts are not supported in LAST_DAY.") 5736 5737 return self.func("LAST_DAY", expression.this) 5738 5739 def dateadd_sql(self, expression: exp.DateAdd) -> str: 5740 import sqlglot.dialects.dialect 5741 5742 return self.func( 5743 "DATE_ADD", 5744 expression.this, 5745 expression.expression, 5746 sqlglot.dialects.dialect.unit_to_str(expression), 5747 ) 5748 5749 def arrayinsert_sql(self, expression: exp.ArrayInsert, index_offset: int = 0) -> str: 5750 this = expression.this 5751 position = expression.args["position"] 5752 offset = index_offset - (expression.args.get("offset") or 0) 5753 5754 if offset: 5755 if position.is_int: 5756 value = position.to_py() 5757 if value >= 0: 5758 position = exp.Literal.number(value + offset) 5759 elif offset < 0 and value == -1: 5760 # 1-based -1 appends, which a 0-based position can only express as the size 5761 position = exp.ArraySize(this=this.copy()) 5762 else: 5763 # Negative positions count from the end, so they shift in the opposite 5764 # direction, e.g. 0-based -1 (before the last element) is 1-based -2 5765 position = exp.Literal.number(value - offset) 5766 else: 5767 self.unsupported("ARRAY_INSERT position can only be converted if it's a literal") 5768 5769 return self.func("ARRAY_INSERT", this, position, expression.expression) 5770 5771 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 5772 if self.CAN_IMPLEMENT_ARRAY_ANY: 5773 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 5774 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 5775 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 5776 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 5777 5778 import sqlglot.dialects.dialect 5779 5780 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 5781 if self.dialect.__class__ != sqlglot.dialects.dialect.Dialect: 5782 self.unsupported("ARRAY_ANY is unsupported") 5783 5784 return self.function_fallback_sql(expression) 5785 5786 def struct_sql(self, expression: exp.Struct) -> str: 5787 expression.set( 5788 "expressions", 5789 [ 5790 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 5791 if isinstance(e, exp.PropertyEQ) 5792 else e 5793 for e in expression.expressions 5794 ], 5795 ) 5796 5797 return self.function_fallback_sql(expression) 5798 5799 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 5800 low = self.sql(expression, "this") 5801 high = self.sql(expression, "expression") 5802 5803 return f"{low} TO {high}" 5804 5805 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 5806 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 5807 tables = f" {self.expressions(expression)}" 5808 5809 exists = " IF EXISTS" if expression.args.get("exists") else "" 5810 5811 on_cluster = self.sql(expression, "cluster") 5812 on_cluster = f" {on_cluster}" if on_cluster else "" 5813 5814 identity = self.sql(expression, "identity") 5815 identity = f" {identity} IDENTITY" if identity else "" 5816 5817 option = self.sql(expression, "option") 5818 option = f" {option}" if option else "" 5819 5820 partition = self.sql(expression, "partition") 5821 partition = f" {partition}" if partition else "" 5822 5823 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 5824 5825 # This transpiles T-SQL's CONVERT function 5826 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 5827 def convert_sql(self, expression: exp.Convert) -> str: 5828 to = expression.this 5829 value = expression.expression 5830 style = expression.args.get("style") 5831 safe = expression.args.get("safe") 5832 strict = expression.args.get("strict") 5833 5834 if not to or not value: 5835 return "" 5836 5837 # Retrieve length of datatype and override to default if not specified 5838 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5839 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 5840 5841 transformed: exp.Expr | None = None 5842 cast = exp.Cast if strict else exp.TryCast 5843 5844 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 5845 if isinstance(style, exp.Literal) and style.is_int: 5846 import sqlglot.dialects.tsql 5847 5848 style_value = style.name 5849 converted_style = sqlglot.dialects.tsql.TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 5850 if not converted_style: 5851 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 5852 5853 fmt = exp.Literal.string(converted_style) 5854 5855 if to.this == exp.DType.DATE: 5856 transformed = exp.StrToDate(this=value, format=fmt) 5857 elif to.this in (exp.DType.DATETIME, exp.DType.DATETIME2): 5858 transformed = exp.StrToTime(this=value, format=fmt) 5859 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5860 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 5861 elif to.this == exp.DType.TEXT: 5862 transformed = exp.TimeToStr(this=value, format=fmt) 5863 5864 if not transformed: 5865 transformed = cast(this=value, to=to, safe=safe) 5866 5867 return self.sql(transformed) 5868 5869 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 5870 this = expression.this 5871 if isinstance(this, exp.JSONPathWildcard): 5872 this = self.json_path_part(this) 5873 return f".{this}" if this else "" 5874 5875 quoted = expression.args.get("quoted") 5876 if not ( 5877 quoted and self.JSON_PATH_KEY_QUOTED_FORCES_BRACKETS 5878 ) and self.SAFE_JSON_PATH_KEY_RE.match(this): 5879 return f".{this}" 5880 5881 this = self.json_path_part(this) 5882 5883 return ( 5884 f"[{this}]" 5885 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 5886 else f".{this}" 5887 ) 5888 5889 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 5890 this = self.json_path_part(expression.this) 5891 return f"[{this}]" if this else "" 5892 5893 def _simplify_unless_literal(self, expression: E) -> E: 5894 if not isinstance(expression, exp.Literal): 5895 import sqlglot.optimizer.simplify 5896 5897 expression = sqlglot.optimizer.simplify.simplify(expression, dialect=self.dialect) 5898 5899 return expression 5900 5901 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 5902 this = expression.this 5903 if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS): 5904 self.unsupported( 5905 f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}" 5906 ) 5907 return self.sql(this) 5908 5909 if self.IGNORE_NULLS_IN_FUNC and not expression.meta_get("inline"): 5910 if self.IGNORE_NULLS_BEFORE_ORDER: 5911 from sqlglot.optimizer.scope import find_all_in_scope 5912 5913 # The first modifier here will be the one closest to the AggFunc's arg 5914 mods = sorted( 5915 find_all_in_scope(expression, exp.HavingMax, exp.Order, exp.Limit), 5916 key=lambda x: ( 5917 0 5918 if isinstance(x, exp.HavingMax) 5919 else (1 if isinstance(x, exp.Order) else 2) 5920 ), 5921 ) 5922 5923 if mods: 5924 mod = mods[0] 5925 this = expression.__class__(this=mod.this.copy()) 5926 this.meta["inline"] = True 5927 mod.this.replace(this) 5928 return self.sql(expression.this) 5929 5930 agg_func = expression.find(exp.AggFunc) 5931 5932 if agg_func: 5933 agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})" 5934 return self.maybe_comment(agg_func_sql, comments=agg_func.comments) 5935 5936 return f"{self.sql(expression, 'this')} {text}" 5937 5938 def _replace_line_breaks(self, string: str) -> str: 5939 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 5940 if self.pretty: 5941 return string.replace("\n", self.SENTINEL_LINE_BREAK) 5942 return string 5943 5944 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 5945 option = self.sql(expression, "this") 5946 5947 if expression.expressions: 5948 upper = option.upper() 5949 5950 # Snowflake FILE_FORMAT options are separated by whitespace 5951 sep = " " if upper == "FILE_FORMAT" else ", " 5952 5953 # Databricks copy/format options do not set their list of values with EQ 5954 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 5955 values = self.expressions(expression, flat=True, sep=sep) 5956 return f"{option}{op}({values})" 5957 5958 value = self.sql(expression, "expression") 5959 5960 if not value: 5961 return option 5962 5963 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 5964 5965 return f"{option}{op}{value}" 5966 5967 def credentials_sql(self, expression: exp.Credentials) -> str: 5968 cred_expr = expression.args.get("credentials") 5969 if isinstance(cred_expr, exp.Literal): 5970 # Redshift case: CREDENTIALS <string> 5971 credentials = self.sql(expression, "credentials") 5972 credentials = f"CREDENTIALS {credentials}" if credentials else "" 5973 else: 5974 # Snowflake case: CREDENTIALS = (...) 5975 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 5976 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 5977 5978 storage = self.sql(expression, "storage") 5979 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 5980 5981 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 5982 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 5983 5984 iam_role = self.sql(expression, "iam_role") 5985 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 5986 5987 region = self.sql(expression, "region") 5988 region = f" REGION {region}" if region else "" 5989 5990 return f"{credentials}{storage}{encryption}{iam_role}{region}" 5991 5992 def copy_sql(self, expression: exp.Copy) -> str: 5993 this = self.sql(expression, "this") 5994 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 5995 5996 credentials = self.sql(expression, "credentials") 5997 credentials = self.seg(credentials) if credentials else "" 5998 files = self.expressions(expression, key="files", flat=True) 5999 kind = self.seg("FROM" if expression.args.get("kind") else "TO") if files else "" 6000 6001 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 6002 params = self.expressions( 6003 expression, 6004 key="params", 6005 sep=sep, 6006 new_line=True, 6007 skip_last=True, 6008 skip_first=True, 6009 indent=self.COPY_PARAMS_ARE_WRAPPED, 6010 ) 6011 6012 if params: 6013 if self.COPY_PARAMS_ARE_WRAPPED: 6014 params = f" WITH ({params})" 6015 elif not self.pretty and (files or credentials): 6016 params = f" {params}" 6017 6018 return f"COPY{this}{kind} {files}{credentials}{params}" 6019 6020 def semicolon_sql(self, expression: exp.Semicolon) -> str: 6021 return "" 6022 6023 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 6024 on_sql = "ON" if expression.args.get("on") else "OFF" 6025 filter_col: str | None = self.sql(expression, "filter_column") 6026 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 6027 retention_period: str | None = self.sql(expression, "retention_period") 6028 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 6029 6030 if filter_col or retention_period: 6031 on_sql = self.func("ON", filter_col, retention_period) 6032 6033 return f"DATA_DELETION={on_sql}" 6034 6035 def maskingpolicycolumnconstraint_sql( 6036 self, expression: exp.MaskingPolicyColumnConstraint 6037 ) -> str: 6038 this = self.sql(expression, "this") 6039 expressions = self.expressions(expression, flat=True) 6040 expressions = f" USING ({expressions})" if expressions else "" 6041 return f"MASKING POLICY {this}{expressions}" 6042 6043 def gapfill_sql(self, expression: exp.GapFill) -> str: 6044 this = self.sql(expression, "this") 6045 if isinstance(expression.this, exp.Table): 6046 this = f"TABLE {this}" 6047 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 6048 6049 def scope_resolution(self, rhs: str, scope_name: str) -> str: 6050 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 6051 6052 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 6053 this = self.sql(expression, "this") 6054 expr = expression.expression 6055 6056 if isinstance(expr, exp.Func): 6057 # T-SQL's CLR functions are case sensitive 6058 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 6059 else: 6060 expr = self.sql(expression, "expression") 6061 6062 return self.scope_resolution(expr, this) 6063 6064 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 6065 if self.PARSE_JSON_NAME is None: 6066 return self.sql(expression.this) 6067 6068 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 6069 6070 def rand_sql(self, expression: exp.Rand) -> str: 6071 lower = self.sql(expression, "lower") 6072 upper = self.sql(expression, "upper") 6073 6074 if lower and upper: 6075 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 6076 return self.func("RAND", expression.this) 6077 6078 def changes_sql(self, expression: exp.Changes) -> str: 6079 information = self.sql(expression, "information") 6080 information = f"INFORMATION => {information}" 6081 at_before = self.sql(expression, "at_before") 6082 at_before = f"{self.seg('')}{at_before}" if at_before else "" 6083 end = self.sql(expression, "end") 6084 end = f"{self.seg('')}{end}" if end else "" 6085 6086 return f"CHANGES ({information}){at_before}{end}" 6087 6088 def pad_sql(self, expression: exp.Pad) -> str: 6089 prefix = "L" if expression.args.get("is_left") else "R" 6090 6091 fill_pattern = self.sql(expression, "fill_pattern") or None 6092 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 6093 fill_pattern = "' '" 6094 6095 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 6096 6097 def summarize_sql(self, expression: exp.Summarize) -> str: 6098 table = " TABLE" if expression.args.get("table") else "" 6099 return f"SUMMARIZE{table} {self.sql(expression.this)}" 6100 6101 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 6102 generate_series = exp.GenerateSeries(**expression.args) 6103 6104 parent = expression.parent 6105 if isinstance(parent, (exp.Alias, exp.TableAlias)): 6106 parent = parent.parent 6107 6108 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 6109 return self.sql(exp.Unnest(expressions=[generate_series])) 6110 6111 if isinstance(parent, exp.Select): 6112 self.unsupported("GenerateSeries projection unnesting is not supported.") 6113 6114 return self.sql(generate_series) 6115 6116 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 6117 if self.SUPPORTS_CONVERT_TIMEZONE: 6118 return self.function_fallback_sql(expression) 6119 6120 source_tz = expression.args.get("source_tz") 6121 target_tz = expression.args.get("target_tz") 6122 timestamp = expression.args.get("timestamp") 6123 6124 if source_tz and timestamp: 6125 timestamp = exp.AtTimeZone( 6126 this=exp.cast(timestamp, exp.DType.TIMESTAMPNTZ), zone=source_tz 6127 ) 6128 6129 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 6130 6131 return self.sql(expr) 6132 6133 def json_sql(self, expression: exp.JSON) -> str: 6134 this = self.sql(expression, "this") 6135 this = f" {this}" if this else "" 6136 6137 _with = expression.args.get("with_") 6138 6139 if _with is None: 6140 with_sql = "" 6141 elif not _with: 6142 with_sql = " WITHOUT" 6143 else: 6144 with_sql = " WITH" 6145 6146 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 6147 6148 return f"JSON{this}{with_sql}{unique_sql}" 6149 6150 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 6151 path = self.sql(expression, "path") 6152 returning = self.sql(expression, "returning") 6153 returning = f" RETURNING {returning}" if returning else "" 6154 6155 on_condition = self.sql(expression, "on_condition") 6156 on_condition = f" {on_condition}" if on_condition else "" 6157 6158 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 6159 6160 def skipjsoncolumn_sql(self, expression: exp.SkipJSONColumn) -> str: 6161 regexp = " REGEXP" if expression.args.get("regexp") else "" 6162 return f"SKIP{regexp} {self.sql(expression.expression)}" 6163 6164 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 6165 else_ = "ELSE " if expression.args.get("else_") else "" 6166 condition = self.sql(expression, "expression") 6167 condition = f"WHEN {condition} THEN " if condition else else_ 6168 insert = self.sql(expression, "this")[len("INSERT") :].strip() 6169 return f"{condition}{insert}" 6170 6171 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 6172 kind = self.sql(expression, "kind") 6173 source = self.sql(expression, "source") 6174 6175 if kind: 6176 expressions = self.seg(self.expressions(expression, sep=" ")) 6177 sql = f"INSERT {kind}{expressions}{self.seg(source)}" 6178 else: 6179 # If kind isn't present, we have Hive's FROM-first form: 6180 # FROM x INSERT ... SELECT ... [INSERT ... SELECT ...] 6181 inserts = self.sep().join(self.sql(e) for e in expression.expressions) 6182 sql = f"FROM {source}{self.seg(inserts)}" 6183 6184 return self.prepend_ctes(expression, sql) 6185 6186 def oncondition_sql(self, expression: exp.OnCondition) -> str: 6187 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 6188 empty = expression.args.get("empty") 6189 empty = ( 6190 f"DEFAULT {empty} ON EMPTY" 6191 if isinstance(empty, exp.Expr) 6192 else self.sql(expression, "empty") 6193 ) 6194 6195 error = expression.args.get("error") 6196 error = ( 6197 f"DEFAULT {error} ON ERROR" 6198 if isinstance(error, exp.Expr) 6199 else self.sql(expression, "error") 6200 ) 6201 6202 if error and empty: 6203 error = ( 6204 f"{empty} {error}" 6205 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 6206 else f"{error} {empty}" 6207 ) 6208 empty = "" 6209 6210 null = self.sql(expression, "null") 6211 6212 return f"{empty}{error}{null}" 6213 6214 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 6215 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 6216 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 6217 6218 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 6219 this = self.sql(expression, "this") 6220 path = self.sql(expression, "path") 6221 6222 passing = self.expressions(expression, "passing") 6223 passing = f" PASSING {passing}" if passing else "" 6224 6225 on_condition = self.sql(expression, "on_condition") 6226 on_condition = f" {on_condition}" if on_condition else "" 6227 6228 path = f"{path}{passing}{on_condition}" 6229 6230 return self.func("JSON_EXISTS", this, path) 6231 6232 def _add_arrayagg_null_filter( 6233 self, 6234 array_agg_sql: str, 6235 array_agg_expr: exp.ArrayAgg, 6236 column_expr: exp.Expr, 6237 ) -> str: 6238 """ 6239 Add NULL filter to ARRAY_AGG if dialect requires it. 6240 6241 Args: 6242 array_agg_sql: The generated ARRAY_AGG SQL string 6243 array_agg_expr: The ArrayAgg expression node 6244 column_expr: The column/expression to filter (before ORDER BY wrapping) 6245 6246 Returns: 6247 SQL string with FILTER clause added if needed 6248 """ 6249 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 6250 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 6251 if not ( 6252 self.dialect.ARRAY_AGG_INCLUDES_NULLS and array_agg_expr.args.get("nulls_excluded") 6253 ): 6254 return array_agg_sql 6255 6256 parent = array_agg_expr.parent 6257 if isinstance(parent, exp.Filter): 6258 parent_cond = parent.expression.this 6259 parent_cond.replace(parent_cond.and_(column_expr.is_(exp.null()).not_())) 6260 elif column_expr.find(exp.Column): 6261 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 6262 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 6263 this_sql = ( 6264 self.expressions(column_expr) 6265 if isinstance(column_expr, exp.Distinct) 6266 else self.sql(column_expr) 6267 ) 6268 array_agg_sql = f"{array_agg_sql} FILTER(WHERE {this_sql} IS NOT NULL)" 6269 6270 return array_agg_sql 6271 6272 @unsupported_args("count") 6273 def min_sql(self, expression: exp.Min) -> str: 6274 return self.function_fallback_sql(expression) 6275 6276 @unsupported_args("count") 6277 def max_sql(self, expression: exp.Max) -> str: 6278 return self.function_fallback_sql(expression) 6279 6280 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 6281 array_agg = self.function_fallback_sql(expression) 6282 column_expr = expression.this 6283 if isinstance(column_expr, exp.Order): 6284 column_expr = column_expr.this 6285 6286 return self._add_arrayagg_null_filter(array_agg, expression, column_expr) 6287 6288 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 6289 # Only the SQLGlot dialect serializes the internal origin for round-tripping. 6290 origin = expression.args.get("origin") if self.dialect == "" else None 6291 kind = expression.args.get("kind") 6292 if origin is not None and kind is None: 6293 kind = exp.Literal.string("START") 6294 6295 return self.func( 6296 "TIME_SLICE", expression.this, expression.expression, expression.unit, kind, origin 6297 ) 6298 6299 def slice_sql(self, expression: exp.Slice) -> str: 6300 if "[" in self.dialect.tokenizer_class._IDENTIFIERS: 6301 self.unsupported("Slices are not supported") 6302 6303 step = self.sql(expression, "step") 6304 # An omitted end is written as `-` before a step, since `::` is the cast operator 6305 end = self.sql(expression.expression) or ("-" if step else "") 6306 begin = self.sql(expression.this) 6307 6308 sql = f"{end}:{step}" if step else end 6309 return f"{begin}:{sql}" if sql else f"{begin}:" 6310 6311 def apply_sql(self, expression: exp.Apply) -> str: 6312 this = self.sql(expression, "this") 6313 expr = self.sql(expression, "expression") 6314 6315 return f"{this} APPLY({expr})" 6316 6317 def _grant_or_revoke_sql( 6318 self, 6319 expression: exp.Grant | exp.Revoke, 6320 keyword: str, 6321 preposition: str, 6322 grant_option_prefix: str = "", 6323 grant_option_suffix: str = "", 6324 ) -> str: 6325 privileges_sql = self.expressions(expression, key="privileges", flat=True) 6326 6327 kind = self.sql(expression, "kind") 6328 kind = f" {kind}" if kind else "" 6329 6330 securable = self.sql(expression, "securable") 6331 securable = f" {securable}" if securable else "" 6332 6333 principals = self.expressions(expression, key="principals", flat=True) 6334 6335 if not expression.args.get("grant_option"): 6336 grant_option_prefix = grant_option_suffix = "" 6337 6338 # cascade for revoke only 6339 cascade = self.sql(expression, "cascade") 6340 cascade = f" {cascade}" if cascade else "" 6341 6342 return f"{keyword} {grant_option_prefix}{privileges_sql} ON{kind}{securable} {preposition} {principals}{grant_option_suffix}{cascade}" 6343 6344 def grant_sql(self, expression: exp.Grant) -> str: 6345 return self._grant_or_revoke_sql( 6346 expression, 6347 keyword="GRANT", 6348 preposition="TO", 6349 grant_option_suffix=" WITH GRANT OPTION", 6350 ) 6351 6352 def revoke_sql(self, expression: exp.Revoke) -> str: 6353 return self._grant_or_revoke_sql( 6354 expression, 6355 keyword="REVOKE", 6356 preposition="FROM", 6357 grant_option_prefix="GRANT OPTION FOR ", 6358 ) 6359 6360 def grantprivilege_sql(self, expression: exp.GrantPrivilege) -> str: 6361 this = self.sql(expression, "this") 6362 columns = self.expressions(expression, flat=True) 6363 columns = f"({columns})" if columns else "" 6364 6365 return f"{this}{columns}" 6366 6367 def grantprincipal_sql(self, expression: exp.GrantPrincipal) -> str: 6368 this = self.sql(expression, "this") 6369 6370 kind = self.sql(expression, "kind") 6371 kind = f"{kind} " if kind else "" 6372 6373 return f"{kind}{this}" 6374 6375 def columns_sql(self, expression: exp.Columns) -> str: 6376 func = self.function_fallback_sql(expression) 6377 if expression.args.get("unpack"): 6378 func = f"*{func}" 6379 6380 return func 6381 6382 def overlay_sql(self, expression: exp.Overlay) -> str: 6383 this = self.sql(expression, "this") 6384 expr = self.sql(expression, "expression") 6385 from_sql = self.sql(expression, "from_") 6386 for_sql = self.sql(expression, "for_") 6387 for_sql = f" FOR {for_sql}" if for_sql else "" 6388 6389 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 6390 6391 @unsupported_args("format") 6392 def todouble_sql(self, expression: exp.ToDouble) -> str: 6393 cast = exp.TryCast if expression.args.get("safe") else exp.Cast 6394 return self.sql(cast(this=expression.this, to=exp.DType.DOUBLE.into_expr())) 6395 6396 def string_sql(self, expression: exp.String) -> str: 6397 this = expression.this 6398 zone = expression.args.get("zone") 6399 6400 if zone: 6401 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 6402 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 6403 # set for source_tz to transpile the time conversion before the STRING cast 6404 this = exp.ConvertTimezone( 6405 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 6406 ) 6407 6408 return self.sql(exp.cast(this, exp.DType.VARCHAR)) 6409 6410 def median_sql(self, expression: exp.Median) -> str: 6411 if not self.SUPPORTS_MEDIAN: 6412 return self.sql( 6413 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 6414 ) 6415 6416 return self.function_fallback_sql(expression) 6417 6418 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 6419 filler = self.sql(expression, "this") 6420 filler = f" {filler}" if filler else "" 6421 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 6422 return f"TRUNCATE{filler} {with_count}" 6423 6424 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 6425 if self.SUPPORTS_UNIX_SECONDS: 6426 return self.function_fallback_sql(expression) 6427 6428 start_ts = exp.cast(exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DType.TIMESTAMPTZ) 6429 6430 return self.sql( 6431 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 6432 ) 6433 6434 def arraysort_sql(self, expression: exp.ArraySort) -> str: 6435 asc = expression.args.get("asc") 6436 nulls_first = expression.args.get("nulls_first") 6437 if (asc and asc != exp.true()) or (nulls_first and nulls_first != exp.false()): 6438 self.unsupported("ARRAY_SORT only sorts ascending with NULLs last") 6439 return self.func("ARRAY_SORT", expression.this, expression.expression) 6440 6441 def variance_sql(self, expression: exp.Variance, window: exp.Window | None = None) -> str: 6442 this = expression.this 6443 name = self.VARIANCE_NAME or self.function_name(expression) 6444 if not expression.args.get("single_value_returns_zero"): 6445 return self.func(name, this) 6446 6447 node: exp.Expr = expression 6448 while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)): 6449 node = node.parent 6450 if window is None and isinstance(node.parent, exp.Window) and node.arg_key == "this": 6451 self.unsupported("VARIANCE returning 0 for a single value is not supported in a window") 6452 return self.func(name, this) 6453 6454 expression.set("single_value_returns_zero", None) 6455 count: exp.Expr 6456 variance: exp.Expr = expression 6457 if window: 6458 count = window.copy() 6459 count.set("this", exp.Count(this=count.this.this)) 6460 variance = window 6461 else: 6462 count = exp.Count(this=this.copy()) 6463 6464 return self.sql( 6465 exp.case(count, copy=False) 6466 .when(0, exp.null(), copy=False) 6467 .when(1, 0, copy=False) 6468 .else_(variance, copy=False) 6469 ) 6470 6471 def arraysize_sql(self, expression: exp.ArraySize) -> str: 6472 dim = expression.expression 6473 6474 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 6475 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 6476 if not (dim.is_int and dim.name == "1"): 6477 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 6478 dim = None 6479 6480 # If dimension is required but not specified, default initialize it 6481 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 6482 dim = exp.Literal.number(1) 6483 6484 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 6485 6486 def attach_sql(self, expression: exp.Attach) -> str: 6487 this = self.sql(expression, "this") 6488 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 6489 expressions = self.expressions(expression) 6490 expressions = f" ({expressions})" if expressions else "" 6491 6492 return f"ATTACH{exists_sql} {this}{expressions}" 6493 6494 def detach_sql(self, expression: exp.Detach) -> str: 6495 kind = self.sql(expression, "kind") 6496 kind = f" {kind}" if kind else "" 6497 # the DATABASE keyword is required if IF EXISTS is set for DuckDB 6498 # ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax 6499 exists = " IF EXISTS" if expression.args.get("exists") else "" 6500 if exists: 6501 kind = kind or " DATABASE" 6502 6503 this = self.sql(expression, "this") 6504 this = f" {this}" if this else "" 6505 cluster = self.sql(expression, "cluster") 6506 cluster = f" {cluster}" if cluster else "" 6507 permanent = " PERMANENTLY" if expression.args.get("permanent") else "" 6508 sync = " SYNC" if expression.args.get("sync") else "" 6509 return f"DETACH{kind}{exists}{this}{cluster}{permanent}{sync}" 6510 6511 def attachoption_sql(self, expression: exp.AttachOption) -> str: 6512 this = self.sql(expression, "this") 6513 value = self.sql(expression, "expression") 6514 value = f" {value}" if value else "" 6515 return f"{this}{value}" 6516 6517 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 6518 return ( 6519 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 6520 ) 6521 6522 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 6523 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 6524 encode = f"{encode} {self.sql(expression, 'this')}" 6525 6526 properties = expression.args.get("properties") 6527 if properties: 6528 encode = f"{encode} {self.properties(properties)}" 6529 6530 return encode 6531 6532 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 6533 this = self.sql(expression, "this") 6534 include = f"INCLUDE {this}" 6535 6536 column_def = self.sql(expression, "column_def") 6537 if column_def: 6538 include = f"{include} {column_def}" 6539 6540 alias = self.sql(expression, "alias") 6541 if alias: 6542 include = f"{include} AS {alias}" 6543 6544 return include 6545 6546 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 6547 prefix = "EVALNAME" if expression.args.get("evalname") else "NAME" 6548 name = f"{prefix} {self.sql(expression, 'this')}" 6549 return self.func("XMLELEMENT", name, *expression.expressions) 6550 6551 def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str: 6552 this = self.sql(expression, "this") 6553 expr = self.sql(expression, "expression") 6554 expr = f"({expr})" if expr else "" 6555 return f"{this}{expr}" 6556 6557 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 6558 partitions = self.expressions(expression, "partition_expressions") 6559 create = self.expressions(expression, "create_expressions") 6560 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 6561 6562 def partitionbyrangepropertydynamic_sql( 6563 self, expression: exp.PartitionByRangePropertyDynamic 6564 ) -> str: 6565 start = self.sql(expression, "start") 6566 end = self.sql(expression, "end") 6567 6568 every = expression.args["every"] 6569 if isinstance(every, exp.Interval) and every.this.is_string: 6570 every.this.replace(exp.Literal.number(every.name)) 6571 6572 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 6573 6574 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 6575 name = self.sql(expression, "this") 6576 values = self.expressions(expression, flat=True) 6577 6578 return f"NAME {name} VALUE {values}" 6579 6580 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 6581 kind = self.sql(expression, "kind") 6582 sample = self.sql(expression, "sample") 6583 return f"SAMPLE {sample} {kind}" 6584 6585 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 6586 kind = self.sql(expression, "kind") 6587 option = self.sql(expression, "option") 6588 option = f" {option}" if option else "" 6589 this = self.sql(expression, "this") 6590 this = f" {this}" if this else "" 6591 columns = self.expressions(expression) 6592 columns = f" {columns}" if columns else "" 6593 return f"{kind}{option} STATISTICS{this}{columns}" 6594 6595 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 6596 this = self.sql(expression, "this") 6597 columns = self.expressions(expression) 6598 inner_expression = self.sql(expression, "expression") 6599 inner_expression = f" {inner_expression}" if inner_expression else "" 6600 update_options = self.sql(expression, "update_options") 6601 update_options = f" {update_options} UPDATE" if update_options else "" 6602 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 6603 6604 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 6605 kind = self.sql(expression, "kind") 6606 kind = f" {kind}" if kind else "" 6607 return f"DELETE{kind} STATISTICS" 6608 6609 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 6610 inner_expression = self.sql(expression, "expression") 6611 return f"LIST CHAINED ROWS{inner_expression}" 6612 6613 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 6614 kind = self.sql(expression, "kind") 6615 this = self.sql(expression, "this") 6616 this = f" {this}" if this else "" 6617 inner_expression = self.sql(expression, "expression") 6618 return f"VALIDATE {kind}{this}{inner_expression}" 6619 6620 def analyze_sql(self, expression: exp.Analyze) -> str: 6621 options = self.expressions(expression, key="options", sep=" ") 6622 options = f" {options}" if options else "" 6623 kind = self.sql(expression, "kind") 6624 kind = f" {kind}" if kind else "" 6625 tables = self.expressions(expression, key="tables", flat=True) 6626 tables = f" {tables}" if tables else "" 6627 mode = self.sql(expression, "mode") 6628 mode = f" {mode}" if mode else "" 6629 properties = self.sql(expression, "properties") 6630 properties = f" {properties}" if properties else "" 6631 partition = self.sql(expression, "partition") 6632 partition = f" {partition}" if partition else "" 6633 inner_expression = self.sql(expression, "expression") 6634 inner_expression = f" {inner_expression}" if inner_expression else "" 6635 return f"ANALYZE{options}{kind}{tables}{partition}{mode}{inner_expression}{properties}" 6636 6637 def xmltable_sql(self, expression: exp.XMLTable) -> str: 6638 this = self.sql(expression, "this") 6639 namespaces = self.expressions(expression, key="namespaces") 6640 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 6641 passing = self.expressions(expression, key="passing") 6642 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 6643 columns = self.expressions(expression, key="columns") 6644 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 6645 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 6646 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 6647 6648 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 6649 this = self.sql(expression, "this") 6650 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 6651 6652 def export_sql(self, expression: exp.Export) -> str: 6653 this = self.sql(expression, "this") 6654 connection = self.sql(expression, "connection") 6655 connection = f"WITH CONNECTION {connection} " if connection else "" 6656 options = self.sql(expression, "options") 6657 return f"EXPORT DATA {connection}{options} AS {this}" 6658 6659 def declare_sql(self, expression: exp.Declare) -> str: 6660 replace = "OR REPLACE " if expression.args.get("replace") else "" 6661 return f"DECLARE {replace}{self.expressions(expression, flat=True)}" 6662 6663 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 6664 variables = self.expressions(expression, "this") 6665 default = self.sql(expression, "default") 6666 default = f" {self.DECLARE_DEFAULT_ASSIGNMENT} {default}" if default else "" 6667 6668 kind = self.sql(expression, "kind") 6669 if isinstance(expression.args.get("kind"), exp.Schema): 6670 kind = f"TABLE {kind}" 6671 6672 kind = f" {kind}" if kind else "" 6673 6674 return f"{variables}{kind}{default}" 6675 6676 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 6677 kind = self.sql(expression, "kind") 6678 this = self.sql(expression, "this") 6679 set = self.sql(expression, "expression") 6680 to = self.sql(expression, "to") 6681 to = f" TO {to}" if to else "" 6682 default = self.sql(expression, "default") 6683 default = f" DEFAULT {default}" if default else "" 6684 using = self.sql(expression, "using") 6685 using = f" USING {using}" if using else "" 6686 6687 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 6688 6689 return f"{kind_sql} {this} SET {set}{to}{default}{using}" 6690 6691 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 6692 params = self.expressions(expression, key="params", flat=True) 6693 return self.func(expression.name, *expression.expressions) + f"({params})" 6694 6695 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 6696 return self.func(expression.name, *expression.expressions) 6697 6698 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 6699 return self.anonymousaggfunc_sql(expression) 6700 6701 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 6702 return self.parameterizedagg_sql(expression) 6703 6704 def show_sql(self, expression: exp.Show) -> str: 6705 self.unsupported("Unsupported SHOW statement") 6706 return "" 6707 6708 def install_sql(self, expression: exp.Install) -> str: 6709 self.unsupported("Unsupported INSTALL statement") 6710 return "" 6711 6712 def liststage_sql(self, expression: exp.ListStage) -> str: 6713 pattern = self.sql(expression, "pattern") 6714 pattern = f" PATTERN = {pattern}" if pattern else "" 6715 return f"LIST {self.sql(expression, 'this')}{pattern}" 6716 6717 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 6718 # Snowflake GET/PUT statements: 6719 # PUT <file> <internalStage> <properties> 6720 # GET <internalStage> <file> <properties> 6721 props = expression.args.get("properties") 6722 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 6723 this = self.sql(expression, "this") 6724 target = self.sql(expression, "target") 6725 6726 if isinstance(expression, exp.Put): 6727 return f"PUT {this} {target}{props_sql}" 6728 else: 6729 return f"GET {target} {this}{props_sql}" 6730 6731 def translatecharacters_sql(self, expression: exp.TranslateCharacters) -> str: 6732 this = self.sql(expression, "this") 6733 expr = self.sql(expression, "expression") 6734 with_error = " WITH ERROR" if expression.args.get("with_error") else "" 6735 return f"TRANSLATE({this} USING {expr}{with_error})" 6736 6737 def decodecase_sql(self, expression: exp.DecodeCase) -> str: 6738 if self.SUPPORTS_DECODE_CASE: 6739 return self.func("DECODE", *expression.expressions) 6740 6741 decode_expr, *expressions = expression.expressions 6742 6743 ifs = [] 6744 for search, result in zip(expressions[::2], expressions[1::2]): 6745 if isinstance(search, exp.Literal): 6746 ifs.append(exp.If(this=decode_expr.eq(search), true=result)) 6747 elif isinstance(search, exp.Null): 6748 ifs.append(exp.If(this=decode_expr.is_(exp.Null()), true=result)) 6749 else: 6750 if isinstance(search, exp.Binary): 6751 search = exp.paren(search) 6752 6753 cond = exp.or_( 6754 decode_expr.eq(search), 6755 exp.and_(decode_expr.is_(exp.Null()), search.is_(exp.Null()), copy=False), 6756 copy=False, 6757 ) 6758 ifs.append(exp.If(this=cond, true=result)) 6759 6760 case = exp.Case(ifs=ifs, default=expressions[-1] if len(expressions) % 2 == 1 else None) 6761 return self.sql(case) 6762 6763 def semanticview_sql(self, expression: exp.SemanticView) -> str: 6764 this = self.sql(expression, "this") 6765 this = self.seg(this, sep="") 6766 dimensions = self.expressions( 6767 expression, "dimensions", dynamic=True, skip_first=True, skip_last=True 6768 ) 6769 dimensions = self.seg(f"DIMENSIONS {dimensions}") if dimensions else "" 6770 metrics = self.expressions( 6771 expression, "metrics", dynamic=True, skip_first=True, skip_last=True 6772 ) 6773 metrics = self.seg(f"METRICS {metrics}") if metrics else "" 6774 facts = self.expressions(expression, "facts", dynamic=True, skip_first=True, skip_last=True) 6775 facts = self.seg(f"FACTS {facts}") if facts else "" 6776 where = self.sql(expression, "where") 6777 where = self.seg(f"WHERE {where}") if where else "" 6778 body = self.indent(this + metrics + dimensions + facts + where, skip_first=True) 6779 return f"SEMANTIC_VIEW({body}{self.seg(')', sep='')}" 6780 6781 def getextract_sql(self, expression: exp.GetExtract) -> str: 6782 this = expression.this 6783 expr = expression.expression 6784 6785 if not this.type or not expression.type: 6786 import sqlglot.optimizer.annotate_types 6787 6788 this = sqlglot.optimizer.annotate_types.annotate_types(this, dialect=self.dialect) 6789 6790 if this.is_type(*(exp.DType.ARRAY, exp.DType.MAP)): 6791 return self.sql(exp.Bracket(this=this, expressions=[expr])) 6792 6793 return self.sql(exp.JSONExtract(this=this, expression=self.dialect.to_json_path(expr))) 6794 6795 def datefromunixdate_sql(self, expression: exp.DateFromUnixDate) -> str: 6796 return self.sql( 6797 exp.DateAdd( 6798 this=exp.cast(exp.Literal.string("1970-01-01"), exp.DType.DATE), 6799 expression=expression.this, 6800 unit=exp.var("DAY"), 6801 ) 6802 ) 6803 6804 def space_sql(self: Generator, expression: exp.Space) -> str: 6805 return self.sql(exp.Repeat(this=exp.Literal.string(" "), times=expression.this)) 6806 6807 def buildproperty_sql(self, expression: exp.BuildProperty) -> str: 6808 return f"BUILD {self.sql(expression, 'this')}" 6809 6810 def refreshtriggerproperty_sql(self, expression: exp.RefreshTriggerProperty) -> str: 6811 method = self.sql(expression, "method") 6812 kind = expression.args.get("kind") 6813 if not kind: 6814 return f"REFRESH {method}" 6815 6816 every = self.sql(expression, "every") 6817 unit = self.sql(expression, "unit") 6818 every = f" EVERY {every} {unit}" if every else "" 6819 starts = self.sql(expression, "starts") 6820 starts = f" STARTS {starts}" if starts else "" 6821 6822 return f"REFRESH {method} ON {kind}{every}{starts}" 6823 6824 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 6825 self.unsupported("The model!attribute syntax is not supported") 6826 return "" 6827 6828 def directorystage_sql(self, expression: exp.DirectoryStage) -> str: 6829 return self.func("DIRECTORY", expression.this) 6830 6831 def uuid_sql(self, expression: exp.Uuid) -> str: 6832 is_string = expression.args.get("is_string", False) 6833 uuid_func_sql = self.func("UUID") 6834 6835 if is_string and not self.dialect.UUID_IS_STRING_TYPE: 6836 return self.sql(exp.cast(uuid_func_sql, exp.DType.VARCHAR, dialect=self.dialect)) 6837 6838 return uuid_func_sql 6839 6840 def initcap_sql(self, expression: exp.Initcap) -> str: 6841 delimiters = expression.expression 6842 6843 if delimiters: 6844 # do not generate delimiters arg if we are round-tripping from default delimiters 6845 if ( 6846 delimiters.is_string 6847 and delimiters.this == self.dialect.INITCAP_DEFAULT_DELIMITER_CHARS 6848 ): 6849 delimiters = None 6850 elif not self.dialect.INITCAP_SUPPORTS_CUSTOM_DELIMITERS: 6851 self.unsupported("INITCAP does not support custom delimiters") 6852 delimiters = None 6853 6854 return self.func("INITCAP", expression.this, delimiters) 6855 6856 def localtime_sql(self, expression: exp.Localtime) -> str: 6857 this = expression.this 6858 return self.func("LOCALTIME", this) if this else "LOCALTIME" 6859 6860 def localtimestamp_sql(self, expression: exp.Localtimestamp) -> str: 6861 this = expression.this 6862 return self.func("LOCALTIMESTAMP", this) if this else "LOCALTIMESTAMP" 6863 6864 def weekstart_name(self, expression: exp.WeekStart) -> str: 6865 import sqlglot.dialects.dialect 6866 6867 # WEEK(<day>) is BigQuery-only syntax, so it degrades to the plain WEEK unit 6868 this = expression.this.name.upper() 6869 6870 dow_from_week_start_day = sqlglot.dialects.dialect.WEEK_START_DAY_TO_DOW.get(this) 6871 dow_from_week_offset = sqlglot.dialects.dialect.week_offset_to_dow(self.dialect.WEEK_OFFSET) 6872 6873 if dow_from_week_start_day != dow_from_week_offset: 6874 self.unsupported( 6875 f"WEEK({this}) is not supported; falling back to the default week start day" 6876 ) 6877 6878 return "WEEK" 6879 6880 def weekstart_sql(self, expression: exp.WeekStart) -> str: 6881 name = self.weekstart_name(expression) 6882 6883 # DateTrunc stores string literal units, whereas TimeUnit expressions store keywords 6884 if isinstance(expression.parent, exp.DateTrunc): 6885 return self.sql(exp.Literal.string(name)) 6886 6887 return name 6888 6889 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 6890 self._warn_unsupported_arg(expression, "century_from_zero") 6891 unit = expression.unit 6892 if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"): 6893 self.unsupported(f"Unexpected interval unit: {unit.name}") 6894 6895 return self.function_fallback_sql(expression) 6896 6897 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 6898 args = expression.expressions 6899 if len(args) > 1 and not self.SUPPORTS_MULTI_ARG_CHR: 6900 # CHAR(72, 105) -> CHR(72) || CHR(105) 6901 chars: list[exp.Expr] = [exp.Chr(expressions=[arg.copy()]) for arg in args] 6902 return self.sql(reduce(lambda x, y: exp.DPipe(this=x, expression=y), chars)) 6903 6904 this = self.expressions(expression) 6905 charset = self.sql(expression, "charset") 6906 using = f" USING {charset}" if charset else "" 6907 return self.func(name, this + using) 6908 6909 def weightstring_sql(self, expression: exp.WeightString) -> str: 6910 to = self.sql(expression, "to") 6911 to = f" AS {to}" if to else "" 6912 return self.func("WEIGHT_STRING", f"{self.sql(expression, 'this')}{to}") 6913 6914 def block_sql(self, expression: exp.Block) -> str: 6915 expressions = self.expressions(expression, sep="; ", flat=True) 6916 begin = "BEGIN " if expression.args.get("begin") else "" 6917 return f"{begin}{expressions}" if expressions else "" 6918 6919 def functionspecification_sql(self, expression: exp.FunctionSpecification) -> str: 6920 self.unsupported("Unsupported Inline UDFs syntax") 6921 return "" 6922 6923 def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str: 6924 self.unsupported("Unsupported Stored Procedure syntax") 6925 return "" 6926 6927 def ifblock_sql(self, expression: exp.IfBlock) -> str: 6928 self.unsupported("Unsupported If block syntax") 6929 return "" 6930 6931 def casestatement_sql(self, expression: exp.CaseStatement) -> str: 6932 self.unsupported("Unsupported Case statement syntax") 6933 return "" 6934 6935 def whileblock_sql(self, expression: exp.WhileBlock) -> str: 6936 self.unsupported("Unsupported While block syntax") 6937 return "" 6938 6939 def loopblock_sql(self, expression: exp.LoopBlock) -> str: 6940 self.unsupported("Unsupported Loop block syntax") 6941 return "" 6942 6943 def repeatblock_sql(self, expression: exp.RepeatBlock) -> str: 6944 self.unsupported("Unsupported Repeat block syntax") 6945 return "" 6946 6947 def leave_sql(self, expression: exp.Leave) -> str: 6948 self.unsupported("Unsupported Leave syntax") 6949 return "" 6950 6951 def iterate_sql(self, expression: exp.Iterate) -> str: 6952 self.unsupported("Unsupported Iterate syntax") 6953 return "" 6954 6955 def execute_sql(self, expression: exp.Execute) -> str: 6956 self.unsupported("Unsupported Execute syntax") 6957 return "" 6958 6959 def executesql_sql(self, expression: exp.ExecuteSql) -> str: 6960 self.unsupported("Unsupported Execute syntax") 6961 return "" 6962 6963 def executeimmediate_sql(self, expression: exp.ExecuteImmediate) -> str: 6964 if not self.SUPPORTS_EXECUTE_IMMEDIATE: 6965 self.unsupported("EXECUTE IMMEDIATE is not supported") 6966 return "" 6967 using = self.expressions(expression, flat=True) 6968 using = f" USING {using}" if using else "" 6969 return f"EXECUTE IMMEDIATE {self.sql(expression, 'this')}{using}" 6970 6971 def altermodifysqlsecurity_sql(self, expression: exp.AlterModifySqlSecurity) -> str: 6972 props = self.expressions(expression, sep=" ") 6973 return f"MODIFY {props}" 6974 6975 def usingproperty_sql(self, expression: exp.UsingProperty) -> str: 6976 kind = expression.args.get("kind") 6977 return f"USING {kind} {self.sql(expression, 'this')}" 6978 6979 def renameindex_sql(self, expression: exp.RenameIndex) -> str: 6980 this = self.sql(expression, "this") 6981 to = self.sql(expression, "to") 6982 return f"RENAME INDEX {this} TO {to}"
logger =
<Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE =
re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE =
"Argument '{}' is not supported for expression '{}' when targeting {}."
def
unsupported_args( *args: str | tuple[str, str]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
35def unsupported_args( 36 *args: str | tuple[str, str], 37) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 38 """ 39 Decorator that can be used to mark certain args of an `Expr` subclass as unsupported. 40 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 41 """ 42 diagnostic_by_arg: dict[str, str | None] = {} 43 for arg in args: 44 if isinstance(arg, str): 45 diagnostic_by_arg[arg] = None 46 else: 47 diagnostic_by_arg[arg[0]] = arg[1] 48 49 def decorator(func: GeneratorMethod) -> GeneratorMethod: 50 @wraps(func) 51 def _func(generator: G, expression: E) -> str: 52 for arg_name, diagnostic in diagnostic_by_arg.items(): 53 generator._warn_unsupported_arg(expression, arg_name, diagnostic) 54 55 return func(generator, expression) 56 57 return _func 58 59 return decorator
Decorator that can be used to mark certain args of an Expr subclass as unsupported.
It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
AFTER_HAVING_MODIFIER_TRANSFORMS: dict[str, typing.Any] =
{'windows': <function <lambda>>, 'qualify': <function <lambda>>}
class
Generator:
93class Generator: 94 """ 95 Generator converts a given syntax tree to the corresponding SQL string. 96 97 Args: 98 pretty: Whether to format the produced SQL string. 99 Default: False. 100 identify: Determines when an identifier should be quoted. Possible values are: 101 False (default): Never quote, except in cases where it's mandatory by the dialect. 102 True: Always quote except for specials cases. 103 'safe': Only quote identifiers that are case insensitive. 104 normalize: Whether to normalize identifiers to lowercase. 105 Default: False. 106 pad: The pad size in a formatted string. For example, this affects the indentation of 107 a projection in a query, relative to its nesting level. 108 Default: 2. 109 indent: The indentation size in a formatted string. For example, this affects the 110 indentation of subqueries and filters under a `WHERE` clause. 111 Default: 2. 112 normalize_functions: How to normalize function names. Possible values are: 113 "upper" or True (default): Convert names to uppercase. 114 "lower": Convert names to lowercase. 115 False: Disables function name normalization. 116 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 117 Default ErrorLevel.WARN. 118 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 119 This is only relevant if unsupported_level is ErrorLevel.RAISE. 120 Default: 3 121 leading_comma: Whether the comma is leading or trailing in select expressions. 122 This is only relevant when generating in pretty mode. 123 Default: False 124 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 125 The default is on the smaller end because the length only represents a segment and not the true 126 line length. 127 Default: 80 128 comments: Whether to preserve comments in the output SQL code. 129 Default: True 130 """ 131 132 TRANSFORMS: t.ClassVar[dict[type[exp.Expr], t.Callable[..., str]]] = { 133 **JSON_PATH_PART_TRANSFORMS, 134 exp.Adjacent: lambda self, e: self.binary(e, "-|-"), 135 exp.AllowedValuesProperty: lambda self, e: ( 136 f"ALLOWED_VALUES {self.expressions(e, flat=True)}" 137 ), 138 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 139 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 140 exp.ArrayContainedBy: lambda self, e: self.binary(e, "<@"), 141 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 142 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 143 exp.AssumeColumnConstraint: lambda self, e: f"ASSUME ({self.sql(e, 'this')})", 144 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 145 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 146 exp.BinaryColumnConstraint: lambda *_: "BINARY", 147 exp.CaseSpecificColumnConstraint: lambda _, e: ( 148 f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC" 149 ), 150 exp.CalledOnNullInputProperty: lambda *_: "CALLED ON NULL INPUT", 151 exp.Ceil: lambda self, e: self.ceil_floor(e), 152 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 153 exp.CharacterSetProperty: lambda self, e: ( 154 f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}" 155 ), 156 exp.ClusteredColumnConstraint: lambda self, e: ( 157 f"CLUSTERED ({self.expressions(e, 'this', indent=False)})" 158 ), 159 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 160 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 161 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 162 exp.ConvertToCharset: lambda self, e: self.func( 163 "CONVERT", e.this, e.args["dest"], e.args.get("source") 164 ), 165 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 166 exp.CopyTagsProperty: lambda *_: "COPY TAGS", 167 exp.CredentialsProperty: lambda self, e: ( 168 f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})" 169 ), 170 exp.CurrentCatalog: lambda *_: "CURRENT_CATALOG", 171 exp.SessionUser: lambda *_: "SESSION_USER", 172 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 173 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 174 exp.ApiProperty: lambda *_: "API", 175 exp.ApplicationProperty: lambda *_: "APPLICATION", 176 exp.CatalogProperty: lambda *_: "CATALOG", 177 exp.ComputeProperty: lambda *_: "COMPUTE", 178 exp.DatabaseProperty: lambda *_: "DATABASE", 179 exp.DynamicProperty: lambda *_: "DYNAMIC", 180 exp.EmptyProperty: lambda *_: "EMPTY", 181 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 182 exp.EndStatement: lambda *_: "END", 183 exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})", 184 exp.HandlerProperty: lambda self, e: f"HANDLER {self.sql(e, 'this')}", 185 exp.ParameterStyleProperty: lambda self, e: f"PARAMETER STYLE {self.sql(e, 'this')}", 186 exp.EphemeralColumnConstraint: lambda self, e: ( 187 f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}" 188 ), 189 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 190 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 191 exp.Except: lambda self, e: self.set_operations(e), 192 exp.ExternalProperty: lambda *_: "EXTERNAL", 193 exp.Floor: lambda self, e: self.ceil_floor(e), 194 exp.Get: lambda self, e: self.get_put_sql(e), 195 exp.GlobalProperty: lambda *_: "GLOBAL", 196 exp.HeapProperty: lambda *_: "HEAP", 197 exp.HybridProperty: lambda *_: "HYBRID", 198 exp.IcebergProperty: lambda *_: "ICEBERG", 199 exp.IgnoreGrantsProperty: lambda *_: "IGNORE GRANTS", 200 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 201 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 202 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 203 exp.Intersect: lambda self, e: self.set_operations(e), 204 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 205 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DType.BIGINT)), 206 exp.JSONBContainsAnyTopKeys: lambda self, e: self.binary(e, "?|"), 207 exp.JSONBContainsAllTopKeys: lambda self, e: self.binary(e, "?&"), 208 exp.JSONBContainsTopKey: lambda self, e: self.binary(e, "?"), 209 exp.JSONBDeleteAtPath: lambda self, e: self.binary(e, "#-"), 210 exp.JSONBPathExists: lambda self, e: self.binary(e, "@?"), 211 exp.JSONObject: lambda self, e: self._jsonobject_sql(e), 212 exp.JSONObjectAgg: lambda self, e: self._jsonobject_sql(e), 213 exp.LanguageProperty: lambda self, e: self.naked_property(e), 214 exp.LocationProperty: lambda self, e: self.naked_property(e), 215 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 216 exp.MaskingProperty: lambda *_: "MASKING", 217 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 218 exp.NetFunc: lambda self, e: f"NET.{self.sql(e, 'this')}", 219 exp.NetworkProperty: lambda *_: "NETWORK", 220 exp.NonClusteredColumnConstraint: lambda self, e: ( 221 f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})" 222 ), 223 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 224 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 225 exp.OnCommitProperty: lambda _, e: ( 226 f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS" 227 ), 228 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 229 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 230 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 231 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 232 exp.ExtendsLeft: lambda self, e: self.binary(e, "&<"), 233 exp.ExtendsRight: lambda self, e: self.binary(e, "&>"), 234 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 235 exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression), 236 exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression), 237 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 238 exp.PositionalColumn: lambda self, e: f"#{self.sql(e, 'this')}", 239 exp.ProjectionPolicyColumnConstraint: lambda self, e: ( 240 f"PROJECTION POLICY {self.sql(e, 'this')}" 241 ), 242 exp.InvisibleColumnConstraint: lambda self, e: "INVISIBLE", 243 exp.ZeroFillColumnConstraint: lambda self, e: "ZEROFILL", 244 exp.Put: lambda self, e: self.get_put_sql(e), 245 exp.RemoteWithConnectionModelProperty: lambda self, e: ( 246 f"REMOTE WITH CONNECTION {self.sql(e, 'this')}" 247 ), 248 exp.ReturnsProperty: lambda self, e: ( 249 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 250 ), 251 exp.RowAccessProperty: lambda *_: "ROW ACCESS", 252 exp.SafeFunc: lambda self, e: f"SAFE.{self.sql(e, 'this')}", 253 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 254 exp.SecureProperty: lambda *_: "SECURE", 255 exp.SecurityIntegrationProperty: lambda *_: "SECURITY", 256 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 257 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 258 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 259 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 260 exp.SqlReadWriteProperty: lambda _, e: e.name, 261 exp.SqlSecurityProperty: lambda self, e: f"SQL SECURITY {self.sql(e, 'this')}", 262 exp.StabilityProperty: lambda _, e: e.name, 263 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 264 exp.StreamingTableProperty: lambda *_: "STREAMING", 265 exp.StrictProperty: lambda *_: "STRICT", 266 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 267 exp.TableColumn: lambda self, e: self.sql(e.this), 268 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 269 exp.TemporaryProperty: lambda *_: "TEMPORARY", 270 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 271 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 272 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 273 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 274 exp.TransientProperty: lambda *_: "TRANSIENT", 275 exp.VirtualProperty: lambda *_: "VIRTUAL", 276 exp.TriggerExecute: lambda self, e: f"EXECUTE FUNCTION {self.sql(e, 'this')}", 277 exp.Union: lambda self, e: self.set_operations(e), 278 exp.UnloggedProperty: lambda *_: "UNLOGGED", 279 exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 280 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 281 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 282 exp.UtcDate: lambda self, e: self.sql(exp.CurrentDate(this=exp.Literal.string("UTC"))), 283 exp.UtcTime: lambda self, e: self.sql(exp.CurrentTime(this=exp.Literal.string("UTC"))), 284 exp.UtcTimestamp: lambda self, e: self.sql( 285 exp.CurrentTimestamp(this=exp.Literal.string("UTC")) 286 ), 287 exp.Variadic: lambda self, e: f"VARIADIC {self.sql(e, 'this')}", 288 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 289 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 290 exp.VolatileProperty: lambda *_: "VOLATILE", 291 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 292 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 293 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 294 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 295 exp.WithoutRowidProperty: lambda *_: "WITHOUT ROWID", 296 exp.ForceProperty: lambda *_: "FORCE", 297 } 298 299 # Whether null ordering is supported in order by 300 # True: Full Support, None: No support, False: No support for certain cases 301 # such as window specifications, aggregate functions etc 302 NULL_ORDERING_SUPPORTED: bool | None = True 303 304 # Window functions that support NULLS FIRST/LAST 305 WINDOW_FUNCS_WITH_NULL_ORDERING: t.ClassVar[tuple[type[exp.Expression], ...]] = () 306 307 # Window functions that require an ORDER BY in their window specification 308 WINDOW_FUNCS_REQUIRING_ORDER: t.ClassVar[tuple[type[exp.Expression], ...]] = () 309 310 # Whether ignore nulls is inside the agg or outside. 311 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 312 IGNORE_NULLS_IN_FUNC = False 313 314 # Whether IGNORE NULLS is placed before ORDER BY in the agg. 315 # FIRST(x IGNORE NULLS ORDER BY y) vs FIRST(x ORDER BY y IGNORE NULLS) 316 IGNORE_NULLS_BEFORE_ORDER = True 317 318 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 319 LOCKING_READS_SUPPORTED = False 320 321 # Whether the EXCEPT and INTERSECT operations can return duplicates 322 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 323 324 # Wrap derived values in parens, usually standard but spark doesn't support it 325 WRAP_DERIVED_VALUES = True 326 327 # Whether create function uses an AS before the RETURN 328 CREATE_FUNCTION_RETURN_AS = True 329 330 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 331 MATCHED_BY_SOURCE = True 332 333 # Whether MERGE ... WHEN MATCHED/NOT MATCHED THEN UPDATE/INSERT ... WHERE is supported 334 SUPPORTS_MERGE_WHERE = False 335 336 # First version supporting MERGE WITH SCHEMA EVOLUTION 337 MERGE_SCHEMA_EVOLUTION_MIN_VERSION: t.ClassVar[tuple[int, ...] | None] = None 338 339 # Whether MERGE uses ALL BY NAME instead of a star to update or insert all columns 340 MERGE_ALL_BY_NAME = False 341 342 # Whether the INTERVAL expression works only with values like '1 day' 343 SINGLE_STRING_INTERVAL = False 344 345 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 346 INTERVAL_ALLOWS_PLURAL_FORM = True 347 348 # Whether intervals in a REFRESH schedule (AutoRefreshProperty) are generated without the 349 # INTERVAL keyword, e.g. ClickHouse's REFRESH EVERY 30 SECOND 350 AUTO_REFRESH_BARE_INTERVALS = False 351 352 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 353 LIMIT_FETCH = "ALL" 354 355 # Whether limit and fetch allows expressions or just limits 356 LIMIT_ONLY_LITERALS = False 357 358 # Whether a table is allowed to be renamed with a db 359 RENAME_TABLE_WITH_DB = True 360 361 # The separator for grouping sets and rollups 362 GROUPINGS_SEP = "," 363 364 # Whether GROUPING SETS can follow GROUP BY expressions without a comma 365 SUPPORTS_GROUPING_SETS_AS_SUFFIX = False 366 367 # The string used for creating an index on a table 368 INDEX_ON = "ON" 369 370 # Separator for IN/OUT parameter mode (Oracle uses " " for "IN OUT", PostgreSQL uses "" for "INOUT") 371 INOUT_SEPARATOR = " " 372 373 # Whether join hints should be generated 374 JOIN_HINTS = True 375 376 # Whether directed joins are supported 377 DIRECTED_JOINS = False 378 379 # Whether top-k distance/similarity joins are supported 380 SUPPORTS_NEAREST_JOIN = False 381 382 # Whether MATCH_CONDITION in ASOF joins is supported 383 SUPPORTS_MATCH_CONDITION = False 384 385 # Whether ASOF JOIN MATCH_CONDITION should be folded into the ON clause 386 MATCH_CONDITION_IN_ON = False 387 388 # Whether table hints should be generated 389 TABLE_HINTS = True 390 391 # Whether query hints should be generated 392 QUERY_HINTS = True 393 394 # What kind of separator to use for query hints 395 QUERY_HINT_SEP = ", " 396 397 # Whether comparing against booleans (e.g. x IS TRUE) is supported 398 IS_BOOL_ALLOWED = True 399 400 # Whether casting a fractional number to an integer rounds it instead of truncating it 401 CAST_TO_INT_ROUNDS = False 402 403 # Whether the native integer division operator returns NULL for a zero divisor instead of raising 404 SAFE_INT_DIVISION = False 405 406 # The infix integer division operator, e.g. DIV in MySQL. If unset, IntDiv is a truncated division 407 INT_DIV_OPERATOR: str | None = None 408 409 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 410 DUPLICATE_KEY_UPDATE_WITH_SET = True 411 412 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 413 LIMIT_IS_TOP = False 414 415 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 416 RETURNING_END = True 417 418 # Whether to generate an unquoted value for EXTRACT's date part argument 419 EXTRACT_ALLOWS_QUOTES = True 420 421 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 422 TZ_TO_WITH_TIME_ZONE = False 423 424 # Whether the NVL2 function is supported 425 NVL2_SUPPORTED = True 426 427 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 428 SELECT_KINDS: t.ClassVar[tuple[str, ...]] = ("STRUCT", "VALUE") 429 430 # Whether VALUES statements can be used as derived tables. 431 # MySQL 5 and Redshift do not allow this, so when False, it will convert 432 # SELECT * VALUES into SELECT UNION 433 VALUES_AS_TABLE = True 434 435 # Whether COLUMN/COLUMNS keywords are included when adding columns with ALTER TABLE. 436 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 437 438 # Whether ALTER TABLE mutli-column additions are wrapped in parentheses. 439 ALTER_TABLE_ADD_COLUMNS_WRAPPED = True 440 441 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 442 UNNEST_WITH_ORDINALITY = True 443 444 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 445 SEMI_ANTI_JOIN_WITH_SIDE = True 446 447 # Whether to include the type of a computed column in the CREATE DDL 448 COMPUTED_COLUMN_WITH_TYPE = True 449 450 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 451 SUPPORTS_TABLE_COPY = True 452 453 # Whether parentheses are required around the table sample's expression 454 TABLESAMPLE_REQUIRES_PARENS = True 455 456 # Whether a table sample clause's size needs to be followed by the ROWS keyword 457 TABLESAMPLE_SIZE_IS_ROWS = True 458 459 # The keyword(s) to use when generating a sample clause 460 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 461 462 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 463 TABLESAMPLE_WITH_METHOD = True 464 465 # The keyword to use when specifying the seed of a sample clause 466 TABLESAMPLE_SEED_KEYWORD = "SEED" 467 468 # Whether the historical data clause (AT ... / BEFORE ...) is generated after the table alias 469 HISTORICAL_DATA_POST_ALIAS = False 470 471 # Whether COLLATE is a function instead of a binary operator 472 COLLATE_IS_FUNC = False 473 474 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 475 DATA_TYPE_SPECIFIERS_ALLOWED = False 476 477 # Whether conditions require booleans WHERE x = 0 vs WHERE x 478 ENSURE_BOOLS = False 479 480 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 481 CTE_RECURSIVE_KEYWORD_REQUIRED = True 482 483 # Whether CONCAT requires >1 arguments 484 SUPPORTS_SINGLE_ARG_CONCAT = True 485 486 # Whether LAST_DAY function supports a date part argument 487 LAST_DAY_SUPPORTS_DATE_PART = True 488 489 # Whether named columns are allowed in table aliases 490 SUPPORTS_TABLE_ALIAS_COLUMNS = True 491 492 # Whether named columns are allowed in CTE definitions 493 SUPPORTS_NAMED_CTE_COLUMNS = True 494 495 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 496 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 497 498 # Whether a (UN)PIVOT's alias is introduced with AS (Oracle rejects it, ORA-03048) 499 PIVOT_ALIAS_WITH_AS = True 500 501 # What delimiter to use for separating JSON key/value pairs 502 JSON_KEY_VALUE_PAIR_SEP = ":" 503 504 # INSERT OVERWRITE TABLE x override 505 INSERT_OVERWRITE = " OVERWRITE TABLE" 506 507 # Whether the SELECT .. INTO syntax is used instead of CTAS 508 SUPPORTS_SELECT_INTO = False 509 510 SUPPORTS_OPTIMIZE = False 511 SUPPORTS_EXECUTE_IMMEDIATE = True 512 513 # Whether UNLOGGED tables can be created 514 SUPPORTS_UNLOGGED_TABLES = False 515 516 # Whether the CREATE TABLE LIKE statement is supported 517 SUPPORTS_CREATE_TABLE_LIKE = True 518 519 # Whether ALTER TABLE ... MODIFY COLUMN column-redefinition syntax is supported 520 SUPPORTS_MODIFY_COLUMN = False 521 522 # Whether ALTER TABLE ... CHANGE COLUMN column-rename-and-redefine syntax is supported 523 SUPPORTS_CHANGE_COLUMN = False 524 525 # Whether ALTER COLUMN can set a column's nullability together with its type 526 SUPPORTS_ALTER_COLUMN_NULLABILITY = False 527 528 # Whether ALTER COLUMN IF EXISTS is supported 529 SUPPORTS_ALTER_COLUMN_IF_EXISTS = False 530 531 # Whether the LikeProperty needs to be specified inside of the schema clause 532 LIKE_PROPERTY_INSIDE_SCHEMA = False 533 534 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 535 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 536 MULTI_ARG_DISTINCT = True 537 538 # Whether the JSON extraction operators expect a value of type JSON 539 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 540 541 # Whether the .^ operator can select nested JSON objects 542 SUPPORTS_NESTED_JSON_SELECT = False 543 544 # Whether bracketed keys like ["foo"] are supported in JSON paths 545 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 546 547 # Whether to escape keys using single quotes in JSON paths 548 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 549 550 # Whether a quoted JSON path key (e.g. from a quoted identifier or ['key'] bracket) must be 551 # rendered in bracket form to preserve its case-sensitivity, even if it would otherwise match 552 # SAFE_JSON_PATH_KEY_RE and render as a bare dotted key. Needed for dialects like Databricks 553 # where a bare colon key is case-insensitive but a bracketed key is case-sensitive. 554 JSON_PATH_KEY_QUOTED_FORCES_BRACKETS = False 555 556 # The JSONPathPart expressions supported by this dialect 557 SUPPORTED_JSON_PATH_PARTS: t.ClassVar = ALL_JSON_PATH_PARTS.copy() 558 559 # Whether any(f(x) for x in array) can be implemented by this dialect 560 CAN_IMPLEMENT_ARRAY_ANY = False 561 562 # Whether the function TO_NUMBER is supported 563 SUPPORTS_TO_NUMBER = True 564 565 # Whether EXCLUDE in window specification is supported 566 SUPPORTS_WINDOW_EXCLUDE = False 567 568 # Whether or not set op modifiers apply to the outer set op or select. 569 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 570 # True means limit 1 happens after the set op, False means it it happens on y. 571 SET_OP_MODIFIERS = True 572 573 # Whether a SELECT operand can have a branch-local LIMIT/TOP without parentheses. 574 SET_OP_LIMITS = False 575 576 # Whether set operation operands can be parenthesized without a SELECT wrapper. 577 SET_OP_PARENTHESIZED_OPERANDS = True 578 579 # Whether parameters from COPY statement are wrapped in parentheses 580 COPY_PARAMS_ARE_WRAPPED = True 581 582 # Whether values of params are set with "=" token or empty space 583 COPY_PARAMS_EQ_REQUIRED = False 584 585 # Whether COPY statement has INTO keyword 586 COPY_HAS_INTO_KEYWORD = True 587 588 # Whether the conditional TRY(expression) function is supported 589 TRY_SUPPORTED = True 590 591 # Whether the UESCAPE syntax in unicode strings is supported 592 SUPPORTS_UESCAPE = True 593 594 # Function used to replace escaped unicode codes in unicode strings 595 UNICODE_SUBSTITUTE: t.ClassVar[t.Any] = None 596 597 # The keyword to use when generating a star projection with excluded columns 598 STAR_EXCEPT = "EXCEPT" 599 600 # The HEX function name 601 HEX_FUNC = "HEX" 602 603 # Function that constructs a binary value from a hex-encoded byte string. 604 BYTE_STRING_FUNCTION = "" 605 606 # The keywords to use when prefixing & separating WITH based properties 607 WITH_PROPERTIES_PREFIX = "WITH" 608 609 # Whether to quote the generated expression of exp.JsonPath 610 QUOTE_JSON_PATH = True 611 612 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 613 PAD_FILL_PATTERN_IS_REQUIRED = False 614 615 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 616 SUPPORTS_EXPLODING_PROJECTIONS = True 617 618 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 619 ARRAY_CONCAT_IS_VAR_LEN = True 620 621 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 622 SUPPORTS_CONVERT_TIMEZONE = False 623 624 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 625 SUPPORTS_MEDIAN = True 626 627 # Whether UNIX_SECONDS(timestamp) is supported 628 SUPPORTS_UNIX_SECONDS = False 629 630 # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>) 631 ALTER_SET_WRAPPED = False 632 633 # Whether to normalize the date parts in EXTRACT(<date_part> FROM <expr>) into a common representation 634 # using the dialect's general aliases as a fallback for parts without an EXTRACT-specific mapping. 635 # For instance, to extract the day of week in ISO semantics, one can use ISODOW, DAYOFWEEKISO etc depending on the dialect. 636 # TODO: The normalization should be done by default once we've tested it across all dialects. 637 NORMALIZE_EXTRACT_DATE_PARTS = False 638 639 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 640 PARSE_JSON_NAME: str | None = "PARSE_JSON" 641 642 # The function name of the exp.ArraySize expression 643 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 644 645 DAYOFWEEK_NAME = "" 646 DAYOFWEEK_ZERO_BASED = False 647 648 # Override for sample variance; otherwise use the expression's function name. 649 VARIANCE_NAME: str = "" 650 651 # Whether VARIANCE natively returns zero for a single non-NULL value. 652 VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE = False 653 654 # The syntax to use when altering the type of a column 655 ALTER_SET_TYPE = "SET DATA TYPE" 656 657 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 658 # None -> Doesn't support it at all 659 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 660 # True (Postgres) -> Explicitly requires it 661 ARRAY_SIZE_DIM_REQUIRED: bool | None = None 662 663 # Whether a multi-argument DECODE(...) function is supported. If not, a CASE expression is generated 664 SUPPORTS_DECODE_CASE = True 665 666 # Whether CHR / CHAR accepts multiple code points, e.g. CHAR(72, 105). If not, the calls are concatenated 667 SUPPORTS_MULTI_ARG_CHR = True 668 669 # Whether SYMMETRIC and ASYMMETRIC flags are supported with BETWEEN expression 670 SUPPORTS_BETWEEN_FLAGS = False 671 672 # Whether LIKE and ILIKE support quantifiers such as LIKE ANY/ALL/SOME 673 SUPPORTS_LIKE_QUANTIFIERS = True 674 675 # Prefix which is appended to exp.Table expressions in MATCH AGAINST 676 MATCH_AGAINST_TABLE_PREFIX: str | None = None 677 678 # Whether to include the VARIABLE keyword for SET assignments 679 SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD = False 680 681 # The keyword to use for default value assignment in DECLARE statements 682 DECLARE_DEFAULT_ASSIGNMENT = "=" 683 684 # Whether FROM is supported in UPDATE statements or if joins must be generated instead, e.g: 685 # Supported (Postgres, Doris etc): UPDATE t1 SET t1.a = t2.b FROM t2 686 # Unsupported (MySQL, SingleStore): UPDATE t1 JOIN t2 ON TRUE SET t1.a = t2.b 687 UPDATE_STATEMENT_SUPPORTS_FROM = True 688 689 # Whether SELECT *, ... EXCLUDE requires wrapping in a subquery for transpilation. 690 STAR_EXCLUDE_REQUIRES_DERIVED_TABLE = True 691 692 # Whether DROP and ALTER statements against Iceberg tables include 'ICEBERG', e.g.: 693 # - Snowflake: DROP ICEBERG TABLE a.b; 694 # - DuckDB: DROP TABLE a.b; 695 SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY = True 696 697 TYPE_MAPPING: t.ClassVar = { 698 exp.DType.DATETIME2: "TIMESTAMP", 699 exp.DType.NCHAR: "CHAR", 700 exp.DType.NVARCHAR: "VARCHAR", 701 exp.DType.MEDIUMTEXT: "TEXT", 702 exp.DType.LONGTEXT: "TEXT", 703 exp.DType.TINYTEXT: "TEXT", 704 exp.DType.BLOB: "VARBINARY", 705 exp.DType.MEDIUMBLOB: "BLOB", 706 exp.DType.LONGBLOB: "BLOB", 707 exp.DType.TINYBLOB: "BLOB", 708 exp.DType.INET: "INET", 709 exp.DType.ROWVERSION: "VARBINARY", 710 exp.DType.SMALLDATETIME: "TIMESTAMP", 711 } 712 713 UNSUPPORTED_TYPES: t.ClassVar[set[exp.DType]] = set() 714 715 # mapping of DType to its default parameters, bounds 716 TYPE_PARAM_SETTINGS: t.ClassVar[ 717 dict[exp.DType, tuple[tuple[int, ...], tuple[int | None, ...]]] 718 ] = {} 719 720 TIME_PART_SINGULARS: t.ClassVar = { 721 "MICROSECONDS": "MICROSECOND", 722 "SECONDS": "SECOND", 723 "MINUTES": "MINUTE", 724 "HOURS": "HOUR", 725 "DAYS": "DAY", 726 "WEEKS": "WEEK", 727 "MONTHS": "MONTH", 728 "QUARTERS": "QUARTER", 729 "YEARS": "YEAR", 730 } 731 732 AFTER_HAVING_MODIFIER_TRANSFORMS: t.ClassVar = { 733 "cluster": lambda self, e: self.sql(e, "cluster"), 734 "distribute": lambda self, e: self.sql(e, "distribute"), 735 "sort": lambda self, e: self.sql(e, "sort"), 736 **AFTER_HAVING_MODIFIER_TRANSFORMS, 737 } 738 739 TOKEN_MAPPING: t.ClassVar[dict[TokenType, str]] = {} 740 741 STRUCT_DELIMITER: t.ClassVar = ("<", ">") 742 743 PARAMETER_TOKEN = "@" 744 NAMED_PLACEHOLDER_TOKEN = ":" 745 746 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.ClassVar[set[str]] = set() 747 748 PROPERTIES_LOCATION: t.ClassVar = { 749 exp.AggregateKeyProperty: exp.Properties.Location.POST_SCHEMA, 750 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 751 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 752 exp.ApiProperty: exp.Properties.Location.POST_CREATE, 753 exp.ApplicationProperty: exp.Properties.Location.POST_CREATE, 754 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 755 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 756 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 757 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 758 exp.CalledOnNullInputProperty: exp.Properties.Location.POST_SCHEMA, 759 exp.CatalogProperty: exp.Properties.Location.POST_CREATE, 760 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 761 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 762 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 763 exp.ComputeProperty: exp.Properties.Location.POST_CREATE, 764 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 765 exp.CopyTagsProperty: exp.Properties.Location.POST_SCHEMA, 766 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 767 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 768 exp.ClusterProperty: exp.Properties.Location.POST_SCHEMA, 769 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 770 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 771 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 772 exp.DatabaseProperty: exp.Properties.Location.POST_CREATE, 773 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 774 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 775 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 776 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 777 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 778 exp.DistKeyProperty: exp.Properties.Location.UNSUPPORTED, 779 exp.DistStyleProperty: exp.Properties.Location.UNSUPPORTED, 780 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 781 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 782 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 783 exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA, 784 exp.HandlerProperty: exp.Properties.Location.POST_SCHEMA, 785 exp.ParameterStyleProperty: exp.Properties.Location.POST_SCHEMA, 786 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 787 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 788 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 789 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 790 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 791 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 792 exp.HeapProperty: exp.Properties.Location.POST_WITH, 793 exp.HybridProperty: exp.Properties.Location.POST_CREATE, 794 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 795 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 796 exp.IgnoreGrantsProperty: exp.Properties.Location.POST_SCHEMA, 797 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 798 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 799 exp.InteractiveProperty: exp.Properties.Location.UNSUPPORTED, 800 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 801 exp.JournalProperty: exp.Properties.Location.POST_NAME, 802 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 803 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 804 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 805 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 806 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 807 exp.LogProperty: exp.Properties.Location.POST_NAME, 808 exp.MaskingProperty: exp.Properties.Location.POST_CREATE, 809 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 810 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 811 exp.ModuleProperty: exp.Properties.Location.POST_SCHEMA, 812 exp.NetworkProperty: exp.Properties.Location.POST_CREATE, 813 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 814 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 815 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 816 exp.OptionsProperty: exp.Properties.Location.UNSUPPORTED, 817 exp.Order: exp.Properties.Location.POST_SCHEMA, 818 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 819 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 820 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 821 exp.PhysicalProperty: exp.Properties.Location.UNSUPPORTED, 822 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 823 exp.Property: exp.Properties.Location.POST_WITH, 824 exp.RefreshTriggerProperty: exp.Properties.Location.POST_SCHEMA, 825 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 826 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 827 exp.RollupProperty: exp.Properties.Location.UNSUPPORTED, 828 exp.RowAccessProperty: exp.Properties.Location.UNSUPPORTED, 829 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 830 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 831 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 832 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 833 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 834 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 835 exp.SecurityIntegrationProperty: exp.Properties.Location.POST_CREATE, 836 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 837 exp.Set: exp.Properties.Location.POST_SCHEMA, 838 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 839 exp.SetProperty: exp.Properties.Location.POST_CREATE, 840 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 841 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 842 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 843 exp.TriggerProperties: exp.Properties.Location.POST_EXPRESSION, 844 exp.SortKeyProperty: exp.Properties.Location.UNSUPPORTED, 845 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 846 exp.SqlSecurityProperty: exp.Properties.Location.POST_SCHEMA, 847 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 848 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 849 exp.StorageProperty: exp.Properties.Location.UNSUPPORTED, 850 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 851 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 852 exp.Tags: exp.Properties.Location.POST_WITH, 853 exp.TableSpaceProperty: exp.Properties.Location.UNSUPPORTED, 854 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 855 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 856 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 857 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 858 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 859 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 860 exp.UsingProperty: exp.Properties.Location.POST_EXPRESSION, 861 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 862 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 863 exp.VirtualProperty: exp.Properties.Location.POST_CREATE, 864 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 865 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 866 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 867 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 868 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 869 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 870 exp.WithoutRowidProperty: exp.Properties.Location.UNSUPPORTED, 871 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 872 } 873 874 # Keywords that can't be used as unquoted identifier names 875 RESERVED_KEYWORDS: t.ClassVar[set[str]] = set() 876 877 # Exprs whose comments are separated from them for better formatting 878 WITH_SEPARATED_COMMENTS: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 879 exp.Command, 880 exp.Create, 881 exp.Describe, 882 exp.Delete, 883 exp.Drop, 884 exp.From, 885 exp.Insert, 886 exp.Join, 887 exp.MultitableInserts, 888 exp.Order, 889 exp.Group, 890 exp.Having, 891 exp.Select, 892 exp.SetOperation, 893 exp.Update, 894 exp.Where, 895 exp.With, 896 ) 897 898 # Exprs that should not have their comments generated in maybe_comment 899 EXCLUDE_COMMENTS: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 900 exp.Binary, 901 exp.SetOperation, 902 ) 903 904 # Exprs that can remain unwrapped when appearing in the context of an INTERVAL 905 UNWRAPPED_INTERVAL_VALUES: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 906 exp.Column, 907 exp.Literal, 908 exp.Neg, 909 exp.Paren, 910 ) 911 912 PARAMETERIZABLE_TEXT_TYPES: t.ClassVar = { 913 exp.DType.NVARCHAR, 914 exp.DType.VARCHAR, 915 exp.DType.CHAR, 916 exp.DType.NCHAR, 917 } 918 919 # Exprs that need to have all CTEs under them bubbled up to them 920 EXPRESSIONS_WITHOUT_NESTED_CTES: t.ClassVar[set[type[exp.Expr]]] = set() 921 922 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = () 923 924 MOD_OPERATOR = "%" 925 926 # Unqualified operators that can be written without OPERATOR(...). 927 BARE_OPERATORS: t.ClassVar[set[str]] = set() 928 929 # Infix operators that bind at least as tightly as %, so a Mod on their right side needs parentheses 930 MOD_PAREN_PARENT_TYPES: t.ClassVar[tuple[type[exp.Expr], ...]] = ( 931 exp.Mul, 932 exp.Div, 933 exp.IntDiv, 934 exp.Mod, 935 ) 936 937 # ALTER options that follow the others without a comma, e.g. MySQL's 938 # ENGINE=InnoDB PARTITION BY LIST (...) or StarRocks' PARTITION BY ... DISTRIBUTED BY ... 939 ALTER_PARTITION_OPTIONS: t.ClassVar[tuple[type[exp.Expr], ...]] = () 940 941 SAFE_JSON_PATH_KEY_RE: t.ClassVar = exp.SAFE_IDENTIFIER_RE 942 943 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 944 945 __slots__ = ( 946 "pretty", 947 "identify", 948 "normalize", 949 "pad", 950 "_indent", 951 "normalize_functions", 952 "unsupported_level", 953 "max_unsupported", 954 "leading_comma", 955 "max_text_width", 956 "comments", 957 "dialect", 958 "unsupported_messages", 959 "_escaped_quote_end", 960 "_escaped_byte_quote_end", 961 "_escaped_identifier_end", 962 "_identifier_escaped_sequences", 963 "_next_name", 964 "_identifier_start", 965 "_identifier_end", 966 "_quote_json_path_key_using_brackets", 967 "_dispatch", 968 ) 969 970 def __init__( 971 self, 972 pretty: bool | int | None = None, 973 identify: str | bool = False, 974 normalize: bool = False, 975 pad: int = 2, 976 indent: int = 2, 977 normalize_functions: str | bool | None = None, 978 unsupported_level: ErrorLevel = ErrorLevel.WARN, 979 max_unsupported: int = 3, 980 leading_comma: bool = False, 981 max_text_width: int = 80, 982 comments: bool = True, 983 dialect: DialectType = None, 984 ): 985 import sqlglot 986 import sqlglot.dialects.dialect 987 988 self.pretty = pretty if pretty is not None else sqlglot.pretty 989 self.identify = identify 990 self.normalize = normalize 991 self.pad = pad 992 self._indent = indent 993 self.unsupported_level = unsupported_level 994 self.max_unsupported = max_unsupported 995 self.leading_comma = leading_comma 996 self.max_text_width = max_text_width 997 self.comments = comments 998 self.dialect = sqlglot.dialects.dialect.Dialect.get_or_raise(dialect) 999 1000 # This is both a Dialect property and a Generator argument, so we prioritize the latter 1001 self.normalize_functions = ( 1002 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 1003 ) 1004 1005 self.unsupported_messages: list[str] = [] 1006 self._escaped_quote_end: str = ( 1007 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 1008 ) 1009 self._escaped_byte_quote_end: str = ( 1010 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.BYTE_END 1011 if self.dialect.BYTE_END 1012 else "" 1013 ) 1014 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 1015 self._identifier_escaped_sequences = self.dialect.IDENTIFIER_ESCAPED_SEQUENCES 1016 1017 self._next_name = name_sequence("_t") 1018 1019 self._identifier_start = self.dialect.IDENTIFIER_START 1020 self._identifier_end = self.dialect.IDENTIFIER_END 1021 1022 self._quote_json_path_key_using_brackets = True 1023 1024 cls = type(self) 1025 dispatch = _DISPATCH_CACHE.get(cls) 1026 if dispatch is None: 1027 dispatch = _build_dispatch(cls) 1028 _DISPATCH_CACHE[cls] = dispatch 1029 self._dispatch = dispatch 1030 1031 def generate(self, expression: exp.Expr, copy: bool = True) -> str: 1032 """ 1033 Generates the SQL string corresponding to the given syntax tree. 1034 1035 Args: 1036 expression: The syntax tree. 1037 copy: Whether to copy the expression. The generator performs mutations so 1038 it is safer to copy. 1039 1040 Returns: 1041 The SQL string corresponding to `expression`. 1042 """ 1043 if copy: 1044 expression = expression.copy() 1045 1046 expression = self.preprocess(expression) 1047 1048 self.unsupported_messages = [] 1049 sql = self.sql(expression) 1050 # A trailing newline in a raw command can terminate a line comment. 1051 sql = sql.lstrip() if isinstance(expression, exp.Command) else sql.strip() 1052 1053 if self.pretty: 1054 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 1055 1056 if self.unsupported_level == ErrorLevel.IGNORE: 1057 return sql 1058 1059 if self.unsupported_level == ErrorLevel.WARN: 1060 for msg in self.unsupported_messages: 1061 logger.warning(msg) 1062 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 1063 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 1064 1065 return sql 1066 1067 def preprocess(self, expression: exp.Expr) -> exp.Expr: 1068 """Apply generic preprocessing transformations to a given expression.""" 1069 expression = self._move_ctes_to_top_level(expression) 1070 1071 if self.ENSURE_BOOLS: 1072 import sqlglot.transforms 1073 1074 expression = sqlglot.transforms.ensure_bools(expression) 1075 1076 return expression 1077 1078 def _move_ctes_to_top_level(self, expression: E) -> E: 1079 if ( 1080 not expression.parent 1081 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 1082 and any(node.parent is not expression for node in expression.find_all(exp.With)) 1083 ): 1084 import sqlglot.transforms 1085 1086 expression = sqlglot.transforms.move_ctes_to_top_level(expression) 1087 return expression 1088 1089 def _warn_unsupported_arg( 1090 self, expression: exp.Expr, arg_name: str, diagnostic: str | None = None 1091 ) -> None: 1092 if expression.args.get(arg_name): 1093 self.unsupported( 1094 diagnostic 1095 or UNSUPPORTED_TEMPLATE.format( 1096 arg_name, expression.__class__.__name__, self.dialect.__class__.__name__ 1097 ) 1098 ) 1099 1100 def unsupported(self, message: str) -> None: 1101 if self.unsupported_level == ErrorLevel.IMMEDIATE: 1102 raise UnsupportedError(message) 1103 self.unsupported_messages.append(message) 1104 1105 def sep(self, sep: str = " ") -> str: 1106 return f"{sep.strip()}\n" if self.pretty else sep 1107 1108 def seg(self, sql: str, sep: str = " ") -> str: 1109 return f"{self.sep(sep)}{sql}" 1110 1111 def sanitize_comment(self, comment: str) -> str: 1112 comment = " " + comment if comment[0].strip() else comment 1113 comment = comment + " " if comment[-1].strip() else comment 1114 1115 # Escape block comment markers to prevent premature closure or unintended nesting. 1116 # This is necessary because single-line comments (--) are converted to block comments 1117 # (/* */) on output, and any */ in the original text would close the comment early. 1118 comment = comment.replace("*/", "* /").replace("/*", "/ *") 1119 1120 return comment 1121 1122 def maybe_comment( 1123 self, 1124 sql: str, 1125 expression: exp.Expr | None = None, 1126 comments: list[str] | None = None, 1127 separated: bool = False, 1128 ) -> str: 1129 comments = ( 1130 ((expression and expression.comments) if comments is None else comments) # type: ignore 1131 if self.comments 1132 else None 1133 ) 1134 1135 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 1136 return sql 1137 1138 comments_list = [ 1139 f"/*{self._replace_line_breaks(self.sanitize_comment(comment))}*/" 1140 for comment in comments 1141 if comment 1142 ] 1143 1144 if not comments_list: 1145 return sql 1146 1147 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 1148 comments_sql = self.sep().join(comments_list) 1149 return ( 1150 f"{self.sep()}{comments_sql}{sql}" 1151 if not sql or sql[0].isspace() 1152 else f"{comments_sql}{self.sep()}{sql}" 1153 ) 1154 1155 return f"{sql} {' '.join(comments_list)}" 1156 1157 def wrap(self, expression: exp.Expr | str) -> str: 1158 this_sql = ( 1159 self.sql(expression) 1160 if isinstance(expression, exp.UNWRAPPED_QUERIES) 1161 else self.sql(expression, "this") 1162 ) 1163 if not this_sql: 1164 return "()" 1165 1166 this_sql = self.indent(this_sql, level=1, pad=0) 1167 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 1168 1169 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 1170 original = self.identify 1171 self.identify = False 1172 result = func(*args, **kwargs) 1173 self.identify = original 1174 return result 1175 1176 def normalize_func(self, name: str) -> str: 1177 if self.normalize_functions == "upper" or self.normalize_functions is True: 1178 return name.upper() 1179 if self.normalize_functions == "lower": 1180 return name.lower() 1181 return name 1182 1183 def indent( 1184 self, 1185 sql: str, 1186 level: int = 0, 1187 pad: int | None = None, 1188 skip_first: bool = False, 1189 skip_last: bool = False, 1190 ) -> str: 1191 if not self.pretty or not sql: 1192 return sql 1193 1194 pad = self.pad if pad is None else pad 1195 lines = sql.split("\n") 1196 1197 return "\n".join( 1198 ( 1199 line 1200 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 1201 else f"{' ' * (level * self._indent + pad)}{line}" 1202 ) 1203 for i, line in enumerate(lines) 1204 ) 1205 1206 def sql( 1207 self, 1208 expression: str | exp.Expr | None, 1209 key: str | None = None, 1210 comment: bool = True, 1211 ) -> str: 1212 if not expression: 1213 return "" 1214 1215 if isinstance(expression, str): 1216 return expression 1217 1218 if key: 1219 value = expression.args.get(key) 1220 if value: 1221 return self.sql(value) 1222 return "" 1223 1224 handler = self._dispatch.get(expression.__class__) 1225 1226 if handler: 1227 sql = handler(self, expression) 1228 elif isinstance(expression, exp.Func): 1229 sql = self.function_fallback_sql(expression) 1230 elif isinstance(expression, exp.Property): 1231 sql = self.property_sql(expression) 1232 else: 1233 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 1234 1235 return self.maybe_comment(sql, expression) if self.comments and comment else sql 1236 1237 def uncache_sql(self, expression: exp.Uncache) -> str: 1238 table = self.sql(expression, "this") 1239 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 1240 return f"UNCACHE TABLE{exists_sql} {table}" 1241 1242 def cache_sql(self, expression: exp.Cache) -> str: 1243 lazy = " LAZY" if expression.args.get("lazy") else "" 1244 table = self.sql(expression, "this") 1245 options = expression.args.get("options") 1246 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 1247 sql = self.sql(expression, "expression") 1248 sql = f" AS{self.sep()}{sql}" if sql else "" 1249 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 1250 return self.prepend_ctes(expression, sql) 1251 1252 def characterset_sql(self, expression: exp.CharacterSet) -> str: 1253 default = "DEFAULT " if expression.args.get("default") else "" 1254 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 1255 1256 def column_parts(self, expression: exp.Column) -> str: 1257 if expression.args.get("shadow") and self.dialect.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES: 1258 # The qualifier would be captured by a colliding projection alias (see qualify_columns) 1259 return self.sql(expression, "this") 1260 1261 return ".".join( 1262 self.sql(part) 1263 for part in ( 1264 expression.args.get("catalog"), 1265 expression.args.get("db"), 1266 expression.args.get("table"), 1267 expression.args.get("this"), 1268 ) 1269 if part 1270 ) 1271 1272 def column_sql(self, expression: exp.Column) -> str: 1273 join_mark = " (+)" if expression.args.get("join_mark") else "" 1274 1275 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 1276 join_mark = "" 1277 self.unsupported("Outer join syntax using the (+) operator is not supported.") 1278 1279 return f"{self.column_parts(expression)}{join_mark}" 1280 1281 def pseudocolumn_sql(self, expression: exp.Pseudocolumn) -> str: 1282 return self.column_sql(expression) 1283 1284 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 1285 this = self.sql(expression, "this") 1286 this = f" {this}" if this else "" 1287 position = self.sql(expression, "position") 1288 return f"{position}{this}" 1289 1290 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 1291 column = self.sql(expression, "this") 1292 kind = self.sql(expression, "kind") 1293 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 1294 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 1295 kind = f"{sep}{kind}" if kind else "" 1296 constraints = f" {constraints}" if constraints else "" 1297 position = self.sql(expression, "position") 1298 position = f" {position}" if position else "" 1299 1300 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1301 kind = "" 1302 1303 return f"{exists}{column}{kind}{constraints}{position}" 1304 1305 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 1306 this = self.sql(expression, "this") 1307 kind_sql = self.sql(expression, "kind").strip() 1308 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 1309 1310 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1311 this = self.sql(expression, "this") 1312 if expression.args.get("not_null"): 1313 persisted = " PERSISTED NOT NULL" 1314 elif expression.args.get("persisted"): 1315 persisted = " PERSISTED" 1316 else: 1317 persisted = "" 1318 1319 return f"AS {this}{persisted}" 1320 1321 def autoincrementcolumnconstraint_sql(self, _: exp.AutoIncrementColumnConstraint) -> str: 1322 return self.token_sql(TokenType.AUTO_INCREMENT) 1323 1324 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1325 if isinstance(expression.this, list): 1326 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1327 else: 1328 this = self.sql(expression, "this") 1329 1330 return f"COMPRESS {this}" 1331 1332 def generatedasidentitycolumnconstraint_sql( 1333 self, expression: exp.GeneratedAsIdentityColumnConstraint 1334 ) -> str: 1335 this = "" 1336 if expression.this is not None: 1337 on_null = " ON NULL" if expression.args.get("on_null") else "" 1338 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1339 1340 start = expression.args.get("start") 1341 start = f"START WITH {start}" if start else "" 1342 increment = expression.args.get("increment") 1343 increment = f" INCREMENT BY {increment}" if increment else "" 1344 minvalue = expression.args.get("minvalue") 1345 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1346 maxvalue = expression.args.get("maxvalue") 1347 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1348 cycle = expression.args.get("cycle") 1349 cycle_sql = "" 1350 1351 if cycle is not None: 1352 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1353 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1354 1355 sequence_opts = "" 1356 if start or increment or cycle_sql: 1357 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1358 sequence_opts = f" ({sequence_opts.strip()})" 1359 1360 expr = self.sql(expression, "expression") 1361 expr = f"({expr})" if expr else "IDENTITY" 1362 1363 return f"GENERATED{this} AS {expr}{sequence_opts}" 1364 1365 def generatedasrowcolumnconstraint_sql( 1366 self, expression: exp.GeneratedAsRowColumnConstraint 1367 ) -> str: 1368 start = "START" if expression.args.get("start") else "END" 1369 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1370 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1371 1372 def periodforsystemtimeconstraint_sql( 1373 self, expression: exp.PeriodForSystemTimeConstraint 1374 ) -> str: 1375 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1376 1377 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1378 on_conflict = self.sql(expression, "on_conflict") 1379 on_conflict = f" {on_conflict}" if on_conflict else "" 1380 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL{on_conflict}" 1381 1382 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1383 on_conflict = self.sql(expression, "on_conflict") 1384 on_conflict = f" {on_conflict}" if on_conflict else "" 1385 desc = expression.args.get("desc") 1386 if desc is not None: 1387 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}{on_conflict}" 1388 options = self.expressions(expression, key="options", flat=True, sep=" ") 1389 options = f" {options}" if options else "" 1390 include = self.sql(expression, "include") 1391 return f"PRIMARY KEY{on_conflict}{include}{options}" 1392 1393 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1394 this = self.sql(expression, "this") 1395 this = f" {this}" if this else "" 1396 index_type = expression.args.get("index_type") 1397 index_type = f" USING {index_type}" if index_type else "" 1398 on_conflict = self.sql(expression, "on_conflict") 1399 on_conflict = f" {on_conflict}" if on_conflict else "" 1400 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1401 options = self.expressions(expression, key="options", flat=True, sep=" ") 1402 options = f" {options}" if options else "" 1403 include = self.sql(expression, "include") 1404 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{include}{options}" 1405 1406 def inoutcolumnconstraint_sql(self, expression: exp.InOutColumnConstraint) -> str: 1407 input_ = expression.args.get("input_") 1408 output = expression.args.get("output") 1409 variadic = expression.args.get("variadic") 1410 1411 # VARIADIC is mutually exclusive with IN/OUT/INOUT 1412 if variadic: 1413 return "VARIADIC" 1414 1415 if input_ and output: 1416 return f"IN{self.INOUT_SEPARATOR}OUT" 1417 if input_: 1418 return "IN" 1419 if output: 1420 return "OUT" 1421 1422 return "" 1423 1424 def createable_sql(self, expression: exp.Create, locations: defaultdict) -> str: 1425 return self.sql(expression, "this") 1426 1427 def create_sql(self, expression: exp.Create) -> str: 1428 kind = self.sql(expression, "kind") 1429 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1430 1431 properties = expression.args.get("properties") 1432 1433 if ( 1434 kind == "TRIGGER" 1435 and properties 1436 and properties.expressions 1437 and isinstance(properties.expressions[0], exp.TriggerProperties) 1438 and properties.expressions[0].args.get("constraint") 1439 ): 1440 kind = f"CONSTRAINT {kind}" 1441 1442 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1443 1444 this = self.createable_sql(expression, properties_locs) 1445 1446 properties_sql = "" 1447 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1448 exp.Properties.Location.POST_WITH 1449 ): 1450 props_ast = exp.Properties( 1451 expressions=[ 1452 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1453 *properties_locs[exp.Properties.Location.POST_WITH], 1454 ] 1455 ) 1456 props_ast.parent = expression 1457 properties_sql = self.sql(props_ast) 1458 1459 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1460 properties_sql = self.sep() + properties_sql 1461 elif not self.pretty: 1462 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1463 properties_sql = f" {properties_sql}" 1464 1465 begin = " BEGIN" if expression.args.get("begin") else "" 1466 1467 expression_sql = self.sql(expression, "expression") 1468 if expression_sql: 1469 expression_sql = f"{begin}{self.sep()}{expression_sql}" 1470 1471 if not isinstance(expression.expression, exp.MacroOverloads) and ( 1472 self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return) 1473 ): 1474 postalias_props_sql = "" 1475 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1476 postalias_props_sql = self.properties( 1477 exp.Properties( 1478 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1479 ), 1480 wrapped=False, 1481 ) 1482 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1483 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1484 1485 postindex_props_sql = "" 1486 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1487 postindex_props_sql = self.properties( 1488 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1489 wrapped=False, 1490 prefix=" ", 1491 ) 1492 1493 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1494 indexes = f" {indexes}" if indexes else "" 1495 index_sql = indexes + postindex_props_sql 1496 1497 replace = " OR REPLACE" if expression.args.get("replace") else "" 1498 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1499 unique = " UNIQUE" if expression.args.get("unique") else "" 1500 1501 clustered = expression.args.get("clustered") 1502 if clustered is None: 1503 clustered_sql = "" 1504 elif clustered: 1505 clustered_sql = " CLUSTERED COLUMNSTORE" 1506 else: 1507 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1508 1509 postcreate_props_sql = "" 1510 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1511 postcreate_props_sql = self.properties( 1512 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1513 sep=" ", 1514 prefix=" ", 1515 wrapped=False, 1516 ) 1517 1518 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1519 1520 postexpression_props_sql = "" 1521 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1522 postexpression_props_sql = self.properties( 1523 exp.Properties( 1524 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1525 ), 1526 sep=" ", 1527 prefix=" ", 1528 wrapped=False, 1529 ) 1530 1531 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1532 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1533 no_schema_binding = ( 1534 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1535 ) 1536 1537 clone = self.sql(expression, "clone") 1538 clone = f" {clone}" if clone else "" 1539 1540 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1541 properties_expression = f"{expression_sql}{properties_sql}" 1542 else: 1543 properties_expression = f"{properties_sql}{expression_sql}" 1544 1545 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1546 return self.prepend_ctes(expression, expression_sql) 1547 1548 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1549 start = self.sql(expression, "start") 1550 start = f"START WITH {start}" if start else "" 1551 increment = self.sql(expression, "increment") 1552 increment = f" INCREMENT BY {increment}" if increment else "" 1553 minvalue = self.sql(expression, "minvalue") 1554 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1555 maxvalue = self.sql(expression, "maxvalue") 1556 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1557 owned = self.sql(expression, "owned") 1558 owned = f" OWNED BY {owned}" if owned else "" 1559 1560 cache = expression.args.get("cache") 1561 if cache is None: 1562 cache_str = "" 1563 elif cache is True: 1564 cache_str = " CACHE" 1565 else: 1566 cache_str = f" CACHE {cache}" 1567 1568 options = self.expressions(expression, key="options", flat=True, sep=" ") 1569 options = f" {options}" if options else "" 1570 1571 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1572 1573 def triggerproperties_sql(self, expression: exp.TriggerProperties) -> str: 1574 timing = expression.args.get("timing", "") 1575 events = " OR ".join(self.sql(event) for event in expression.args.get("events") or []) 1576 timing_events = f"{timing} {events}".strip() if timing or events else "" 1577 1578 parts = [timing_events, "ON", self.sql(expression, "table")] 1579 1580 if referenced_table := expression.args.get("referenced_table"): 1581 parts.extend(["FROM", self.sql(referenced_table)]) 1582 1583 if deferrable := expression.args.get("deferrable"): 1584 parts.append(deferrable) 1585 1586 if initially := expression.args.get("initially"): 1587 parts.append(f"INITIALLY {initially}") 1588 1589 if referencing := expression.args.get("referencing"): 1590 parts.append(self.sql(referencing)) 1591 1592 if for_each := expression.args.get("for_each"): 1593 parts.append(f"FOR EACH {for_each}") 1594 1595 if when := expression.args.get("when"): 1596 parts.append(f"WHEN ({self.sql(when)})") 1597 1598 parts.append(self.sql(expression, "execute")) 1599 1600 return self.sep().join(parts) 1601 1602 def triggerreferencing_sql(self, expression: exp.TriggerReferencing) -> str: 1603 parts = [] 1604 1605 if old_alias := expression.args.get("old"): 1606 parts.append(f"OLD TABLE AS {self.sql(old_alias)}") 1607 1608 if new_alias := expression.args.get("new"): 1609 parts.append(f"NEW TABLE AS {self.sql(new_alias)}") 1610 1611 return f"REFERENCING {' '.join(parts)}" 1612 1613 def triggerevent_sql(self, expression: exp.TriggerEvent) -> str: 1614 columns = expression.args.get("columns") 1615 if columns: 1616 return f"{expression.this} OF {self.expressions(expression, key='columns', flat=True)}" 1617 1618 return self.sql(expression, "this") 1619 1620 def clone_sql(self, expression: exp.Clone) -> str: 1621 this = self.sql(expression, "this") 1622 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1623 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1624 return f"{shallow}{keyword} {this}" 1625 1626 def describe_sql(self, expression: exp.Describe) -> str: 1627 style = expression.args.get("style") 1628 style = f" {style}" if style else "" 1629 partition = self.sql(expression, "partition") 1630 partition = f" {partition}" if partition else "" 1631 format = self.sql(expression, "format") 1632 format = f" {format}" if format else "" 1633 as_json = " AS JSON" if expression.args.get("as_json") else "" 1634 1635 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}{as_json}" 1636 1637 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1638 tag = self.sql(expression, "tag") 1639 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1640 1641 def prepend_ctes(self, expression: exp.Expr, sql: str) -> str: 1642 with_ = self.sql(expression, "with_") 1643 if with_: 1644 sql = f"{with_}{self.sep()}{sql}" 1645 return sql 1646 1647 def with_sql(self, expression: exp.With) -> str: 1648 udfs = self.expressions(expression, key="udfs", flat=True) 1649 udfs = f"WITH {udfs}" if udfs else "" 1650 1651 sql = self.expressions(expression, flat=True) 1652 1653 recursive = ( 1654 "RECURSIVE " 1655 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1656 else "" 1657 ) 1658 search = self.sql(expression, "search") 1659 search = f" {search}" if search else "" 1660 cycle = self.sql(expression, "cycle") 1661 cycle = f" {cycle}" if cycle else "" 1662 1663 sql = f"WITH {recursive}{sql}{search}{cycle}" if sql else "" 1664 return f"{udfs} {sql}" if udfs and sql else f"{udfs}{sql}" 1665 1666 def cte_sql(self, expression: exp.CTE) -> str: 1667 alias = expression.args.get("alias") 1668 if alias: 1669 alias.add_comments(expression.pop_comments()) 1670 1671 alias_sql = self.sql(expression, "alias") 1672 1673 materialized = expression.args.get("materialized") 1674 if materialized is False: 1675 materialized = "NOT MATERIALIZED " 1676 elif materialized: 1677 materialized = "MATERIALIZED " 1678 1679 key_expressions = self.expressions(expression, key="key_expressions", flat=True) 1680 key_expressions = f" USING KEY ({key_expressions})" if key_expressions else "" 1681 1682 return f"{alias_sql}{key_expressions} AS {materialized or ''}{self.wrap(expression)}" 1683 1684 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1685 alias = self.sql(expression, "this") 1686 columns = self.expressions(expression, key="columns", flat=True) 1687 columns = f"({columns})" if columns else "" 1688 1689 if ( 1690 columns 1691 and not self.SUPPORTS_TABLE_ALIAS_COLUMNS 1692 and not (self.SUPPORTS_NAMED_CTE_COLUMNS and isinstance(expression.parent, exp.CTE)) 1693 ): 1694 columns = "" 1695 self.unsupported("Named columns are not supported in table alias.") 1696 1697 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1698 alias = self._next_name() 1699 1700 return f"{alias}{columns}" 1701 1702 def bitstring_sql(self, expression: exp.BitString) -> str: 1703 this = self.sql(expression, "this") 1704 if self.dialect.BIT_START: 1705 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1706 return f"{int(this, 2)}" 1707 1708 def hexstring_sql( 1709 self, expression: exp.HexString, binary_function_repr: str | None = None 1710 ) -> str: 1711 if expression.args.get("is_character"): 1712 self.unsupported("Hexadecimal character literals are only supported in Teradata") 1713 this = expression.this.replace("'", "''") 1714 return f"'{this}'XC" 1715 1716 this = self.sql(expression, "this") 1717 is_integer_type = expression.args.get("is_integer") 1718 1719 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1720 not self.dialect.HEX_START and not binary_function_repr 1721 ): 1722 # Integer representation will be returned if: 1723 # - The read dialect treats the hex value as integer literal but not the write 1724 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1725 return f"{int(this, 16)}" 1726 1727 if not is_integer_type: 1728 # Read dialect treats the hex value as BINARY/BLOB 1729 if binary_function_repr: 1730 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1731 return self.func(binary_function_repr, exp.Literal.string(this)) 1732 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1733 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1734 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1735 1736 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1737 1738 def bytestring_sql(self, expression: exp.ByteString) -> str: 1739 this = self.sql(expression, "this") 1740 is_bytes = bool(expression.args.get("is_bytes")) 1741 if is_bytes and self.BYTE_STRING_FUNCTION: 1742 # Hex digits can be quoted directly without escaping. 1743 return self.func(self.BYTE_STRING_FUNCTION, f"'{this.encode('latin-1').hex()}'") 1744 1745 if self.dialect.BYTE_START: 1746 escaped_byte_string = self.escape_str( 1747 this, 1748 escape_backslash=bool( 1749 self.dialect.tokenizer_class.NUMERIC_ESCAPES 1750 or self.dialect.tokenizer_class.DROP_UNKNOWN_ESCAPES 1751 ), 1752 delimiter=self.dialect.BYTE_END, 1753 escaped_delimiter=self._escaped_byte_quote_end, 1754 is_byte_string=True, 1755 is_bytes=is_bytes, 1756 ) 1757 delimited_byte_string = ( 1758 f"{self.dialect.BYTE_START}{escaped_byte_string}{self.dialect.BYTE_END}" 1759 ) 1760 if is_bytes and not self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1761 return self.sql( 1762 exp.cast(delimited_byte_string, exp.DType.BINARY, dialect=self.dialect) 1763 ) 1764 if not is_bytes and self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1765 return self.sql( 1766 exp.cast(delimited_byte_string, exp.DType.VARCHAR, dialect=self.dialect) 1767 ) 1768 1769 return delimited_byte_string 1770 1771 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1772 return self.sql(exp.Literal.string(this)) 1773 1774 self.unsupported(f"Byte strings are not supported for {self.dialect.__class__.__name__}") 1775 return "" 1776 1777 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1778 this = self.sql(expression, "this") 1779 escape = expression.args.get("escape") 1780 unicode_start = self.dialect.UNICODE_START 1781 1782 if unicode_start: 1783 escape_substitute = r"\\\1" 1784 left_quote, right_quote = unicode_start, self.dialect.UNICODE_END or "" 1785 else: 1786 escape_substitute = r"\\u\1" 1787 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1788 1789 if escape: 1790 escape_pattern = re.compile(rf"{re.escape(escape.name)}(\d+)") 1791 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1792 else: 1793 escape_pattern = ESCAPED_UNICODE_RE 1794 escape_sql = "" 1795 1796 if not unicode_start or (escape and not self.SUPPORTS_UESCAPE): 1797 this = escape_pattern.sub(self.UNICODE_SUBSTITUTE or escape_substitute, this) 1798 1799 if unicode_start: 1800 # A Unicode literal only escapes its delimiter by doubling it; the escape character 1801 # introduces a code point, so the dialect's ordinary string escapes don't apply here 1802 this = self._replace_line_breaks(this).replace(right_quote, right_quote * 2) 1803 else: 1804 this = self.escape_str(this, escape_backslash=False) 1805 1806 return f"{left_quote}{this}{right_quote}{escape_sql}" 1807 1808 def rawstring_sql(self, expression: exp.RawString) -> str: 1809 string = expression.this 1810 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1811 string = string.replace("\\", "\\\\") 1812 1813 string = self.escape_str(string, escape_backslash=False) 1814 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1815 1816 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1817 this = self.sql(expression, "this") 1818 specifier = self.sql(expression, "expression") 1819 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1820 return f"{this}{specifier}" 1821 1822 def datatype_param_bound_limiter( 1823 self, 1824 expression: exp.DataType, 1825 type_value: exp.DType, 1826 defaults: tuple[int, ...], 1827 bounds: tuple[int | None, ...], 1828 ) -> exp.DataType: 1829 params = expression.expressions 1830 1831 if not params: 1832 if defaults: 1833 expression.set( 1834 "expressions", 1835 [exp.DataTypeParam(this=exp.Literal.number(d)) for d in defaults], 1836 ) 1837 return expression 1838 1839 if not bounds: 1840 return expression 1841 1842 for i, param in enumerate(params): 1843 bound = bounds[i] if i < len(bounds) else None 1844 if bound is None: 1845 continue 1846 1847 param_value = param.this if isinstance(param, exp.DataTypeParam) else param 1848 value = ( 1849 param_value.to_py() 1850 if isinstance(param_value, exp.Literal) and param_value.is_number 1851 else None 1852 ) 1853 if isinstance(value, (int, Decimal)) and value > bound: 1854 self.unsupported( 1855 f"{type_value.value} parameter {param_value.name} exceeds " 1856 f"{self.dialect.__class__.__name__}'s maximum of {bound}; capping" 1857 ) 1858 params[i] = exp.DataTypeParam(this=exp.Literal.number(bound)) 1859 1860 return expression 1861 1862 def datatype_sql(self, expression: exp.DataType) -> str: 1863 nested = "" 1864 values = "" 1865 1866 expr_nested = expression.args.get("nested") 1867 type_value = expression.this 1868 1869 if ( 1870 not expr_nested 1871 and isinstance(type_value, exp.DType) 1872 and (settings := self.TYPE_PARAM_SETTINGS.get(type_value)) 1873 ): 1874 expression = self.datatype_param_bound_limiter(expression, type_value, *settings) 1875 1876 interior = ( 1877 self.expressions( 1878 expression, dynamic=True, new_line=True, skip_first=True, skip_last=True 1879 ) 1880 if expr_nested and self.pretty 1881 else self.expressions(expression, flat=True) 1882 ) 1883 1884 if type_value in self.UNSUPPORTED_TYPES: 1885 self.unsupported( 1886 f"Data type {type_value.value} is not supported when targeting {self.dialect.__class__.__name__}" 1887 ) 1888 1889 type_sql: t.Any = "" 1890 if type_value == exp.DType.USERDEFINED and expression.args.get("kind"): 1891 type_sql = self.sql(expression, "kind") 1892 elif type_value == exp.DType.CHARACTER_SET: 1893 char = f"CHAR({interior})" if interior else "CHAR" 1894 return f"{char} CHARACTER SET {self.sql(expression, 'kind')}" 1895 else: 1896 type_sql = ( 1897 self.TYPE_MAPPING.get(type_value, type_value.value) 1898 if isinstance(type_value, exp.DType) 1899 else type_value 1900 ) 1901 1902 if interior: 1903 if expr_nested: 1904 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1905 if expression.args.get("values") is not None: 1906 delimiters = ("[", "]") if type_value == exp.DType.ARRAY else ("(", ")") 1907 values = self.expressions(expression, key="values", flat=True) 1908 values = f"{delimiters[0]}{values}{delimiters[1]}" 1909 elif type_value == exp.DType.INTERVAL: 1910 nested = f" {interior}" 1911 else: 1912 nested = f"({interior})" 1913 1914 type_sql = f"{type_sql}{nested}{values}" 1915 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1916 exp.DType.TIMETZ, 1917 exp.DType.TIMESTAMPTZ, 1918 ): 1919 type_sql = f"{type_sql} WITH TIME ZONE" 1920 1921 collate = self.sql(expression, "collate") 1922 if collate: 1923 type_sql = f"{type_sql} COLLATE {collate}" 1924 1925 return type_sql 1926 1927 def directory_sql(self, expression: exp.Directory) -> str: 1928 local = "LOCAL " if expression.args.get("local") else "" 1929 row_format = self.sql(expression, "row_format") 1930 row_format = f" {row_format}" if row_format else "" 1931 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1932 1933 def delete_sql(self, expression: exp.Delete) -> str: 1934 hint = self.sql(expression, "hint") 1935 this = self.sql(expression, "this") 1936 this = f" FROM {this}" if this else "" 1937 using = self.expressions(expression, key="using") 1938 using = f" USING {using}" if using else "" 1939 cluster = self.sql(expression, "cluster") 1940 cluster = f" {cluster}" if cluster else "" 1941 where = self.sql(expression, "where") 1942 returning = self.sql(expression, "returning") 1943 order = self.sql(expression, "order") 1944 limit = self.sql(expression, "limit") 1945 tables = self.expressions(expression, key="tables") 1946 tables = f" {tables}" if tables else "" 1947 if self.RETURNING_END: 1948 expression_sql = f"{this}{using}{cluster}{where}{returning}{order}{limit}" 1949 else: 1950 expression_sql = f"{returning}{this}{using}{cluster}{where}{order}{limit}" 1951 return self.prepend_ctes(expression, f"DELETE{hint}{tables}{expression_sql}") 1952 1953 def drop_sql(self, expression: exp.Drop) -> str: 1954 tables = self.expressions(expression, key="tables", flat=True) 1955 expressions = self.expressions(expression, flat=True) 1956 expressions = f" ({expressions})" if expressions else "" 1957 kind = expression.args["kind"] 1958 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1959 iceberg = ( 1960 " ICEBERG" 1961 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 1962 else "" 1963 ) 1964 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1965 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1966 on_cluster = self.sql(expression, "cluster") 1967 on_cluster = f" {on_cluster}" if on_cluster else "" 1968 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1969 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1970 cascade = " CASCADE" if expression.args.get("cascade") else "" 1971 restrict = " RESTRICT" if expression.args.get("restrict") else "" 1972 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1973 purge = " PURGE" if expression.args.get("purge") else "" 1974 sync = " SYNC" if expression.args.get("sync") else "" 1975 force = " FORCE" if expression.args.get("force") else "" 1976 return f"DROP{temporary}{materialized}{iceberg} {kind}{concurrently_sql}{exists_sql}{tables}{on_cluster}{expressions}{cascade}{restrict}{constraints}{purge}{sync}{force}" 1977 1978 def set_operation(self, expression: exp.SetOperation) -> str: 1979 op_type = type(expression) 1980 op_name = op_type.key.upper() 1981 1982 distinct = expression.args.get("distinct") 1983 if ( 1984 distinct is False 1985 and op_type in (exp.Except, exp.Intersect) 1986 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1987 ): 1988 self.unsupported(f"{op_name} ALL is not supported") 1989 1990 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1991 1992 if distinct is None: 1993 distinct = default_distinct 1994 if distinct is None: 1995 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1996 1997 if distinct is default_distinct: 1998 distinct_or_all = "" 1999 else: 2000 distinct_or_all = " DISTINCT" if distinct else " ALL" 2001 2002 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 2003 side_kind = f"{side_kind} " if side_kind else "" 2004 2005 by_name = " BY NAME" if expression.args.get("by_name") else "" 2006 on = self.expressions(expression, key="on", flat=True) 2007 on = f" ON ({on})" if on else "" 2008 2009 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}" 2010 2011 def set_operations(self, expression: exp.SetOperation) -> str: 2012 if not self.SET_OP_MODIFIERS: 2013 limit = expression.args.get("limit") 2014 order = expression.args.get("order") 2015 offset = expression.args.get("offset") 2016 2017 if limit or order or offset: 2018 select = self._move_ctes_to_top_level( 2019 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 2020 ) 2021 2022 for arg in ("limit", "order", "offset"): 2023 if value := expression.args.get(arg): 2024 select.set(arg, value.pop()) 2025 return self.sql(select) 2026 2027 sqls: list[str] = [] 2028 stack: list[str | exp.Expr | int | None] = [expression] 2029 depth = 0 2030 open_parens = "" 2031 2032 while stack: 2033 node = stack.pop() 2034 2035 if isinstance(node, int): 2036 # Closes a plain grouping opened below, restoring its depth 2037 depth = node 2038 sqls[-1] += self.sep("") + self.indent(")", level=depth, pad=0) 2039 elif isinstance(node, exp.SetOperation): 2040 stack.append(node.expression) 2041 stack.append( 2042 self.maybe_comment( 2043 self.set_operation(node), comments=node.comments, separated=True 2044 ) 2045 ) 2046 left = node.this 2047 if ( 2048 not self.SET_OP_PARENTHESIZED_OPERANDS 2049 and not self.dialect.INTERSECT_BINDS_TIGHTER_THAN_UNION_AND_EXCEPT 2050 ): 2051 # Left grouping is implicit, so skip the `SELECT * FROM (...)` wrapper: 2052 # it renames duplicate columns and deepens recursion. Inner CTEs and 2053 # modifiers still need the wrapper. 2054 wrappers: list[exp.Subquery] = [] 2055 inner = left 2056 while isinstance(inner, exp.Subquery) and inner.is_wrapper: 2057 wrappers.append(inner) 2058 inner = inner.this 2059 2060 if ( 2061 isinstance(inner, exp.SetOperation) 2062 and not inner.args.get("with_") 2063 and not any(inner.args.get(key) for key in exp.QUERY_MODIFIERS) 2064 ): 2065 for wrapper in wrappers: 2066 inner.add_comments(wrapper.pop_comments()) 2067 left = inner 2068 elif ( 2069 self.SET_OP_PARENTHESIZED_OPERANDS 2070 and isinstance(left, exp.Subquery) 2071 and left.is_wrapper 2072 and not left.comments 2073 and isinstance(left.this, exp.SetOperation) 2074 and not left.this.args.get("with_") 2075 and not any(left.this.args.get(key) for key in exp.QUERY_MODIFIERS) 2076 ): 2077 # Write a plain grouping's parentheses here rather than recursing through 2078 # subquery_sql: left-to-right chains nest one grouping per INTERSECT, and 2079 # long ones would exhaust the stack. The depth pushed here marks the close. 2080 open_parens += self.indent("(", level=depth, pad=0) + self.sep("") 2081 stack.append(depth) 2082 depth += 1 2083 left = left.this 2084 stack.append(left) 2085 else: 2086 if ( 2087 not self.SET_OP_LIMITS 2088 and isinstance(node, exp.Select) 2089 and node.args.get("limit") 2090 ): 2091 node = node.subquery(copy=False) 2092 if not self.SET_OP_PARENTHESIZED_OPERANDS and isinstance(node, exp.Subquery): 2093 node = exp.select("*").from_(node, copy=False) 2094 sqls.append(open_parens + self.indent(self.sql(node), level=depth, pad=0)) 2095 open_parens = "" 2096 2097 this = self.sep().join(sqls) 2098 this = self.query_modifiers(expression, this) 2099 return self.prepend_ctes(expression, this) 2100 2101 def fetch_sql(self, expression: exp.Fetch) -> str: 2102 direction = expression.args.get("direction") 2103 direction = f" {direction}" if direction else "" 2104 count = self.sql(expression, "count") 2105 count = f" {count}" if count else "" 2106 limit_options = self.sql(expression, "limit_options") 2107 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 2108 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 2109 2110 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 2111 percent = " PERCENT" if expression.args.get("percent") else "" 2112 rows = " ROWS" if expression.args.get("rows") else "" 2113 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 2114 if not with_ties and rows: 2115 with_ties = " ONLY" 2116 return f"{percent}{rows}{with_ties}" 2117 2118 def filter_sql(self, expression: exp.Filter) -> str: 2119 this = self.sql(expression, "this") 2120 where = self.sql(expression, "expression").strip() 2121 return f"{this} FILTER({where})" 2122 2123 def per_sql(self, expression: exp.Per) -> str: 2124 keys = ", ".join( 2125 f"{self.sql(key, 'this')} {self.sql(key, 'with_fill')}" 2126 if isinstance(key, exp.Ordered) and key.args.get("with_fill") 2127 else self.sql(key) 2128 for key in expression.expressions 2129 ) 2130 return f"{self.sql(expression, 'this')} PER ({keys})" 2131 2132 def hint_sql(self, expression: exp.Hint) -> str: 2133 if not self.QUERY_HINTS: 2134 self.unsupported("Hints are not supported") 2135 return "" 2136 2137 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 2138 2139 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 2140 using = self.sql(expression, "using") 2141 using = f" USING {using}" if using else "" 2142 columns = self.expressions(expression, key="columns", flat=True) 2143 columns = f"({columns})" if columns else "" 2144 partition_by = self.expressions(expression, key="partition_by", flat=True) 2145 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 2146 where = self.sql(expression, "where") 2147 include = self.expressions(expression, key="include", flat=True) 2148 if include: 2149 include = f" INCLUDE ({include})" 2150 with_storage = self.expressions(expression, key="with_storage", flat=True) 2151 with_storage = f" WITH ({with_storage})" if with_storage else "" 2152 tablespace = self.sql(expression, "tablespace") 2153 if tablespace: 2154 prefix = "" if isinstance(expression.parent, exp.Index) else " USING INDEX" 2155 tablespace = f"{prefix} TABLESPACE {tablespace}" 2156 on = self.sql(expression, "on") 2157 on = f" ON {on}" if on else "" 2158 2159 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 2160 2161 def index_sql(self, expression: exp.Index) -> str: 2162 unique = "UNIQUE " if expression.args.get("unique") else "" 2163 primary = "PRIMARY " if expression.args.get("primary") else "" 2164 amp = "AMP " if expression.args.get("amp") else "" 2165 name = self.sql(expression, "this") 2166 name = f"{name} " if name else "" 2167 table = self.sql(expression, "table") 2168 table = f"{self.INDEX_ON} {table}" if table else "" 2169 2170 index = "INDEX " if not table else "" 2171 2172 params = self.sql(expression, "params") 2173 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 2174 2175 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 2176 this = expression.this 2177 if this and this.is_string: 2178 resolved = maybe_parse(this.name).sql(self.dialect) 2179 if "expressions" in expression.args: 2180 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 2181 # We can't safely emit the call to other dialects since name/arg semantics may differ 2182 self.unsupported( 2183 "Transpiling dynamically-invoked IDENTIFIER() functions is unsupported" 2184 ) 2185 return resolved 2186 self.unsupported("IDENTIFIER() with non-literal arguments is not supported") 2187 return self.func("IDENTIFIER", this) 2188 2189 def identifier_sql(self, expression: exp.Identifier) -> str: 2190 text = expression.name 2191 lower = text.lower() 2192 quoted = expression.quoted 2193 text = lower if self.normalize and not quoted else text 2194 if self._identifier_escaped_sequences: 2195 for char, escaped in self._identifier_escaped_sequences.items(): 2196 text = text.replace(char, escaped) 2197 text = text.replace(self._identifier_end, self._escaped_identifier_end) 2198 if ( 2199 quoted 2200 or self.dialect.can_quote(expression, self.identify) 2201 or lower in self.RESERVED_KEYWORDS 2202 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 2203 ): 2204 text = ( 2205 f"{self._identifier_start}{self._replace_line_breaks(text)}{self._identifier_end}" 2206 ) 2207 return text 2208 2209 def hex_sql(self, expression: exp.Hex) -> str: 2210 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 2211 if self.dialect.HEX_LOWERCASE: 2212 text = self.func("LOWER", text) 2213 2214 return text 2215 2216 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 2217 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 2218 if not self.dialect.HEX_LOWERCASE: 2219 text = self.func("LOWER", text) 2220 return text 2221 2222 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 2223 input_format = self.sql(expression, "input_format") 2224 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 2225 output_format = self.sql(expression, "output_format") 2226 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 2227 return self.sep().join((input_format, output_format)) 2228 2229 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 2230 string = self.sql(exp.Literal.string(expression.name)) 2231 return f"{prefix}{string}" 2232 2233 def partition_sql(self, expression: exp.Partition) -> str: 2234 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 2235 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 2236 2237 def properties_sql(self, expression: exp.Properties) -> str: 2238 root_properties = [] 2239 with_properties = [] 2240 2241 for p in expression.expressions: 2242 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2243 if p_loc == exp.Properties.Location.POST_WITH: 2244 with_properties.append(p) 2245 elif p_loc == exp.Properties.Location.POST_SCHEMA: 2246 root_properties.append(p) 2247 2248 root_props_ast = exp.Properties(expressions=root_properties) 2249 root_props_ast.parent = expression.parent 2250 2251 with_props_ast = exp.Properties(expressions=with_properties) 2252 with_props_ast.parent = expression.parent 2253 2254 root_props = self.root_properties(root_props_ast) 2255 with_props = self.with_properties(with_props_ast) 2256 2257 if root_props and with_props and not self.pretty: 2258 with_props = " " + with_props 2259 2260 return root_props + with_props 2261 2262 def root_properties(self, properties: exp.Properties) -> str: 2263 if properties.expressions: 2264 return self.expressions(properties, indent=False, sep=" ") 2265 return "" 2266 2267 def properties( 2268 self, 2269 properties: exp.Properties, 2270 prefix: str = "", 2271 sep: str = ", ", 2272 suffix: str = "", 2273 wrapped: bool = True, 2274 ) -> str: 2275 if properties.expressions: 2276 expressions = self.expressions(properties, sep=sep, indent=False) 2277 if expressions: 2278 expressions = self.wrap(expressions) if wrapped else expressions 2279 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 2280 return "" 2281 2282 def with_properties(self, properties: exp.Properties) -> str: 2283 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 2284 2285 def locate_properties(self, properties: exp.Properties) -> defaultdict: 2286 properties_locs = defaultdict(list) 2287 for p in properties.expressions: 2288 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2289 if p_loc != exp.Properties.Location.UNSUPPORTED: 2290 properties_locs[p_loc].append(p) 2291 else: 2292 self.unsupported(f"Unsupported property {p.key}") 2293 2294 return properties_locs 2295 2296 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 2297 if isinstance(expression.this, exp.Dot): 2298 return self.sql(expression, "this") 2299 return self.sql(exp.Literal.string(expression.name)) if string_key else expression.name 2300 2301 def property_sql(self, expression: exp.Property) -> str: 2302 property_cls = expression.__class__ 2303 if property_cls == exp.Property: 2304 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 2305 2306 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 2307 if not property_name: 2308 self.unsupported(f"Unsupported property {expression.key}") 2309 return "" 2310 2311 return f"{property_name}={self.sql(expression, 'this')}" 2312 2313 def uuidproperty_sql(self, expression: exp.UuidProperty) -> str: 2314 return f"UUID {self.sql(expression, 'this')}" 2315 2316 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 2317 if self.SUPPORTS_CREATE_TABLE_LIKE: 2318 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 2319 options = f" {options}" if options else "" 2320 2321 like = f"LIKE {self.sql(expression, 'this')}{options}" 2322 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 2323 like = f"({like})" 2324 2325 return like 2326 2327 if expression.expressions: 2328 self.unsupported("Transpilation of LIKE property options is unsupported") 2329 2330 select = exp.select("*").from_(expression.this).limit(0) 2331 return f"AS {self.sql(select)}" 2332 2333 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 2334 no = "NO " if expression.args.get("no") else "" 2335 protection = " PROTECTION" if expression.args.get("protection") else "" 2336 return f"{no}FALLBACK{protection}" 2337 2338 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 2339 no = "NO " if expression.args.get("no") else "" 2340 local = expression.args.get("local") 2341 local = f"{local} " if local else "" 2342 dual = "DUAL " if expression.args.get("dual") else "" 2343 before = "BEFORE " if expression.args.get("before") else "" 2344 after = "AFTER " if expression.args.get("after") else "" 2345 return f"{no}{local}{dual}{before}{after}JOURNAL" 2346 2347 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 2348 freespace = self.sql(expression, "this") 2349 percent = " PERCENT" if expression.args.get("percent") else "" 2350 return f"FREESPACE={freespace}{percent}" 2351 2352 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 2353 if expression.args.get("default"): 2354 property = "DEFAULT" 2355 elif expression.args.get("on"): 2356 property = "ON" 2357 else: 2358 property = "OFF" 2359 return f"CHECKSUM={property}" 2360 2361 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 2362 if expression.args.get("no"): 2363 return "NO MERGEBLOCKRATIO" 2364 if expression.args.get("default"): 2365 return "DEFAULT MERGEBLOCKRATIO" 2366 2367 percent = " PERCENT" if expression.args.get("percent") else "" 2368 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 2369 2370 def moduleproperty_sql(self, expression: exp.ModuleProperty) -> str: 2371 expressions = self.expressions(expression, flat=True) 2372 expressions = f"({expressions})" if expressions else "" 2373 return f"USING {self.sql(expression, 'this')}{expressions}" 2374 2375 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 2376 default = expression.args.get("default") 2377 minimum = expression.args.get("minimum") 2378 maximum = expression.args.get("maximum") 2379 if default or minimum or maximum: 2380 if default: 2381 prop = "DEFAULT" 2382 elif minimum: 2383 prop = "MINIMUM" 2384 else: 2385 prop = "MAXIMUM" 2386 return f"{prop} DATABLOCKSIZE" 2387 units = expression.args.get("units") 2388 units = f" {units}" if units else "" 2389 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 2390 2391 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 2392 autotemp = expression.args.get("autotemp") 2393 always = expression.args.get("always") 2394 default = expression.args.get("default") 2395 manual = expression.args.get("manual") 2396 never = expression.args.get("never") 2397 2398 if autotemp is not None: 2399 prop = f"AUTOTEMP({self.expressions(autotemp)})" 2400 elif always: 2401 prop = "ALWAYS" 2402 elif default: 2403 prop = "DEFAULT" 2404 elif manual: 2405 prop = "MANUAL" 2406 elif never: 2407 prop = "NEVER" 2408 return f"BLOCKCOMPRESSION={prop}" 2409 2410 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 2411 no = expression.args.get("no") 2412 no = " NO" if no else "" 2413 concurrent = expression.args.get("concurrent") 2414 concurrent = " CONCURRENT" if concurrent else "" 2415 target = self.sql(expression, "target") 2416 target = f" {target}" if target else "" 2417 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 2418 2419 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 2420 if isinstance(expression.this, list): 2421 return f"IN ({self.expressions(expression, key='this', flat=True)})" 2422 if expression.this: 2423 modulus = self.sql(expression, "this") 2424 remainder = self.sql(expression, "expression") 2425 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 2426 2427 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 2428 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 2429 return f"FROM ({from_expressions}) TO ({to_expressions})" 2430 2431 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 2432 this = self.sql(expression, "this") 2433 2434 for_values_or_default = expression.expression 2435 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 2436 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 2437 else: 2438 for_values_or_default = " DEFAULT" 2439 2440 return f"PARTITION OF {this}{for_values_or_default}" 2441 2442 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 2443 kind = expression.args.get("kind") 2444 this = f" {self.sql(expression, 'this')}" if expression.this else "" 2445 for_or_in = expression.args.get("for_or_in") 2446 for_or_in = f" {for_or_in}" if for_or_in else "" 2447 lock_type = expression.args.get("lock_type") 2448 override = " OVERRIDE" if expression.args.get("override") else "" 2449 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 2450 2451 def lockingstatement_sql(self, expression: exp.LockingStatement) -> str: 2452 self.unsupported("LOCKING request modifier is not supported") 2453 return self.sql(expression, "expression") 2454 2455 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 2456 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 2457 statistics = expression.args.get("statistics") 2458 statistics_sql = "" 2459 if statistics is not None: 2460 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 2461 return f"{data_sql}{statistics_sql}" 2462 2463 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 2464 this = self.sql(expression, "this") 2465 this = f"HISTORY_TABLE={this}" if this else "" 2466 data_consistency: str | None = self.sql(expression, "data_consistency") 2467 data_consistency = ( 2468 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 2469 ) 2470 retention_period: str | None = self.sql(expression, "retention_period") 2471 retention_period = ( 2472 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 2473 ) 2474 2475 if this: 2476 on_sql = self.func("ON", this, data_consistency, retention_period) 2477 else: 2478 on_sql = "ON" if expression.args.get("on") else "OFF" 2479 2480 sql = f"SYSTEM_VERSIONING={on_sql}" 2481 2482 return f"WITH({sql})" if expression.args.get("with_") else sql 2483 2484 def insert_sql(self, expression: exp.Insert) -> str: 2485 hint = self.sql(expression, "hint") 2486 overwrite = expression.args.get("overwrite") 2487 2488 if isinstance(expression.this, exp.Directory): 2489 this = " OVERWRITE" if overwrite else " INTO" 2490 else: 2491 this = self.INSERT_OVERWRITE if overwrite else " INTO" 2492 2493 stored = self.sql(expression, "stored") 2494 stored = f" {stored}" if stored else "" 2495 alternative = expression.args.get("alternative") 2496 alternative = f" OR {alternative}" if alternative else "" 2497 ignore = " IGNORE" if expression.args.get("ignore") else "" 2498 is_function = expression.args.get("is_function") 2499 if is_function: 2500 this = f"{this} FUNCTION" 2501 this = f"{this} {self.sql(expression, 'this')}" 2502 2503 exists = " IF EXISTS" if expression.args.get("exists") else "" 2504 where = self.sql(expression, "where") 2505 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 2506 using = self.expressions(expression, key="using", flat=True) 2507 using = f"{self.sep()}REPLACE USING ({using})" if using else "" 2508 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 2509 on_conflict = self.sql(expression, "conflict") 2510 on_conflict = f" {on_conflict}" if on_conflict else "" 2511 by_name = " BY NAME" if expression.args.get("by_name") else "" 2512 default_values = "DEFAULT VALUES" if expression.args.get("default") else "" 2513 returning = self.sql(expression, "returning") 2514 2515 if self.RETURNING_END: 2516 expression_sql = f"{expression_sql}{on_conflict}{default_values}{returning}" 2517 else: 2518 expression_sql = f"{returning}{expression_sql}{on_conflict}" 2519 2520 partition_by = self.sql(expression, "partition") 2521 partition_by = f" {partition_by}" if partition_by else "" 2522 settings = self.sql(expression, "settings") 2523 settings = f" {settings}" if settings else "" 2524 2525 source = self.sql(expression, "source") 2526 source = f"TABLE {source}" if source else "" 2527 2528 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{using}{expression_sql}{source}" 2529 return self.prepend_ctes(expression, sql) 2530 2531 def introducer_sql(self, expression: exp.Introducer) -> str: 2532 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 2533 2534 def kill_sql(self, expression: exp.Kill) -> str: 2535 kind = self.sql(expression, "kind") 2536 kind = f" {kind}" if kind else "" 2537 this = self.sql(expression, "this") 2538 this = f" {this}" if this else "" 2539 return f"KILL{kind}{this}" 2540 2541 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 2542 return expression.name 2543 2544 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 2545 return expression.name 2546 2547 def onconflict_sql(self, expression: exp.OnConflict) -> str: 2548 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 2549 2550 constraint = self.sql(expression, "constraint") 2551 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 2552 2553 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 2554 if conflict_keys: 2555 conflict_keys = f"({conflict_keys})" 2556 2557 index_predicate = self.sql(expression, "index_predicate") 2558 conflict_keys = f"{conflict_keys}{index_predicate} " 2559 2560 action = self.sql(expression, "action") 2561 2562 expressions = self.expressions(expression, flat=True) 2563 if expressions: 2564 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 2565 expressions = f" {set_keyword}{expressions}" 2566 2567 where = self.sql(expression, "where") 2568 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 2569 2570 def returning_sql(self, expression: exp.Returning) -> str: 2571 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 2572 2573 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 2574 fields = self.sql(expression, "fields") 2575 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 2576 escaped = self.sql(expression, "escaped") 2577 escaped = f" ESCAPED BY {escaped}" if escaped else "" 2578 items = self.sql(expression, "collection_items") 2579 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 2580 keys = self.sql(expression, "map_keys") 2581 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 2582 lines = self.sql(expression, "lines") 2583 lines = f" LINES TERMINATED BY {lines}" if lines else "" 2584 null = self.sql(expression, "null") 2585 null = f" NULL DEFINED AS {null}" if null else "" 2586 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 2587 2588 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 2589 return f"WITH ({self.expressions(expression, flat=True)})" 2590 2591 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 2592 this = f"{self.sql(expression, 'this')} INDEX" 2593 target = self.sql(expression, "target") 2594 target = f" FOR {target}" if target else "" 2595 return f"{this}{target} ({self.expressions(expression, flat=True)})" 2596 2597 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 2598 this = self.sql(expression, "this") 2599 kind = self.sql(expression, "kind") 2600 expr = self.sql(expression, "expression") 2601 return f"{this} ({kind} => {expr})" 2602 2603 def table_parts(self, expression: exp.Table) -> str: 2604 return ".".join( 2605 self.sql(part) 2606 for part in ( 2607 expression.args.get("catalog"), 2608 expression.args.get("db"), 2609 expression.args.get("this"), 2610 ) 2611 if part is not None 2612 ) 2613 2614 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 2615 table = self.table_parts(expression) 2616 only = "ONLY " if expression.args.get("only") else "" 2617 partition = self.sql(expression, "partition") 2618 partition = f" {partition}" if partition else "" 2619 version = self.sql(expression, "version") 2620 version = f" {version}" if version else "" 2621 alias = self.sql(expression, "alias") 2622 alias = f"{sep}{alias}" if alias else "" 2623 2624 sample = self.sql(expression, "sample") 2625 post_alias = "" 2626 pre_alias = "" 2627 2628 if self.dialect.ALIAS_POST_TABLESAMPLE: 2629 pre_alias = sample 2630 else: 2631 post_alias = sample 2632 2633 if self.dialect.ALIAS_POST_VERSION: 2634 pre_alias = f"{pre_alias}{version}" 2635 else: 2636 post_alias = f"{post_alias}{version}" 2637 2638 hints = self.expressions(expression, key="hints", sep=" ") 2639 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2640 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2641 joins = self.indent( 2642 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2643 ) 2644 laterals = self.expressions(expression, key="laterals", sep="") 2645 2646 file_format = self.sql(expression, "format") 2647 pattern = self.sql(expression, "pattern") 2648 if file_format: 2649 pattern = f", PATTERN => {pattern}" if pattern else "" 2650 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2651 elif pattern: 2652 file_format = f" (PATTERN => {pattern})" 2653 2654 ordinality = expression.args.get("ordinality") or "" 2655 if ordinality: 2656 ordinality = f" WITH ORDINALITY{alias}" 2657 alias = "" 2658 2659 when = self.sql(expression, "when") 2660 if when: 2661 if self.HISTORICAL_DATA_POST_ALIAS: 2662 alias = f"{alias} {when}" 2663 else: 2664 table = f"{table} {when}" 2665 2666 changes = self.sql(expression, "changes") 2667 changes = f" {changes}" if changes else "" 2668 2669 rows_from = self.expressions(expression, key="rows_from") 2670 if rows_from: 2671 table = f"ROWS FROM {self.wrap(rows_from)}" 2672 2673 indexed = expression.args.get("indexed") 2674 if indexed is not None: 2675 indexed = f" INDEXED BY {self.sql(indexed)}" if indexed else " NOT INDEXED" 2676 else: 2677 indexed = "" 2678 2679 return f"{only}{table}{changes}{partition}{file_format}{pre_alias}{alias}{indexed}{hints}{pivots}{post_alias}{joins}{laterals}{ordinality}" 2680 2681 def tableargument_sql(self, expression: exp.TableArgument) -> str: 2682 table = expression.this 2683 return f"TABLE {self.maybe_comment(self.table_parts(table), table)}" 2684 2685 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2686 table = self.func("TABLE", expression.this) 2687 alias = self.sql(expression, "alias") 2688 alias = f" AS {alias}" if alias else "" 2689 sample = self.sql(expression, "sample") 2690 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2691 joins = self.indent( 2692 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2693 ) 2694 return f"{table}{alias}{pivots}{sample}{joins}" 2695 2696 def tablesample_sql( 2697 self, 2698 expression: exp.TableSample, 2699 tablesample_keyword: str | None = None, 2700 ) -> str: 2701 if expression.expressions: 2702 self.unsupported("Multiple sample sets are not supported") 2703 return "" 2704 2705 method = self.sql(expression, "method") 2706 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2707 numerator = self.sql(expression, "bucket_numerator") 2708 denominator = self.sql(expression, "bucket_denominator") 2709 field = self.sql(expression, "bucket_field") 2710 field = f" ON {field}" if field else "" 2711 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2712 seed = self.sql(expression, "seed") 2713 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2714 2715 size = self.sql(expression, "size") 2716 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2717 size = f"{size} ROWS" 2718 2719 percent = self.sql(expression, "percent") 2720 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2721 percent = f"{percent} PERCENT" 2722 2723 expr = f"{bucket}{percent}{size}" 2724 if self.TABLESAMPLE_REQUIRES_PARENS: 2725 expr = f"({expr})" 2726 2727 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2728 2729 def _pivot_in_value_aliases(self, expression: exp.Pivot) -> list[exp.Expression] | None: 2730 # Returns the rewritten field.expressions list with PivotAlias wrappers injected where 2731 # the stored column name differs from the target dialect's natural output. 2732 columns = expression.args.get("columns") 2733 if not columns or len(expression.fields) != 1: 2734 return None 2735 2736 args = expression.args 2737 parser_cls = self.dialect.parser_class 2738 2739 tgt_identify_pivot_strings = parser_cls.IDENTIFY_PIVOT_STRINGS 2740 tgt_prefixed_pivot_columns = parser_cls.PREFIXED_PIVOT_COLUMNS 2741 tgt_pivot_column_naming = parser_cls.PIVOT_COLUMN_NAMING 2742 2743 src_identify_pivot_strings = args.get("identify_pivot_strings", tgt_identify_pivot_strings) 2744 src_prefixed_pivot_columns = args.get("prefixed_pivot_columns", tgt_prefixed_pivot_columns) 2745 src_pivot_column_naming = args.get("pivot_column_naming", tgt_pivot_column_naming) 2746 2747 if ( 2748 src_identify_pivot_strings == tgt_identify_pivot_strings 2749 and src_prefixed_pivot_columns == tgt_prefixed_pivot_columns 2750 and src_pivot_column_naming == tgt_pivot_column_naming 2751 ): 2752 return None 2753 2754 in_exprs = expression.fields[0].expressions 2755 step = len(columns) // len(in_exprs) 2756 2757 suffix = "" 2758 if len(expression.expressions) != 1 or expression.expressions[0].alias: 2759 # Derive the per-value suffix from the first stored column vs the first IN-list value. 2760 # This correctly handles dialects (e.g. Spark single-agg) that ignore agg aliases. 2761 first_base = ( 2762 in_exprs[0].sql() if src_identify_pivot_strings else in_exprs[0].alias_or_name 2763 ) 2764 first_stored = columns[0].name 2765 2766 # exit if only suffix matches, not prefix. (e.g. BigQuery, which cannot be fixed) 2767 if not first_stored.startswith(first_base): 2768 return None 2769 2770 suffix = first_stored[len(first_base) :] 2771 2772 # Whether the target dialect would append an agg-name suffix for this pivot. 2773 # Spark single-agg uniquely drops the agg alias entirely. 2774 target_has_suffix = ( 2775 len(expression.expressions) > 1 or tgt_pivot_column_naming != "agg_name_if_multiple" 2776 ) and any(a.alias for a in expression.expressions) 2777 source_has_suffix = suffix != "" 2778 2779 new_exprs: list[exp.Expression] = [] 2780 modified = False 2781 for val_idx, e in enumerate(in_exprs): 2782 if isinstance(e, exp.PivotAlias): 2783 new_exprs.append(e) 2784 continue 2785 2786 i = val_idx * step 2787 stored_full = columns[i].name 2788 stored_value = stored_full[: -len(suffix)] if suffix else stored_full 2789 target_value = e.sql() if tgt_identify_pivot_strings else e.alias_or_name 2790 2791 # Source had a suffix, but target won't apply one 2792 if source_has_suffix and not target_has_suffix: 2793 new_exprs.append( 2794 exp.PivotAlias(this=e, alias=exp.to_identifier(stored_full, quoted=True)) 2795 ) 2796 modified = True 2797 # Value-part mismatch (e.g. Snowflake's literal-style values vs others). 2798 elif stored_value != target_value: 2799 new_exprs.append( 2800 exp.PivotAlias(this=e, alias=exp.to_identifier(stored_value, quoted=True)) 2801 ) 2802 modified = True 2803 else: 2804 new_exprs.append(e) 2805 2806 return new_exprs if modified else None 2807 2808 def pivot_sql(self, expression: exp.Pivot) -> str: 2809 expressions = self.expressions(expression, flat=True) 2810 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2811 2812 group = self.sql(expression, "group") 2813 2814 if expression.this: 2815 this = self.sql(expression, "this") 2816 if not expressions: 2817 sql = f"UNPIVOT {this}" 2818 else: 2819 on = f"{self.seg('ON')} {expressions}" 2820 into = self.sql(expression, "into") 2821 into = f"{self.seg('INTO')} {into}" if into else "" 2822 using = self.expressions(expression, key="using", flat=True) 2823 using = f"{self.seg('USING')} {using}" if using else "" 2824 sql = f"{direction} {this}{on}{into}{using}{group}" 2825 return self.prepend_ctes(expression, sql) 2826 2827 if not expression.unpivot: 2828 # Wrap IN-list values with explicit aliases where the target dialect would differ 2829 new_field_exprs = self._pivot_in_value_aliases(expression) 2830 if new_field_exprs is not None: 2831 expression.fields[0].set("expressions", new_field_exprs) 2832 2833 alias = self.sql(expression, "alias") 2834 if alias: 2835 alias = f" AS {alias}" if self.PIVOT_ALIAS_WITH_AS else f" {alias}" 2836 2837 fields = self.expressions( 2838 expression, 2839 "fields", 2840 sep=" ", 2841 dynamic=True, 2842 new_line=True, 2843 skip_first=True, 2844 skip_last=True, 2845 ) 2846 2847 include_nulls = expression.args.get("include_nulls") 2848 if include_nulls is not None: 2849 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2850 else: 2851 nulls = "" 2852 2853 default_on_null = self.sql(expression, "default_on_null") 2854 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2855 sql = f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}" 2856 return self.prepend_ctes(expression, sql) 2857 2858 def version_sql(self, expression: exp.Version) -> str: 2859 this = f"FOR {expression.name}" 2860 kind = expression.text("kind") 2861 expr = self.sql(expression, "expression") 2862 return f"{this} {kind} {expr}" 2863 2864 def tuple_sql(self, expression: exp.Tuple) -> str: 2865 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2866 2867 def _update_from_joins_sql(self, expression: exp.Update) -> tuple[str, str]: 2868 """ 2869 Returns (join_sql, from_sql) for UPDATE statements. 2870 - join_sql: placed after UPDATE table, before SET 2871 - from_sql: placed after SET clause (standard position) 2872 Dialects like MySQL need to convert FROM to JOIN syntax. 2873 """ 2874 if self.UPDATE_STATEMENT_SUPPORTS_FROM or not (from_expr := expression.args.get("from_")): 2875 return ("", self.sql(expression, "from_")) 2876 2877 # Qualify unqualified columns in SET clause with the target table 2878 # MySQL requires qualified column names in multi-table UPDATE to avoid ambiguity 2879 target_table = expression.this 2880 if isinstance(target_table, exp.Table): 2881 target_name = exp.to_identifier(target_table.alias_or_name) 2882 for eq in expression.expressions: 2883 col = eq.this 2884 if isinstance(col, exp.Column) and not col.table: 2885 col.set("table", target_name) 2886 2887 table = from_expr.this 2888 if nested_joins := table.args.get("joins", []): 2889 table.set("joins", None) 2890 2891 join_sql = self.sql(exp.Join(this=table, on=exp.true())) 2892 for nested in nested_joins: 2893 if not nested.args.get("on") and not nested.args.get("using"): 2894 nested.set("on", exp.true()) 2895 join_sql += self.sql(nested) 2896 2897 return (join_sql, "") 2898 2899 def update_sql(self, expression: exp.Update) -> str: 2900 hint = self.sql(expression, "hint") 2901 alternative = self.sql(expression, "alternative") 2902 if alternative: 2903 if self.dialect.SUPPORTS_UPDATE_OR or self.dialect == "": 2904 alternative = f" OR {alternative}" 2905 else: 2906 self.unsupported(f"UPDATE OR {alternative} is not supported") 2907 alternative = "" 2908 this = self.sql(expression, "this") 2909 join_sql, from_sql = self._update_from_joins_sql(expression) 2910 set_sql = self.expressions(expression, flat=True) 2911 where_sql = self.sql(expression, "where") 2912 returning = self.sql(expression, "returning") 2913 order = self.sql(expression, "order") 2914 limit = self.sql(expression, "limit") 2915 if self.RETURNING_END: 2916 expression_sql = f"{from_sql}{where_sql}{returning}" 2917 else: 2918 expression_sql = f"{returning}{from_sql}{where_sql}" 2919 options = self.expressions(expression, key="options") 2920 options = f" OPTION({options})" if options else "" 2921 sql = f"UPDATE{hint}{alternative} {this}{join_sql} SET {set_sql}{expression_sql}{order}{limit}{options}" 2922 return self.prepend_ctes(expression, sql) 2923 2924 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2925 values_as_table = values_as_table and self.VALUES_AS_TABLE 2926 2927 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2928 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2929 args = self.expressions(expression) 2930 alias = self.sql(expression, "alias") 2931 values = f"VALUES{self.seg('')}{args}" 2932 values = ( 2933 f"({values})" 2934 if self.WRAP_DERIVED_VALUES 2935 and ( 2936 alias 2937 or isinstance(expression.parent, (exp.From, exp.Table, exp.MatchRecognize)) 2938 ) 2939 else values 2940 ) 2941 values = self.query_modifiers(expression, values) 2942 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2943 return f"{values} AS {alias}{pivots}" if alias else f"{values}{pivots}" 2944 2945 # Converts `VALUES...` expression into a series of select unions. 2946 alias_node = expression.args.get("alias") 2947 column_names = alias_node and alias_node.columns 2948 2949 selects: list[exp.Query] = [] 2950 2951 for i, tup in enumerate(expression.expressions): 2952 row = tup.expressions 2953 2954 if i == 0 and column_names: 2955 row = [ 2956 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2957 ] 2958 2959 selects.append(exp.Select(expressions=row)) 2960 2961 if self.pretty: 2962 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2963 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2964 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2965 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2966 for key in ("order", "limit", "offset"): 2967 if value := expression.args.get(key): 2968 query.set(key, value.pop()) 2969 subquery = query.subquery(alias_node and alias_node.this, copy=False) 2970 subquery.set("pivots", expression.args.pop("pivots", None)) 2971 return self.subquery_sql(subquery) 2972 2973 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2974 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2975 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2976 return f"({self.query_modifiers(expression, unions)}){alias}{pivots}" 2977 2978 def var_sql(self, expression: exp.Var) -> str: 2979 return self.sql(expression, "this") 2980 2981 @unsupported_args("expressions") 2982 def into_sql(self, expression: exp.Into) -> str: 2983 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2984 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2985 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2986 2987 def from_sql(self, expression: exp.From) -> str: 2988 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2989 2990 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2991 grouping_sets = self.expressions(expression, indent=False) 2992 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2993 2994 def rollup_sql(self, expression: exp.Rollup) -> str: 2995 expressions = self.expressions(expression, indent=False) 2996 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2997 2998 def rollupindex_sql(self, expression: exp.RollupIndex) -> str: 2999 this = self.sql(expression, "this") 3000 3001 columns = self.expressions(expression, flat=True) 3002 3003 from_sql = self.sql(expression, "from_index") 3004 from_sql = f" FROM {from_sql}" if from_sql else "" 3005 3006 properties = expression.args.get("properties") 3007 properties_sql = ( 3008 f" {self.properties(properties, prefix='PROPERTIES')}" if properties else "" 3009 ) 3010 3011 return f"{this}({columns}){from_sql}{properties_sql}" 3012 3013 def rollupproperty_sql(self, expression: exp.RollupProperty) -> str: 3014 return f"ROLLUP ({self.expressions(expression, flat=True)})" 3015 3016 def cube_sql(self, expression: exp.Cube) -> str: 3017 expressions = self.expressions(expression, indent=False) 3018 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 3019 3020 def group_sql(self, expression: exp.Group) -> str: 3021 group_by_all = expression.args.get("all") 3022 if group_by_all is True: 3023 modifier = " ALL" 3024 elif group_by_all is False: 3025 modifier = " DISTINCT" 3026 else: 3027 modifier = "" 3028 3029 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 3030 3031 grouping_sets = self.expressions(expression, key="grouping_sets") 3032 cube = self.expressions(expression, key="cube") 3033 rollup = self.expressions(expression, key="rollup") 3034 3035 groupings = csv( 3036 self.seg(grouping_sets) if grouping_sets else "", 3037 self.seg(cube) if cube else "", 3038 self.seg(rollup) if rollup else "", 3039 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 3040 sep=self.GROUPINGS_SEP, 3041 ) 3042 3043 if ( 3044 expression.expressions 3045 and groupings 3046 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 3047 ): 3048 add_separator = True 3049 3050 if grouping_sets: 3051 if self.SUPPORTS_GROUPING_SETS_AS_SUFFIX: 3052 add_separator = False 3053 else: 3054 self.unsupported( 3055 "GROUPING SETS without a comma after GROUP BY expressions is not supported" 3056 ) 3057 3058 if add_separator: 3059 group_by = f"{group_by}{self.GROUPINGS_SEP}" 3060 3061 return f"{group_by}{groupings}" 3062 3063 def having_sql(self, expression: exp.Having) -> str: 3064 this = self.indent(self.sql(expression, "this")) 3065 return f"{self.seg('HAVING')}{self.sep()}{this}" 3066 3067 def connectto_sql(self, expression: exp.ConnectTo) -> str: 3068 return f"CONNECT {self.sql(expression, 'this')}" 3069 3070 def disconnect_sql(self, expression: exp.Disconnect) -> str: 3071 return "DISCONNECT" 3072 3073 def connect_sql(self, expression: exp.Connect) -> str: 3074 start = self.sql(expression, "start") 3075 start = self.seg(f"START WITH {start}") if start else "" 3076 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 3077 connect = self.sql(expression, "connect") 3078 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 3079 return start + connect 3080 3081 def prior_sql(self, expression: exp.Prior) -> str: 3082 return f"PRIOR {self.sql(expression, 'this')}" 3083 3084 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3085 if ( 3086 match_condition := expression.args.get("match_condition") 3087 ) and not self.SUPPORTS_MATCH_CONDITION: 3088 if self.MATCH_CONDITION_IN_ON and not expression.args.get("using"): 3089 expression = expression.on(match_condition) 3090 expression.set("match_condition", None) 3091 # Snowflake ASOF joins preserve unmatched left rows. 3092 expression.set("side", "LEFT") 3093 else: 3094 self.unsupported("MATCH_CONDITION is not supported") 3095 3096 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 3097 side = None 3098 else: 3099 side = expression.side 3100 3101 op_sql = " ".join( 3102 op 3103 for op in ( 3104 expression.method, 3105 "GLOBAL" if expression.args.get("global_") else None, 3106 side, 3107 expression.kind, 3108 expression.hint if self.JOIN_HINTS else None, 3109 "DIRECTED" if expression.args.get("directed") and self.DIRECTED_JOINS else None, 3110 ) 3111 if op 3112 ) 3113 match_cond = self.sql(expression, "match_condition") 3114 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 3115 nearest = self.sql(expression, "nearest") 3116 nearest = f" {nearest}" if nearest else "" 3117 on_sql = self.sql(expression, "on") 3118 using = expression.args.get("using") 3119 3120 if not on_sql and using: 3121 on_sql = csv(*(self.sql(column) for column in using)) 3122 3123 this = expression.this 3124 this_sql = self.sql(this) 3125 3126 exprs = self.expressions(expression) 3127 if exprs: 3128 this_sql = f"{this_sql},{self.seg(exprs)}" 3129 3130 if on_sql: 3131 on_sql = self.indent(on_sql, skip_first=True) 3132 space = self.seg(" " * self.pad) if self.pretty else " " 3133 if using: 3134 on_sql = f"{space}USING ({on_sql})" 3135 else: 3136 on_sql = f"{space}ON {on_sql}" 3137 elif not op_sql and not nearest: 3138 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 3139 return f" {this_sql}" 3140 3141 return f", {this_sql}" 3142 3143 if join_op: 3144 op_sql = join_op 3145 elif op_sql != "STRAIGHT_JOIN": 3146 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 3147 3148 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3149 return f"{self.seg(op_sql)} {this_sql}{match_cond}{nearest}{on_sql}{pivots}" 3150 3151 def nearest_sql(self, expression: exp.Nearest) -> str: 3152 if not self.SUPPORTS_NEAREST_JOIN: 3153 self.unsupported("NEAREST joins are not supported") 3154 3155 approximate = "APPROX " if expression.args.get("approximate") else "" 3156 metric = "SIMILARITY" if expression.args.get("similarity") else "DISTANCE" 3157 return f"{approximate}NEAREST {self.sql(expression, 'count')} BY {metric} {self.sql(expression, 'this')}" 3158 3159 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->", wrap: bool = True) -> str: 3160 args = self.expressions(expression, flat=True) 3161 args = f"({args})" if wrap and len(args.split(",")) > 1 else args 3162 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 3163 3164 def lateral_op(self, expression: exp.Lateral) -> str: 3165 cross_apply = expression.args.get("cross_apply") 3166 3167 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 3168 if cross_apply is True: 3169 op = "INNER JOIN " 3170 elif cross_apply is False: 3171 op = "LEFT JOIN " 3172 else: 3173 op = "" 3174 3175 return f"{op}LATERAL" 3176 3177 def lateral_sql(self, expression: exp.Lateral) -> str: 3178 this = self.sql(expression, "this") 3179 3180 if expression.args.get("view"): 3181 alias = expression.args["alias"] 3182 columns = self.expressions(alias, key="columns", flat=True) 3183 table = f" {alias.name}" if alias.name else "" 3184 columns = f" AS {columns}" if columns else "" 3185 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 3186 return f"{op_sql}{self.sep()}{this}{table}{columns}" 3187 3188 table_alias = expression.args.get("alias") 3189 offset = expression.this.args.get("offset") 3190 3191 if ( 3192 self.UNNEST_WITH_ORDINALITY 3193 and table_alias 3194 and isinstance(expression.this, exp.Unnest) 3195 and isinstance(offset, exp.Identifier) 3196 ): 3197 # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset 3198 table_alias = table_alias.copy() 3199 table_alias.append("columns", offset.copy()) 3200 3201 alias = self.sql(table_alias) 3202 alias = f" AS {alias}" if alias else "" 3203 3204 ordinality = expression.args.get("ordinality") or "" 3205 if ordinality: 3206 ordinality = f" WITH ORDINALITY{alias}" 3207 alias = "" 3208 3209 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}" 3210 3211 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 3212 this = self.sql(expression, "this") 3213 3214 if expression.is_limit_all and not self.dialect.SUPPORTS_LIMIT_ALL: 3215 return this 3216 3217 args = [ 3218 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 3219 for e in (expression.args.get(k) for k in ("offset", "expression")) 3220 if e 3221 ] 3222 3223 args_sql = ", ".join(self.sql(e) for e in args) 3224 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 3225 expressions = self.expressions(expression, flat=True) 3226 limit_options = self.sql(expression, "limit_options") 3227 expressions = f" BY {expressions}" if expressions else "" 3228 3229 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 3230 3231 def offset_sql(self, expression: exp.Offset) -> str: 3232 this = self.sql(expression, "this") 3233 value = expression.expression 3234 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 3235 expressions = self.expressions(expression, flat=True) 3236 expressions = f" BY {expressions}" if expressions else "" 3237 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 3238 3239 def setitem_sql(self, expression: exp.SetItem) -> str: 3240 kind = self.sql(expression, "kind") 3241 if not self.SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD and kind == "VARIABLE": 3242 kind = "" 3243 else: 3244 kind = f"{kind} " if kind else "" 3245 this = self.sql(expression, "this") 3246 expressions = self.expressions(expression) 3247 collate = self.sql(expression, "collate") 3248 collate = f" COLLATE {collate}" if collate else "" 3249 global_ = "GLOBAL " if expression.args.get("global_") else "" 3250 return f"{global_}{kind}{this}{expressions}{collate}" 3251 3252 def set_sql(self, expression: exp.Set) -> str: 3253 expressions = f" {self.expressions(expression, flat=True)}" 3254 tag = " TAG" if expression.args.get("tag") else "" 3255 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 3256 3257 def queryband_sql(self, expression: exp.QueryBand) -> str: 3258 this = self.sql(expression, "this") 3259 update = " UPDATE" if expression.args.get("update") else "" 3260 scope = self.sql(expression, "scope") 3261 scope = f" FOR {scope}" if scope else "" 3262 3263 return f"QUERY_BAND = {this}{update}{scope}" 3264 3265 def pragma_sql(self, expression: exp.Pragma) -> str: 3266 return f"PRAGMA {self.sql(expression, 'this')}" 3267 3268 def lock_sql(self, expression: exp.Lock) -> str: 3269 if not self.LOCKING_READS_SUPPORTED: 3270 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 3271 return "" 3272 3273 update = expression.args["update"] 3274 key = expression.args.get("key") 3275 if update: 3276 lock_type = "FOR NO KEY UPDATE" if key else "FOR UPDATE" 3277 else: 3278 lock_type = "FOR KEY SHARE" if key else "FOR SHARE" 3279 expressions = self.expressions(expression, flat=True) 3280 expressions = f" OF {expressions}" if expressions else "" 3281 wait = expression.args.get("wait") 3282 3283 if wait is not None: 3284 if isinstance(wait, exp.Literal): 3285 wait = f" WAIT {self.sql(wait)}" 3286 else: 3287 wait = " NOWAIT" if wait else " SKIP LOCKED" 3288 3289 return f"{lock_type}{expressions}{wait or ''}" 3290 3291 def literal_sql(self, expression: exp.Literal) -> str: 3292 text = expression.this or "" 3293 if expression.is_string: 3294 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 3295 return text 3296 3297 def escape_str( 3298 self, 3299 text: str, 3300 escape_backslash: bool = True, 3301 delimiter: str | None = None, 3302 escaped_delimiter: str | None = None, 3303 is_byte_string: bool = False, 3304 is_bytes: bool = False, 3305 ) -> str: 3306 if is_byte_string: 3307 supports_escape_sequences = self.dialect.BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES 3308 else: 3309 supports_escape_sequences = self.dialect.STRINGS_SUPPORT_ESCAPED_SEQUENCES 3310 3311 if supports_escape_sequences: 3312 text = "".join( 3313 self.dialect.ESCAPED_SEQUENCES.get(ch, ch) if escape_backslash or ch != "\\" else ch 3314 for ch in text 3315 ) 3316 3317 if is_bytes and "x" in self.dialect.tokenizer_class.NUMERIC_ESCAPES: 3318 # Escape high bytes so they aren't re-encoded as UTF-8 characters. 3319 text = _HIGH_BYTE_RE.sub(lambda m: f"\\x{ord(m.group()):02x}", text) 3320 3321 delimiter = delimiter or self.dialect.QUOTE_END 3322 escaped_delimiter = escaped_delimiter or self._escaped_quote_end 3323 3324 return self._replace_line_breaks(text).replace(delimiter, escaped_delimiter) 3325 3326 def loaddata_sql(self, expression: exp.LoadData) -> str: 3327 is_overwrite = expression.args.get("overwrite") 3328 overwrite = " OVERWRITE" if is_overwrite else "" 3329 this = self.sql(expression, "this") 3330 3331 files = expression.args.get("files") 3332 if files: 3333 files_sql = self.expressions(files, flat=True) 3334 files_sql = f"FILES{self.wrap(files_sql)}" 3335 if is_overwrite: 3336 this = f" {this}" 3337 elif expression.args.get("temp"): 3338 this = f" INTO TEMP TABLE {this}" 3339 else: 3340 this = f" INTO TABLE {this}" 3341 return f"LOAD DATA{overwrite}{this} FROM {files_sql}" 3342 3343 local = " LOCAL" if expression.args.get("local") else "" 3344 inpath = f" INPATH {self.sql(expression, 'inpath')}" 3345 this = f" INTO TABLE {this}" 3346 partition = self.sql(expression, "partition") 3347 partition = f" {partition}" if partition else "" 3348 input_format = self.sql(expression, "input_format") 3349 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 3350 serde = self.sql(expression, "serde") 3351 serde = f" SERDE {serde}" if serde else "" 3352 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 3353 3354 def null_sql(self, *_) -> str: 3355 return "NULL" 3356 3357 def boolean_sql(self, expression: exp.Boolean) -> str: 3358 return "TRUE" if expression.this else "FALSE" 3359 3360 def booland_sql(self, expression: exp.Booland) -> str: 3361 return f"(({self.sql(expression, 'this')}) AND ({self.sql(expression, 'expression')}))" 3362 3363 def boolor_sql(self, expression: exp.Boolor) -> str: 3364 return f"(({self.sql(expression, 'this')}) OR ({self.sql(expression, 'expression')}))" 3365 3366 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 3367 this = self.sql(expression, "this") 3368 this = f"{this} " if this else this 3369 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 3370 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=bool(this) or flat) 3371 3372 def withfill_sql(self, expression: exp.WithFill) -> str: 3373 from_sql = self.sql(expression, "from_") 3374 from_sql = f" FROM {from_sql}" if from_sql else "" 3375 to_sql = self.sql(expression, "to") 3376 to_sql = f" TO {to_sql}" if to_sql else "" 3377 step_sql = self.sql(expression, "step") 3378 step_sql = f" STEP {step_sql}" if step_sql else "" 3379 interpolated_values = [ 3380 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 3381 if isinstance(e, exp.Alias) 3382 else self.sql(e, "this") 3383 for e in expression.args.get("interpolate") or [] 3384 ] 3385 interpolate = ( 3386 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 3387 ) 3388 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 3389 3390 def cluster_sql(self, expression: exp.Cluster) -> str: 3391 return self.op_expressions("CLUSTER BY", expression) 3392 3393 def clusterproperty_sql(self, expression: exp.ClusterProperty) -> str: 3394 if expression.this: 3395 self.unsupported(f"Unsupported CLUSTER BY {self.sql(expression, 'this')}") 3396 return "" 3397 expressions = self.expressions(expression, flat=True) 3398 return f"CLUSTER BY ({expressions})" 3399 3400 def distribute_sql(self, expression: exp.Distribute) -> str: 3401 return self.op_expressions("DISTRIBUTE BY", expression) 3402 3403 def sort_sql(self, expression: exp.Sort) -> str: 3404 return self.op_expressions("SORT BY", expression) 3405 3406 def _resolve_ordered_for_null_ordering_simulation( 3407 self, expression: exp.Ordered 3408 ) -> exp.Expr | None: 3409 """Resolve a bare ORDER BY name against the enclosing SELECT projection. 3410 3411 Returns the underlying expression of the uniquely-matching projection 3412 (Alias-stripped) for substitution into the NULLS FIRST/LAST CASE 3413 simulation, since the CASE is evaluated in FROM-clause scope rather 3414 than alias scope (MySQL error 1052). Returns None if no safe 3415 substitution applies, leaving the original behaviour unchanged. 3416 """ 3417 this = expression.this 3418 if not (isinstance(this, exp.Column) and not this.table): 3419 return None 3420 3421 # Only a query's own ORDER BY can reference its projection aliases 3422 order = expression.parent 3423 ancestor = order.parent if isinstance(order, exp.Order) else None 3424 if not isinstance(ancestor, exp.Select): 3425 return None 3426 3427 column_name = this.name 3428 matched: list[exp.Expr] = [ 3429 p.this if isinstance(p, exp.Alias) else p 3430 for p in ancestor.selects 3431 if p.output_name == column_name 3432 ] 3433 match = matched[0] if len(matched) == 1 else None 3434 3435 # Skip the substitution when it would be identical to the existing 3436 # reference (e.g. ``SELECT col FROM t ORDER BY col``). 3437 if isinstance(match, exp.Column) and not match.table and match.name == column_name: 3438 return None 3439 3440 return match 3441 3442 def ordered_sql(self, expression: exp.Ordered) -> str: 3443 desc = expression.args.get("desc") 3444 asc = not desc 3445 3446 nulls_first = expression.args.get("nulls_first") 3447 nulls_last = not nulls_first 3448 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 3449 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 3450 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 3451 3452 this = self.sql(expression, "this") 3453 3454 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 3455 nulls_sort_change = "" 3456 if nulls_first and ( 3457 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 3458 ): 3459 nulls_sort_change = " NULLS FIRST" 3460 elif ( 3461 nulls_last 3462 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 3463 and not nulls_are_last 3464 ): 3465 nulls_sort_change = " NULLS LAST" 3466 3467 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 3468 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 3469 window = expression.find_ancestor(exp.Window, exp.Select) 3470 3471 if isinstance(window, exp.Window): 3472 window_this = window.this 3473 if isinstance(window_this, (exp.IgnoreNulls, exp.RespectNulls)): 3474 window_this = window_this.this 3475 spec = window.args.get("spec") 3476 else: 3477 window_this = None 3478 spec = None 3479 3480 # Some window functions (e.g. LAST_VALUE, RANK) support NULLS FIRST/LAST 3481 # without a spec or with a ROWS spec, but not with RANGE 3482 if not ( 3483 isinstance(window_this, self.WINDOW_FUNCS_WITH_NULL_ORDERING) 3484 and (not spec or spec.text("kind").upper() == "ROWS") 3485 ): 3486 if window_this and spec: 3487 self.unsupported( 3488 f"'{nulls_sort_change.strip()}' translation not supported in window function {window_this.sql_name()}" 3489 ) 3490 nulls_sort_change = "" 3491 elif self.NULL_ORDERING_SUPPORTED is False and ( 3492 (asc and nulls_sort_change == " NULLS LAST") 3493 or (desc and nulls_sort_change == " NULLS FIRST") 3494 ): 3495 # BigQuery does not allow these ordering/nulls combinations when used under 3496 # an aggregation func or under a window containing one 3497 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 3498 3499 if isinstance(ancestor, exp.Window): 3500 ancestor = ancestor.this 3501 if isinstance(ancestor, exp.AggFunc): 3502 self.unsupported( 3503 f"'{nulls_sort_change.strip()}' translation not supported for aggregate function {ancestor.sql_name()} with {sort_order} sort order" 3504 ) 3505 nulls_sort_change = "" 3506 elif self.NULL_ORDERING_SUPPORTED is None: 3507 if expression.this.is_int: 3508 self.unsupported( 3509 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 3510 ) 3511 elif not isinstance(expression.this, exp.Rand): 3512 resolved = self._resolve_ordered_for_null_ordering_simulation(expression) 3513 target = self.sql(resolved) if resolved is not None else this 3514 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 3515 this = f"CASE WHEN {target} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {target}" 3516 nulls_sort_change = "" 3517 3518 with_fill = self.sql(expression, "with_fill") 3519 with_fill = f" {with_fill}" if with_fill else "" 3520 3521 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 3522 3523 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 3524 window_frame = self.sql(expression, "window_frame") 3525 window_frame = f"{window_frame} " if window_frame else "" 3526 3527 this = self.sql(expression, "this") 3528 3529 return f"{window_frame}{this}" 3530 3531 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 3532 partition = self.partition_by_sql(expression) 3533 order = self.sql(expression, "order") 3534 measures = self.expressions(expression, key="measures") 3535 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 3536 rows = self.sql(expression, "rows") 3537 rows = self.seg(rows) if rows else "" 3538 after = self.sql(expression, "after") 3539 after = self.seg(after) if after else "" 3540 pattern = self.sql(expression, "pattern") 3541 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 3542 subset = self.expressions(expression, key="subset") 3543 subset = self.seg(f"SUBSET{self.seg(subset)}") if subset else "" 3544 definition_sqls = [ 3545 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 3546 for definition in expression.args.get("define") or [] 3547 ] 3548 definitions = self.expressions(sqls=definition_sqls) 3549 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 3550 body = "".join( 3551 ( 3552 partition, 3553 order, 3554 measures, 3555 rows, 3556 after, 3557 pattern, 3558 subset, 3559 define, 3560 ) 3561 ).lstrip() 3562 alias = self.sql(expression, "alias") 3563 alias = f" {alias}" if alias else "" 3564 sample = self.sql(expression, "sample") 3565 joins = self.indent( 3566 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 3567 ) 3568 source = self.sql(expression, "this") 3569 return f"{source}{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}{sample}{joins}" 3570 3571 def query_modifiers(self, expression: exp.Expr, *sqls: str) -> str: 3572 limit = expression.args.get("limit") 3573 3574 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 3575 count = limit.args.get("count") 3576 # "FETCH FIRST ROWS ONLY" without a count means one row per the SQL 3577 # standard; emitting a bare "LIMIT" here would produce invalid SQL. 3578 limit = exp.Limit( 3579 expression=exp.maybe_copy(count) if count is not None else exp.Literal.number(1) 3580 ) 3581 elif ( 3582 self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit) and not limit.is_limit_all 3583 ): 3584 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 3585 3586 return csv( 3587 *sqls, 3588 *[self.sql(join) for join in expression.args.get("joins") or []], 3589 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 3590 self.sql(expression, "prewhere"), 3591 self.sql(expression, "where"), 3592 self.sql(expression, "connect"), 3593 self.sql(expression, "group"), 3594 self.sql(expression, "having"), 3595 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 3596 self.sql(expression, "order"), 3597 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 3598 *self.after_limit_modifiers(expression), 3599 self.sql(expression, "for_"), 3600 self.options_modifier(expression), 3601 sep="", 3602 ) 3603 3604 def options_modifier(self, expression: exp.Expr) -> str: 3605 options = self.expressions(expression, key="options") 3606 return f" {options}" if options else "" 3607 3608 def forclause_sql(self, expression: exp.ForClause) -> str: 3609 kind = expression.args["kind"] 3610 if kind == "BROWSE": 3611 return f"{self.sep()}FOR BROWSE" 3612 # FOR XML/JSON always carry at least AUTO/PATH. An empty rendering means 3613 # the target dialect doesn't support QueryOption, so we drop the clause. 3614 options = self.expressions(expression, key="expressions") 3615 if not options: 3616 return "" 3617 return f"{self.sep()}FOR {kind}{self.seg(options)}" 3618 3619 def queryoption_sql(self, expression: exp.QueryOption) -> str: 3620 self.unsupported("Unsupported query option.") 3621 return "" 3622 3623 def offset_limit_modifiers( 3624 self, expression: exp.Expr, fetch: bool, limit: exp.Fetch | exp.Limit | None 3625 ) -> list[str]: 3626 return [ 3627 self.sql(expression, "offset") if fetch else self.sql(limit), 3628 self.sql(limit) if fetch else self.sql(expression, "offset"), 3629 ] 3630 3631 def after_limit_modifiers(self, expression: exp.Expr) -> list[str]: 3632 locks = self.expressions(expression, key="locks", sep=" ") 3633 locks = f" {locks}" if locks else "" 3634 return [locks, self.sql(expression, "sample")] 3635 3636 def select_sql(self, expression: exp.Select) -> str: 3637 into = expression.args.get("into") 3638 if not self.SUPPORTS_SELECT_INTO and into: 3639 into.pop() 3640 3641 hint = self.sql(expression, "hint") 3642 distinct = self.sql(expression, "distinct") 3643 distinct = f" {distinct}" if distinct else "" 3644 kind = self.sql(expression, "kind") 3645 3646 limit = expression.args.get("limit") 3647 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 3648 top = self.limit_sql(limit, top=True) 3649 limit.pop() 3650 else: 3651 top = "" 3652 3653 expressions = self.expressions(expression) 3654 3655 if kind: 3656 if kind in self.SELECT_KINDS: 3657 kind = f" AS {kind}" 3658 else: 3659 if kind == "STRUCT": 3660 expressions = self.expressions( 3661 sqls=[ 3662 self.sql( 3663 exp.Struct( 3664 expressions=[ 3665 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 3666 if isinstance(e, exp.Alias) 3667 else e 3668 for e in expression.expressions 3669 ] 3670 ) 3671 ) 3672 ] 3673 ) 3674 kind = "" 3675 3676 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 3677 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 3678 3679 exclude = expression.args.get("exclude") 3680 3681 if not self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3682 exclude_sql = self.expressions(sqls=exclude, flat=True) 3683 expressions = f"{expressions}{self.seg('EXCLUDE')} ({exclude_sql})" 3684 3685 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 3686 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 3687 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 3688 expressions = f"{self.sep()}{expressions}" if expressions else expressions 3689 sql = self.query_modifiers( 3690 expression, 3691 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 3692 self.sql(expression, "into", comment=False), 3693 self.sql(expression, "from_", comment=False), 3694 ) 3695 3696 # If both the CTE and SELECT clauses have comments, generate the latter earlier 3697 if expression.args.get("with_"): 3698 sql = self.maybe_comment(sql, expression) 3699 expression.pop_comments() 3700 3701 sql = self.prepend_ctes(expression, sql) 3702 3703 if self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3704 expression.set("exclude", None) 3705 subquery = expression.subquery(copy=False) 3706 star = exp.Star(except_=exclude) 3707 sql = self.sql(exp.select(star).from_(subquery, copy=False)) 3708 3709 if not self.SUPPORTS_SELECT_INTO and into: 3710 if into.args.get("temporary"): 3711 table_kind = " TEMPORARY" 3712 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 3713 table_kind = " UNLOGGED" 3714 else: 3715 table_kind = "" 3716 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 3717 3718 return sql 3719 3720 def schema_sql(self, expression: exp.Schema) -> str: 3721 this = self.sql(expression, "this") 3722 sql = self.schema_columns_sql(expression) 3723 return f"{this} {sql}" if this and sql else this or sql 3724 3725 def schema_columns_sql(self, expression: exp.Expr) -> str: 3726 if expression.expressions: 3727 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 3728 return "" 3729 3730 def star_sql(self, expression: exp.Star) -> str: 3731 except_ = self.expressions(expression, key="except_", flat=True) 3732 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 3733 replace = self.expressions(expression, key="replace", flat=True) 3734 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 3735 rename = self.expressions(expression, key="rename", flat=True) 3736 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 3737 ilike = self.sql(expression, "ilike") 3738 ilike = f"{self.seg('ILIKE')} {ilike}" if ilike else "" 3739 return f"*{ilike}{except_}{replace}{rename}" 3740 3741 def parameter_sql(self, expression: exp.Parameter) -> str: 3742 this = self.sql(expression, "this") 3743 return f"{self.PARAMETER_TOKEN}{this}" 3744 3745 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 3746 this = self.sql(expression, "this") 3747 kind = expression.text("kind") 3748 if kind: 3749 kind = f"{kind}." 3750 return f"@@{kind}{this}" 3751 3752 def placeholder_sql(self, expression: exp.Placeholder) -> str: 3753 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 3754 3755 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 3756 alias = self.sql(expression, "alias") 3757 alias = f"{sep}{alias}" if alias else "" 3758 sample = self.sql(expression, "sample") 3759 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 3760 alias = f"{sample}{alias}" 3761 3762 # Set to None so it's not generated again by self.query_modifiers() 3763 expression.set("sample", None) 3764 3765 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3766 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 3767 return self.prepend_ctes(expression, sql) 3768 3769 def qualify_sql(self, expression: exp.Qualify) -> str: 3770 this = self.indent(self.sql(expression, "this")) 3771 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 3772 3773 def unnest_sql(self, expression: exp.Unnest) -> str: 3774 args = self.expressions(expression, flat=True) 3775 3776 alias = expression.args.get("alias") 3777 offset = expression.args.get("offset") 3778 3779 if self.UNNEST_WITH_ORDINALITY: 3780 if alias and isinstance(offset, exp.Expr): 3781 alias.append("columns", offset) 3782 expression.set("offset", None) 3783 3784 if alias and self.dialect.UNNEST_COLUMN_ONLY: 3785 columns = alias.columns 3786 alias = self.sql(columns[0]) if columns else "" 3787 else: 3788 alias = self.sql(alias) 3789 3790 alias = f" AS {alias}" if alias else alias 3791 if self.UNNEST_WITH_ORDINALITY: 3792 suffix = f" WITH ORDINALITY{alias}" if offset else alias 3793 else: 3794 if isinstance(offset, exp.Expr): 3795 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 3796 elif offset: 3797 suffix = f"{alias} WITH OFFSET" 3798 else: 3799 suffix = alias 3800 3801 return f"UNNEST({args}){suffix}" 3802 3803 def prewhere_sql(self, expression: exp.PreWhere) -> str: 3804 return "" 3805 3806 def where_sql(self, expression: exp.Where) -> str: 3807 this = self.indent(self.sql(expression, "this")) 3808 return f"{self.seg('WHERE')}{self.sep()}{this}" 3809 3810 def window_sql(self, expression: exp.Window) -> str: 3811 if ( 3812 isinstance(expression.this, exp.Variance) 3813 and expression.this.args.get("single_value_returns_zero") 3814 and expression.text("over") != "KEEP" 3815 and not self.VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE 3816 ): 3817 return self.variance_sql(expression.this, window=expression) 3818 3819 this = self.sql(expression, "this") 3820 partition = self.partition_by_sql(expression) 3821 order = expression.args.get("order") 3822 if not order and self.WINDOW_FUNCS_REQUIRING_ORDER and not expression.args.get("alias"): 3823 func = expression.this 3824 if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)): 3825 func = func.this 3826 if isinstance(func, self.WINDOW_FUNCS_REQUIRING_ORDER): 3827 # Without an ordering all rows of a partition are peers, which is 3828 # also the case when ordering by the partition keys themselves 3829 partition_by = expression.args.get("partition_by") 3830 order = exp.Order( 3831 expressions=[e.copy() for e in partition_by] if partition_by else [exp.null()] 3832 ) 3833 order = self.order_sql(order, flat=True) if order else "" 3834 spec = self.sql(expression, "spec") 3835 alias = self.sql(expression, "alias") 3836 over = self.sql(expression, "over") or "OVER" 3837 3838 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 3839 3840 first = expression.args.get("first") 3841 if first is None: 3842 first = "" 3843 else: 3844 first = "FIRST" if first else "LAST" 3845 3846 if not partition and not order and not spec and alias: 3847 # WINDOW w2 AS w1 is unparseable in DuckDB/Postgres; parens are required. 3848 if expression.arg_key == "windows": 3849 return f"{this} ({alias})" 3850 return f"{this} {alias}" 3851 3852 args = self.format_args( 3853 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 3854 ) 3855 return f"{this} ({args})" 3856 3857 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 3858 partition = self.expressions(expression, key="partition_by", flat=True) 3859 return f"PARTITION BY {partition}" if partition else "" 3860 3861 def partitionbyexcluding_sql(self, expression: exp.PartitionByExcluding) -> str: 3862 return f"EXCLUDING {self.expressions(expression, flat=True)}" 3863 3864 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 3865 kind = self.sql(expression, "kind") 3866 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 3867 end = ( 3868 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 3869 or "CURRENT ROW" 3870 ) 3871 3872 window_spec = f"{kind} BETWEEN {start} AND {end}" 3873 3874 exclude = self.sql(expression, "exclude") 3875 if exclude: 3876 if self.SUPPORTS_WINDOW_EXCLUDE: 3877 window_spec += f" EXCLUDE {exclude}" 3878 else: 3879 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 3880 3881 return window_spec 3882 3883 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 3884 this = self.sql(expression, "this") 3885 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 3886 return f"{this} WITHIN GROUP ({expression_sql})" 3887 3888 def between_sql(self, expression: exp.Between) -> str: 3889 this = self.sql(expression, "this") 3890 low = self.sql(expression, "low") 3891 high = self.sql(expression, "high") 3892 symmetric = expression.args.get("symmetric") 3893 3894 if symmetric and not self.SUPPORTS_BETWEEN_FLAGS: 3895 return f"({this} BETWEEN {low} AND {high} OR {this} BETWEEN {high} AND {low})" 3896 3897 flag = ( 3898 " SYMMETRIC" 3899 if symmetric 3900 else " ASYMMETRIC" 3901 if symmetric is False and self.SUPPORTS_BETWEEN_FLAGS 3902 else "" # silently drop ASYMMETRIC – semantics identical 3903 ) 3904 return f"{this} BETWEEN{flag} {low} AND {high}" 3905 3906 def bracket_offset_expressions( 3907 self, expression: exp.Bracket, index_offset: int | None = None 3908 ) -> list[exp.Expr]: 3909 if expression.args.get("json_access"): 3910 return expression.expressions 3911 3912 return apply_index_offset( 3913 expression.this, 3914 expression.expressions, 3915 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 3916 dialect=self.dialect, 3917 ) 3918 3919 def bracket_sql(self, expression: exp.Bracket) -> str: 3920 expressions = self.bracket_offset_expressions(expression) 3921 expressions_sql = ", ".join(self.sql(e) for e in expressions) 3922 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 3923 3924 def all_sql(self, expression: exp.All) -> str: 3925 this = self.sql(expression, "this") 3926 if not isinstance(expression.this, (exp.Tuple, exp.Paren)): 3927 this = self.wrap(this) 3928 return f"ALL {this}" 3929 3930 def any_sql(self, expression: exp.Any) -> str: 3931 this = self.sql(expression, "this") 3932 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 3933 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 3934 this = self.wrap(this) 3935 return f"ANY{this}" 3936 return f"ANY {this}" 3937 3938 def exists_sql(self, expression: exp.Exists) -> str: 3939 predicate = expression.expression 3940 if not predicate: 3941 return f"EXISTS{self.wrap(expression)}" 3942 3943 # Spark's EXISTS(array, lambda) 3944 if self.CAN_IMPLEMENT_ARRAY_ANY: 3945 filtered = exp.ArrayFilter(this=expression.this, expression=predicate) 3946 return self.sql(exp.paren(exp.ArraySize(this=filtered).neq(0))) 3947 3948 self.unsupported("EXISTS with a lambda predicate is unsupported") 3949 return self.function_fallback_sql(expression) 3950 3951 def case_sql(self, expression: exp.Case) -> str: 3952 this = self.sql(expression, "this") 3953 statements = [f"CASE {this}" if this else "CASE"] 3954 3955 for e in expression.args["ifs"]: 3956 statements.append(f"WHEN {self.sql(e, 'this')}") 3957 statements.append(f"THEN {self.sql(e, 'true')}") 3958 3959 default = self.sql(expression, "default") 3960 3961 if default: 3962 statements.append(f"ELSE {default}") 3963 3964 statements.append("END") 3965 3966 if self.pretty and self.too_wide(statements): 3967 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 3968 3969 return " ".join(statements) 3970 3971 def constraint_sql(self, expression: exp.Constraint) -> str: 3972 this = self.sql(expression, "this") 3973 expressions = self.expressions(expression, flat=True) 3974 return f"CONSTRAINT {this} {expressions}" 3975 3976 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 3977 order = expression.args.get("order") 3978 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 3979 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 3980 3981 def dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 3982 if bool(expression.args.get("zero_based")) == self.DAYOFWEEK_ZERO_BASED: 3983 return self._native_dayofweek_sql(expression) 3984 3985 adjusted = expression + 1 if self.DAYOFWEEK_ZERO_BASED else expression - 1 3986 adjusted.this.set("zero_based", self.DAYOFWEEK_ZERO_BASED) 3987 # The outer DayOfWeek already emits the function's comments. 3988 adjusted.this.pop_comments() 3989 return self.sql(exp.paren(adjusted, copy=False)) 3990 3991 def _native_dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 3992 return self.func(self.DAYOFWEEK_NAME or self.function_name(expression), expression.this) 3993 3994 def extract_date_part(self, part: exp.Expr) -> exp.Expr: 3995 mapping = self.dialect.EXTRACT_DATE_PART_MAPPING 3996 if self.NORMALIZE_EXTRACT_DATE_PARTS and part.name.upper() not in mapping: 3997 mapping = self.dialect.DATE_PART_MAPPING 3998 if mapping: 3999 import sqlglot.dialects.dialect 4000 4001 return sqlglot.dialects.dialect.map_date_part(part, mapping=mapping) 4002 return part 4003 4004 def extract_sql(self, expression: exp.Extract) -> str: 4005 this = self.extract_date_part(expression.this) 4006 if self.EXTRACT_ALLOWS_QUOTES: 4007 this_sql = self.sql(this) 4008 elif isinstance(this, exp.WeekStart): 4009 this_sql = self.weekstart_name(this) 4010 else: 4011 this_sql = this.name 4012 expression_sql = self.sql(expression, "expression") 4013 4014 return f"EXTRACT({this_sql} FROM {expression_sql})" 4015 4016 def trim_sql(self, expression: exp.Trim) -> str: 4017 trim_type = self.sql(expression, "position") 4018 4019 if trim_type == "LEADING": 4020 func_name = "LTRIM" 4021 elif trim_type == "TRAILING": 4022 func_name = "RTRIM" 4023 else: 4024 func_name = "TRIM" 4025 4026 return self.func(func_name, expression.this, expression.expression) 4027 4028 def convert_concat_args(self, expression: exp.Func) -> list[exp.Expr]: 4029 args = expression.expressions 4030 if isinstance(expression, exp.ConcatWs): 4031 args = args[1:] # Skip the delimiter 4032 4033 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 4034 args = [exp.cast(e, exp.DType.TEXT) for e in args] 4035 4036 concat_coalesce = ( 4037 self.dialect.CONCAT_WS_COALESCE 4038 if isinstance(expression, exp.ConcatWs) 4039 else self.dialect.CONCAT_COALESCE 4040 ) 4041 4042 if not concat_coalesce and expression.args.get("coalesce"): 4043 4044 def _wrap_with_coalesce(e: exp.Expr) -> exp.Expr: 4045 if not e.type: 4046 import sqlglot.optimizer.annotate_types 4047 4048 e = sqlglot.optimizer.annotate_types.annotate_types(e, dialect=self.dialect) 4049 4050 if e.is_string or e.is_type(exp.DType.ARRAY): 4051 return e 4052 4053 return exp.func("coalesce", e, exp.Literal.string("")) 4054 4055 args = [_wrap_with_coalesce(e) for e in args] 4056 4057 return args 4058 4059 def concat_sql(self, expression: exp.Concat) -> str: 4060 if self.dialect.CONCAT_COALESCE and not expression.args.get("coalesce"): 4061 # Dialect's CONCAT function coalesces NULLs to empty strings, but the expression does not. 4062 # Transpile to double pipe operators, which typically returns NULL if any args are NULL 4063 # instead of coalescing them to empty string. 4064 import sqlglot.dialects.dialect 4065 4066 return sqlglot.dialects.dialect.concat_to_dpipe_sql(self, expression) 4067 4068 expressions = self.convert_concat_args(expression) 4069 4070 # Some dialects don't allow a single-argument CONCAT call 4071 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 4072 return self.sql(expressions[0]) 4073 4074 return self.func("CONCAT", *expressions) 4075 4076 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4077 if self.dialect.CONCAT_WS_COALESCE and not expression.args.get("coalesce"): 4078 # Dialect's CONCAT_WS function skips NULL args, but the expression does not. 4079 # Wrap the entire call in a CASE expression that returns NULL if any input IS NULL. 4080 all_args = expression.expressions 4081 expression.set("coalesce", True) 4082 return self.sql( 4083 exp.case() 4084 .when(exp.or_(*(arg.is_(exp.null()) for arg in all_args)), exp.null()) 4085 .else_(expression) 4086 ) 4087 4088 return self.func( 4089 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 4090 ) 4091 4092 def check_sql(self, expression: exp.Check) -> str: 4093 this = self.sql(expression, key="this") 4094 return f"CHECK ({this})" 4095 4096 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 4097 this = self.sql(expression, "this") 4098 this = f" {this}" if this else "" 4099 expressions = self.expressions(expression, flat=True) 4100 expressions = f" ({expressions})" if expressions else "" 4101 reference = self.sql(expression, "reference") 4102 reference = f" {reference}" if reference else "" 4103 delete = self.sql(expression, "delete") 4104 delete = f" ON DELETE {delete}" if delete else "" 4105 update = self.sql(expression, "update") 4106 update = f" ON UPDATE {update}" if update else "" 4107 options = self.expressions(expression, key="options", flat=True, sep=" ") 4108 options = f" {options}" if options else "" 4109 return f"FOREIGN KEY{this}{expressions}{reference}{delete}{update}{options}" 4110 4111 def primarykey_sql(self, expression: exp.PrimaryKey) -> str: 4112 this = self.sql(expression, "this") 4113 this = f" {this}" if this else "" 4114 expressions = self.expressions(expression, flat=True) 4115 include = self.sql(expression, "include") 4116 options = self.expressions(expression, key="options", flat=True, sep=" ") 4117 options = f" {options}" if options else "" 4118 return f"PRIMARY KEY{this} ({expressions}){include}{options}" 4119 4120 def timeserieskey_sql(self, expression: exp.TimeseriesKey) -> str: 4121 self.unsupported("TIMESERIES primary key columns are not supported") 4122 return self.sql(expression, "this") 4123 4124 def if_sql(self, expression: exp.If) -> str: 4125 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 4126 4127 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 4128 if self.MATCH_AGAINST_TABLE_PREFIX: 4129 expressions = [] 4130 for expr in expression.expressions: 4131 if isinstance(expr, exp.Table): 4132 expressions.append(f"TABLE {self.sql(expr)}") 4133 else: 4134 expressions.append(expr) 4135 else: 4136 expressions = expression.expressions 4137 4138 modifier = expression.args.get("modifier") 4139 modifier = f" {modifier}" if modifier else "" 4140 return ( 4141 f"{self.func('MATCH', *expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 4142 ) 4143 4144 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 4145 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 4146 4147 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 4148 path = self.expressions(expression, sep="", flat=True).lstrip(".") 4149 4150 if self.QUOTE_JSON_PATH: 4151 path = self.escape_str(path) 4152 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 4153 4154 return path 4155 4156 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 4157 if isinstance(expression, exp.JSONPathPart): 4158 transform = self.TRANSFORMS.get(expression.__class__) 4159 if not callable(transform): 4160 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 4161 return "" 4162 4163 return transform(self, expression) 4164 4165 if isinstance(expression, int): 4166 return str(expression) 4167 4168 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 4169 escaped = expression.replace("'", "\\'") 4170 escaped = f"'{escaped}'" 4171 else: 4172 escaped = expression.replace('"', '\\"') 4173 escaped = f'"{escaped}"' 4174 4175 return escaped 4176 4177 def format_sql(self, expression: exp.Format) -> str: 4178 if ( 4179 expression.args.get("is_fmt") 4180 and expression.this.is_string 4181 and not expression.expressions 4182 and not any(c in expression.name for c in "{}") 4183 ): 4184 return self.sql(expression.this) 4185 4186 self._warn_unsupported_arg(expression, "is_fmt") 4187 return self.function_fallback_sql(expression) 4188 4189 def formatjson_sql(self, expression: exp.FormatJson) -> str: 4190 return f"{self.sql(expression, 'this')} FORMAT JSON" 4191 4192 def formatphrase_sql(self, expression: exp.FormatPhrase) -> str: 4193 # Output the Teradata column FORMAT override. 4194 # https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT 4195 this = self.sql(expression, "this") 4196 fmt = self.sql(expression, "format") 4197 return f"{this} (FORMAT {fmt})" 4198 4199 def teradataconversion_sql(self, expression: exp.TeradataConversion) -> str: 4200 self.unsupported("Teradata postfix conversion semantics are not supported") 4201 return self.sql(exp.cast(expression.this, expression.args["to"])) 4202 4203 def teradatatitle_sql(self, expression: exp.TeradataTitle) -> str: 4204 self.unsupported("Teradata TITLE display headings are not supported") 4205 return self.sql(expression, "this") 4206 4207 def teradatanamed_sql(self, expression: exp.TeradataNamed) -> str: 4208 self.unsupported("Teradata NAMED on subexpressions is not supported") 4209 return self.sql(expression, "this") 4210 4211 def _jsonobject_sql( 4212 self, expression: exp.JSONObject | exp.JSONObjectAgg, name: str = "" 4213 ) -> str: 4214 null_handling = expression.args.get("null_handling") 4215 null_handling = f" {null_handling}" if null_handling else "" 4216 4217 unique_keys = expression.args.get("unique_keys") 4218 if unique_keys is not None: 4219 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 4220 else: 4221 unique_keys = "" 4222 4223 return_type = self.sql(expression, "return_type") 4224 return_type = f" RETURNING {return_type}" if return_type else "" 4225 encoding = self.sql(expression, "encoding") 4226 encoding = f" ENCODING {encoding}" if encoding else "" 4227 4228 if not name: 4229 name = "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG" 4230 4231 return self.func( 4232 name, 4233 *expression.expressions, 4234 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 4235 ) 4236 4237 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 4238 null_handling = expression.args.get("null_handling") 4239 null_handling = f" {null_handling}" if null_handling else "" 4240 return_type = self.sql(expression, "return_type") 4241 return_type = f" RETURNING {return_type}" if return_type else "" 4242 strict = " STRICT" if expression.args.get("strict") else "" 4243 return self.func( 4244 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 4245 ) 4246 4247 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 4248 this = self.sql(expression, "this") 4249 order = self.sql(expression, "order") 4250 null_handling = expression.args.get("null_handling") 4251 null_handling = f" {null_handling}" if null_handling else "" 4252 return_type = self.sql(expression, "return_type") 4253 return_type = f" RETURNING {return_type}" if return_type else "" 4254 strict = " STRICT" if expression.args.get("strict") else "" 4255 return self.func( 4256 "JSON_ARRAYAGG", 4257 this, 4258 suffix=f"{order}{null_handling}{return_type}{strict})", 4259 ) 4260 4261 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 4262 path = self.sql(expression, "path") 4263 path = f" PATH {path}" if path else "" 4264 nested_schema = self.sql(expression, "nested_schema") 4265 4266 if nested_schema: 4267 return f"NESTED{path} {nested_schema}" 4268 4269 this = self.sql(expression, "this") 4270 kind = self.sql(expression, "kind") 4271 kind = f" {kind}" if kind else "" 4272 format_json = " FORMAT JSON" if expression.args.get("format_json") else "" 4273 4274 ordinality = " FOR ORDINALITY" if expression.args.get("ordinality") else "" 4275 return f"{this}{kind}{format_json}{path}{ordinality}" 4276 4277 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 4278 return self.func("COLUMNS", *expression.expressions) 4279 4280 def jsontable_sql(self, expression: exp.JSONTable) -> str: 4281 this = self.sql(expression, "this") 4282 path = self.sql(expression, "path") 4283 path = f", {path}" if path else "" 4284 error_handling = expression.args.get("error_handling") 4285 error_handling = f" {error_handling}" if error_handling else "" 4286 empty_handling = expression.args.get("empty_handling") 4287 empty_handling = f" {empty_handling}" if empty_handling else "" 4288 schema = self.sql(expression, "schema") 4289 return self.func( 4290 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 4291 ) 4292 4293 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 4294 this = self.sql(expression, "this") 4295 kind = self.sql(expression, "kind") 4296 path = self.sql(expression, "path") 4297 path = f" {path}" if path else "" 4298 as_json = " AS JSON" if expression.args.get("as_json") else "" 4299 return f"{this} {kind}{path}{as_json}" 4300 4301 def openjson_sql(self, expression: exp.OpenJSON) -> str: 4302 this = self.sql(expression, "this") 4303 path = self.sql(expression, "path") 4304 path = f", {path}" if path else "" 4305 expressions = self.expressions(expression) 4306 with_ = ( 4307 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 4308 if expressions 4309 else "" 4310 ) 4311 return f"OPENJSON({this}{path}){with_}" 4312 4313 def in_sql(self, expression: exp.In) -> str: 4314 query = expression.args.get("query") 4315 unnest = expression.args.get("unnest") 4316 field = expression.args.get("field") 4317 is_global = " GLOBAL" if expression.args.get("is_global") else "" 4318 4319 if query: 4320 in_sql = self.sql(query) 4321 elif unnest: 4322 in_sql = self.in_unnest_op(unnest) 4323 elif field: 4324 in_sql = self.sql(field) 4325 else: 4326 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 4327 4328 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 4329 4330 def in_unnest_op(self, unnest: exp.Unnest) -> str: 4331 return f"(SELECT {self.sql(unnest)})" 4332 4333 def interval_sql(self, expression: exp.Interval) -> str: 4334 include_keyword = not self.AUTO_REFRESH_BARE_INTERVALS or not isinstance( 4335 expression.find_ancestor(exp.AutoRefreshProperty, exp.Select), 4336 exp.AutoRefreshProperty, 4337 ) 4338 interval_keyword = "INTERVAL" if include_keyword else "" 4339 unit_expression = expression.args.get("unit") 4340 unit = self.sql(unit_expression) if unit_expression else "" 4341 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 4342 unit = self.TIME_PART_SINGULARS.get(unit, unit) 4343 unit = f" {unit}" if unit else "" 4344 4345 if self.SINGLE_STRING_INTERVAL: 4346 this = expression.this.name if expression.this else "" 4347 if this: 4348 interval_keyword = f"{interval_keyword} " if interval_keyword else "" 4349 if unit_expression and isinstance(unit_expression, exp.IntervalSpan): 4350 return f"{interval_keyword}{self.sql(exp.Literal.string(this))}{unit}" 4351 return f"{interval_keyword}{self.sql(exp.Literal.string(f'{this}{unit}'))}" 4352 return f"{interval_keyword}{unit}" 4353 4354 this = self.sql(expression, "this") 4355 if this: 4356 if not include_keyword and expression.this.is_string: 4357 this = expression.this.name 4358 if not isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES): 4359 this = f"({this})" 4360 if include_keyword: 4361 this = f" {this}" 4362 4363 return f"{interval_keyword}{this}{unit}" 4364 4365 def return_sql(self, expression: exp.Return) -> str: 4366 return f"RETURN {self.sql(expression, 'this')}" 4367 4368 def reference_sql(self, expression: exp.Reference) -> str: 4369 this = self.sql(expression, "this") 4370 expressions = self.expressions(expression, flat=True) 4371 expressions = f"({expressions})" if expressions else "" 4372 options = self.expressions(expression, key="options", flat=True, sep=" ") 4373 options = f" {options}" if options else "" 4374 return f"REFERENCES {this}{expressions}{options}" 4375 4376 def anonymous_sql(self, expression: exp.Anonymous) -> str: 4377 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 4378 parent = expression.parent 4379 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 4380 4381 return self.func( 4382 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 4383 ) 4384 4385 def paren_sql(self, expression: exp.Paren) -> str: 4386 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 4387 return f"({sql}{self.seg(')', sep='')}" 4388 4389 def pos_sql(self, expression: exp.Pos) -> str: 4390 return f"+{self.sql(expression, 'this')}" 4391 4392 def neg_sql(self, expression: exp.Neg) -> str: 4393 # This makes sure we don't convert "- - 5" to "--5", which is a comment 4394 this_sql = self.sql(expression, "this") 4395 sep = " " if this_sql[0] == "-" else "" 4396 return f"-{sep}{this_sql}" 4397 4398 def not_sql(self, expression: exp.Not) -> str: 4399 return f"NOT {self.sql(expression, 'this')}" 4400 4401 def alias_sql(self, expression: exp.Alias) -> str: 4402 alias = self.sql(expression, "alias") 4403 alias = f" AS {alias}" if alias else "" 4404 return f"{self.sql(expression, 'this')}{alias}" 4405 4406 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 4407 alias = expression.args["alias"] 4408 4409 parent = expression.parent 4410 pivot = parent and parent.parent 4411 4412 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 4413 identifier_alias = isinstance(alias, exp.Identifier) 4414 literal_alias = isinstance(alias, exp.Literal) 4415 4416 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4417 alias.replace(exp.Literal.string(alias.output_name)) 4418 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4419 alias.replace(exp.to_identifier(alias.output_name)) 4420 4421 return self.alias_sql(expression) 4422 4423 def aliases_sql(self, expression: exp.Aliases) -> str: 4424 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 4425 4426 def atindex_sql(self, expression: exp.AtIndex) -> str: 4427 this = self.sql(expression, "this") 4428 index = self.sql(expression, "expression") 4429 return f"{this} AT {index}" 4430 4431 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 4432 this = self.sql(expression, "this") 4433 zone = self.sql(expression, "zone") 4434 return f"{this} AT TIME ZONE {zone}" 4435 4436 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 4437 this = self.sql(expression, "this") 4438 zone = self.sql(expression, "zone") 4439 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 4440 4441 def fromiso8601date_sql(self, expression: exp.FromISO8601Date) -> str: 4442 return self.sql(exp.cast(expression.this, exp.DType.DATE)) 4443 4444 def fromiso8601timestamp_sql(self, expression: exp.FromISO8601Timestamp) -> str: 4445 return self.sql(exp.cast(expression.this, exp.DType.TIMESTAMPTZ)) 4446 4447 def fromiso8601timestampnanos_sql(self, expression: exp.FromISO8601TimestampNanos) -> str: 4448 return self.sql(exp.cast(expression.this, exp.DType.TIMESTAMPTZ)) 4449 4450 def add_sql(self, expression: exp.Add) -> str: 4451 return self.binary(expression, "+") 4452 4453 def and_sql(self, expression: exp.And, stack: list[str | exp.Expr] | None = None) -> str: 4454 return self.connector_sql(expression, "AND", stack) 4455 4456 def or_sql(self, expression: exp.Or, stack: list[str | exp.Expr] | None = None) -> str: 4457 return self.connector_sql(expression, "OR", stack) 4458 4459 def xor_sql(self, expression: exp.Xor, stack: list[str | exp.Expr] | None = None) -> str: 4460 return self.connector_sql(expression, "XOR", stack) 4461 4462 def connector_sql( 4463 self, 4464 expression: exp.Connector, 4465 op: str, 4466 stack: list[str | exp.Expr] | None = None, 4467 ) -> str: 4468 if stack is not None: 4469 stack.append(expression.right) 4470 if expression.comments and self.comments: 4471 op = self.maybe_comment(op, comments=expression.comments) 4472 4473 stack.extend((op, expression.left)) 4474 return op 4475 4476 stack = [expression] 4477 sqls: list[str] = [] 4478 ops = set() 4479 4480 while stack: 4481 node = stack.pop() 4482 if isinstance(node, exp.Connector): 4483 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 4484 else: 4485 sql = self.sql(node) 4486 if sqls and sqls[-1] in ops: 4487 sqls[-1] += f" {sql}" 4488 else: 4489 sqls.append(sql) 4490 4491 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 4492 return sep.join(sqls) 4493 4494 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 4495 return self.binary(expression, "&") 4496 4497 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 4498 return self.binary(expression, "<<") 4499 4500 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 4501 return f"~{self.sql(expression, 'this')}" 4502 4503 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 4504 return self.binary(expression, "|") 4505 4506 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 4507 return self.binary(expression, ">>") 4508 4509 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 4510 return self.binary(expression, "^") 4511 4512 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 4513 format_sql = self.sql(expression, "format") 4514 format_sql = f" FORMAT {format_sql}" if format_sql else "" 4515 to_sql = self.sql(expression, "to") 4516 to_sql = f" {to_sql}" if to_sql else "" 4517 action = self.sql(expression, "action") 4518 action = f" {action}" if action else "" 4519 default = self.sql(expression, "default") 4520 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 4521 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 4522 4523 # Base implementation that excludes safe, zone, and target_type metadata args 4524 def strtotime_sql(self, expression: exp.StrToTime) -> str: 4525 return self.func("STR_TO_TIME", expression.this, expression.args.get("format")) 4526 4527 # Base implementation that excludes the safe and default_year metadata args 4528 def strtodate_sql(self, expression: exp.StrToDate) -> str: 4529 return self.func("STR_TO_DATE", expression.this, expression.args.get("format")) 4530 4531 def parsedatetime_sql(self, expression: exp.ParseDatetime) -> str: 4532 return self.func( 4533 "PARSE_DATETIME", 4534 expression.this, 4535 expression.args.get("format"), 4536 expression.args.get("zone"), 4537 ) 4538 4539 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 4540 zone = self.sql(expression, "this") 4541 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 4542 4543 def collate_sql(self, expression: exp.Collate) -> str: 4544 if self.COLLATE_IS_FUNC: 4545 return self.function_fallback_sql(expression) 4546 return self.binary(expression, "COLLATE") 4547 4548 def command_sql(self, expression: exp.Command) -> str: 4549 args = expression.text("expression").lstrip() 4550 return f"{self.sql(expression, 'this')} {args}".rstrip(" \t") 4551 4552 def optimize_sql(self, expression: exp.Optimize) -> str: 4553 if not self.SUPPORTS_OPTIMIZE: 4554 self.unsupported("OPTIMIZE is only supported in Databricks") 4555 full = " FULL" if expression.args.get("full") else "" 4556 where = self.sql(expression, "where") 4557 columns = self.expressions(expression, key="zorder", flat=True) 4558 zorder = self.seg(f"ZORDER BY ({columns})") if columns else "" 4559 return f"OPTIMIZE {self.sql(expression, 'this')}{full}{where}{zorder}" 4560 4561 def comment_sql(self, expression: exp.Comment) -> str: 4562 this = self.sql(expression, "this") 4563 kind = expression.args["kind"] 4564 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 4565 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 4566 expression_sql = self.sql(expression, "expression") 4567 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 4568 4569 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 4570 this = self.sql(expression, "this") 4571 delete = " DELETE" if expression.args.get("delete") else "" 4572 recompress = self.sql(expression, "recompress") 4573 recompress = f" RECOMPRESS {recompress}" if recompress else "" 4574 to_disk = self.sql(expression, "to_disk") 4575 to_disk = f" TO DISK {to_disk}" if to_disk else "" 4576 to_volume = self.sql(expression, "to_volume") 4577 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 4578 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 4579 4580 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 4581 where = self.sql(expression, "where") 4582 group = self.sql(expression, "group") 4583 aggregates = self.expressions(expression, key="aggregates") 4584 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 4585 4586 if not (where or group or aggregates) and len(expression.expressions) == 1: 4587 return f"TTL {self.expressions(expression, flat=True)}" 4588 4589 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 4590 4591 def transaction_sql(self, expression: exp.Transaction) -> str: 4592 modes = self.expressions(expression, key="modes") 4593 modes = f" {modes}" if modes else "" 4594 return f"BEGIN{modes}" 4595 4596 def commit_sql(self, expression: exp.Commit) -> str: 4597 chain = expression.args.get("chain") 4598 if chain is not None: 4599 chain = " AND CHAIN" if chain else " AND NO CHAIN" 4600 4601 return f"COMMIT{chain or ''}" 4602 4603 def rollback_sql(self, expression: exp.Rollback) -> str: 4604 savepoint = expression.args.get("savepoint") 4605 savepoint = f" TO {savepoint}" if savepoint else "" 4606 return f"ROLLBACK{savepoint}" 4607 4608 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 4609 this = self.sql(expression, "this") 4610 4611 exists = "" 4612 if expression.args.get("exists"): 4613 if self.SUPPORTS_ALTER_COLUMN_IF_EXISTS: 4614 exists = " IF EXISTS" 4615 else: 4616 self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect") 4617 4618 dtype = self.sql(expression, "dtype") 4619 if dtype: 4620 collate = self.sql(expression, "collate") 4621 collate = f" COLLATE {collate}" if collate else "" 4622 using = self.sql(expression, "using") 4623 using = f" USING {using}" if using else "" 4624 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 4625 null_constraint = self._alter_column_null_constraint_sql(expression) 4626 4627 return ( 4628 f"ALTER COLUMN{exists} {this} {alter_set_type}{dtype}" 4629 f"{collate}{using}{null_constraint}" 4630 ) 4631 4632 default = self.sql(expression, "default") 4633 if default: 4634 return f"ALTER COLUMN{exists} {this} SET DEFAULT {default}" 4635 4636 comment = self.sql(expression, "comment") 4637 if comment: 4638 return f"ALTER COLUMN{exists} {this} COMMENT {comment}" 4639 4640 visible = expression.args.get("visible") 4641 if visible: 4642 return f"ALTER COLUMN{exists} {this} SET {visible}" 4643 4644 allow_null = expression.args.get("allow_null") 4645 drop = expression.args.get("drop") 4646 4647 if not drop and not allow_null: 4648 self.unsupported("Unsupported ALTER COLUMN syntax") 4649 4650 if allow_null is not None: 4651 keyword = "DROP" if drop else "SET" 4652 return f"ALTER COLUMN{exists} {this} {keyword} NOT NULL" 4653 4654 return f"ALTER COLUMN{exists} {this} DROP DEFAULT" 4655 4656 def _alter_column_null_constraint_sql(self, expression: exp.AlterColumn) -> str: 4657 allow_null = expression.args.get("allow_null") 4658 if allow_null is None: 4659 return "" 4660 4661 if not self.SUPPORTS_ALTER_COLUMN_NULLABILITY: 4662 self.unsupported("ALTER COLUMN cannot set nullability along with a type") 4663 return "" 4664 4665 return " NULL" if allow_null else " NOT NULL" 4666 4667 def modifycolumn_sql(self, expression: exp.ModifyColumn) -> str: 4668 this = self.sql(expression, "this") 4669 rename_from = self.sql(expression, "rename_from") 4670 if rename_from: 4671 if not self.SUPPORTS_CHANGE_COLUMN: 4672 self.unsupported("CHANGE COLUMN is not supported in this dialect") 4673 return f"CHANGE COLUMN {rename_from} {this}" 4674 if not self.SUPPORTS_MODIFY_COLUMN: 4675 self.unsupported("MODIFY COLUMN is not supported in this dialect") 4676 return f"MODIFY COLUMN {this}" 4677 4678 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 4679 this = self.sql(expression, "this") 4680 4681 visible = expression.args.get("visible") 4682 visible_sql = "VISIBLE" if visible else "INVISIBLE" 4683 4684 return f"ALTER INDEX {this} {visible_sql}" 4685 4686 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 4687 this = self.sql(expression, "this") 4688 if not isinstance(expression.this, exp.Var): 4689 this = f"KEY DISTKEY {this}" 4690 return f"ALTER DISTSTYLE {this}" 4691 4692 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 4693 compound = " COMPOUND" if expression.args.get("compound") else "" 4694 this = self.sql(expression, "this") 4695 expressions = self.expressions(expression, flat=True) 4696 expressions = f"({expressions})" if expressions else "" 4697 return f"ALTER{compound} SORTKEY {this or expressions}" 4698 4699 def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str: 4700 if not self.RENAME_TABLE_WITH_DB: 4701 # Remove db from tables 4702 expression = expression.transform( 4703 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 4704 ).assert_is(exp.AlterRename) 4705 this = self.sql(expression, "this") 4706 to_kw = " TO" if include_to else "" 4707 return f"RENAME{to_kw} {this}" 4708 4709 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 4710 exists = " IF EXISTS" if expression.args.get("exists") else "" 4711 old_column = self.sql(expression, "this") 4712 new_column = self.sql(expression, "to") 4713 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 4714 4715 def alterset_sql(self, expression: exp.AlterSet) -> str: 4716 exprs = self.expressions(expression, flat=True) 4717 if self.ALTER_SET_WRAPPED: 4718 exprs = f"({exprs})" 4719 4720 return f"SET {exprs}" 4721 4722 def alter_sql(self, expression: exp.Alter) -> str: 4723 actions = expression.actions 4724 4725 if ( 4726 not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN 4727 and actions 4728 and isinstance(actions[0], exp.ColumnDef) 4729 ): 4730 actions_sql = self.expressions(expression, key="actions", flat=True) 4731 actions_sql = f"ADD {actions_sql}" 4732 else: 4733 actions_list = [] 4734 for action in actions: 4735 if isinstance(action, (exp.ColumnDef, exp.Schema)): 4736 action_sql = self.add_column_sql(action) 4737 else: 4738 action_sql = self.sql(action) 4739 if isinstance(action, exp.Query): 4740 action_sql = f"AS {action_sql}" 4741 4742 actions_list.append(action_sql) 4743 4744 actions_sql = self.format_args(*actions_list).lstrip("\n") 4745 4746 iceberg = ( 4747 "ICEBERG " 4748 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 4749 else "" 4750 ) 4751 exists = " IF EXISTS" if expression.args.get("exists") else "" 4752 on_cluster = self.sql(expression, "cluster") 4753 on_cluster = f" {on_cluster}" if on_cluster else "" 4754 only = " ONLY" if expression.args.get("only") else "" 4755 options = expression.args.get("options") or [] 4756 options_sql = self.expressions( 4757 sqls=[o for o in options if not isinstance(o, self.ALTER_PARTITION_OPTIONS)] 4758 ) 4759 options_sql = f", {options_sql}" if options_sql and actions_sql else options_sql 4760 partitions_sql = self.expressions( 4761 sqls=[o for o in options if isinstance(o, self.ALTER_PARTITION_OPTIONS)], 4762 sep=" ", 4763 flat=True, 4764 ) 4765 if partitions_sql and (actions_sql or options_sql): 4766 partitions_sql = f" {partitions_sql}" 4767 kind = self.sql(expression, "kind") 4768 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 4769 check = " WITH CHECK" if expression.args.get("check") else "" 4770 cascade = ( 4771 " CASCADE" 4772 if expression.args.get("cascade") and self.dialect.ALTER_TABLE_SUPPORTS_CASCADE 4773 else "" 4774 ) 4775 this = self.sql(expression, "this") 4776 this = f" {this}" if this else "" 4777 4778 return f"ALTER {iceberg}{kind}{exists}{only}{this}{on_cluster}{check}{self.sep()}{actions_sql}{not_valid}{options_sql}{partitions_sql}{cascade}" 4779 4780 def altersession_sql(self, expression: exp.AlterSession) -> str: 4781 items_sql = self.expressions(expression, flat=True) 4782 keyword = "UNSET" if expression.args.get("unset") else "SET" 4783 return f"{keyword} {items_sql}" 4784 4785 def add_column_sql(self, expression: exp.Expr) -> str: 4786 column_text = "" 4787 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 4788 if isinstance(expression, exp.ColumnDef): 4789 column_text = " COLUMN" 4790 elif isinstance(expression, exp.Schema): 4791 column_text = " COLUMNS" 4792 4793 if isinstance(expression, exp.Schema) and not self.ALTER_TABLE_ADD_COLUMNS_WRAPPED: 4794 sql = self.expressions(expression, flat=True) 4795 else: 4796 sql = self.sql(expression) 4797 4798 return f"ADD{column_text} {sql}" 4799 4800 def droppartition_sql(self, expression: exp.DropPartition) -> str: 4801 expressions = self.expressions(expression) 4802 exists = " IF EXISTS " if expression.args.get("exists") else " " 4803 return f"DROP{exists}{expressions}" 4804 4805 def dropprimarykey_sql(self, expression: exp.DropPrimaryKey) -> str: 4806 return "DROP PRIMARY KEY" 4807 4808 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 4809 return f"ADD {self.expressions(expression, indent=False)}" 4810 4811 def replacecolumns_sql(self, expression: exp.ReplaceColumns) -> str: 4812 return f"REPLACE COLUMNS ({self.expressions(expression, flat=True)})" 4813 4814 def addpartition_sql(self, expression: exp.AddPartition) -> str: 4815 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 4816 location = self.sql(expression, "location") 4817 location = f" {location}" if location else "" 4818 return f"ADD {exists}{self.sql(expression.this)}{location}" 4819 4820 def distinct_sql(self, expression: exp.Distinct) -> str: 4821 this = self.expressions(expression, flat=True) 4822 4823 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 4824 case = exp.case() 4825 for arg in expression.expressions: 4826 case = case.when(arg.is_(exp.null()), exp.null()) 4827 this = self.sql(case.else_(f"({this})")) 4828 4829 this = f" {this}" if this else "" 4830 4831 on = self.sql(expression, "on") 4832 on = f" ON {on}" if on else "" 4833 return f"DISTINCT{this}{on}" 4834 4835 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 4836 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 4837 4838 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 4839 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 4840 4841 def havingmax_sql(self, expression: exp.HavingMax) -> str: 4842 this_sql = self.sql(expression, "this") 4843 expression_sql = self.sql(expression, "expression") 4844 kind = "MAX" if expression.args.get("max") else "MIN" 4845 return f"{this_sql} HAVING {kind} {expression_sql}" 4846 4847 def intdiv_sql(self, expression: exp.IntDiv) -> str: 4848 if not self.INT_DIV_OPERATOR: 4849 return self._truncated_div_sql(expression.this, expression.expression) 4850 4851 # Integer division binds like %, so those operators chain on its left without parentheses 4852 node: exp.Expr = expression 4853 while isinstance(node, exp.IntDiv): 4854 this = node.this 4855 if not isinstance(this, self.MOD_PAREN_PARENT_TYPES): 4856 node.set("this", exp._wrap(this, exp.Binary)) 4857 node.set("expression", exp._wrap(node.expression, exp.Binary)) 4858 node = this 4859 4860 sql = self.binary(expression, self.INT_DIV_OPERATOR) 4861 4862 parent = expression.parent 4863 if isinstance(parent, (exp.Neg, exp.BitwiseNot)) or ( 4864 isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression 4865 ): 4866 return f"({sql})" 4867 4868 return sql 4869 4870 def _truncated_div_sql(self, this: exp.Expr, divisor: exp.Expr) -> str: 4871 div: exp.Expr = this / divisor 4872 if self.CAST_TO_INT_ROUNDS: 4873 div = exp.Trunc(this=div) 4874 4875 return self.sql(exp.Cast(this=div, to=exp.DataType(this=exp.DType.BIGINT))) 4876 4877 def dpipe_sql(self, expression: exp.DPipe) -> str: 4878 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 4879 return self.func("CONCAT", *(exp.cast(e, exp.DType.TEXT) for e in expression.flatten())) 4880 return self.binary(expression, "||") 4881 4882 def nullif_zero_divisor(self, expression: exp.Div | exp.Mod) -> None: 4883 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 4884 divisor = expression.right 4885 divisor.replace(exp.Nullif(this=divisor.copy(), expression=exp.Literal.number(0))) 4886 4887 def div_sql(self, expression: exp.Div) -> str: 4888 l, r = expression.left, expression.right 4889 self.nullif_zero_divisor(expression) 4890 4891 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 4892 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 4893 l.replace(exp.cast(l.copy(), to=exp.DType.DOUBLE)) 4894 4895 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 4896 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 4897 # Native integer division depends on the target's operand types, which may differ 4898 # from the source's (e.g. FLOOR(int) is DOUBLE in DuckDB), unless the operands are 4899 # integer literals or casts 4900 if all(e.is_int or isinstance(e, exp.Cast) for e in (l, r)) and ( 4901 expression.args.get("safe") or not self.SAFE_INT_DIVISION 4902 ): 4903 return self.sql(exp.IntDiv(this=l, expression=expression.right)) 4904 return self._truncated_div_sql(l, expression.right) 4905 4906 return self.binary(expression, "/") 4907 4908 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 4909 n = exp._wrap(expression.this, exp.Binary) 4910 d = exp._wrap(expression.expression, exp.Binary) 4911 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 4912 4913 def overlaps_sql(self, expression: exp.Overlaps) -> str: 4914 return self.binary(expression, "OVERLAPS") 4915 4916 def distance_sql(self, expression: exp.Distance) -> str: 4917 return self.binary(expression, "<->") 4918 4919 def distancend_sql(self, expression: exp.DistanceNd) -> str: 4920 return self.binary(expression, "<<->>") 4921 4922 def dot_sql(self, expression: exp.Dot) -> str: 4923 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 4924 4925 def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: 4926 if not self.SUPPORTS_NESTED_JSON_SELECT and self.dialect != "": 4927 self.unsupported("Selecting nested JSON objects with .^ is not supported") 4928 return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}" 4929 4930 def eq_sql(self, expression: exp.EQ) -> str: 4931 return self.binary(expression, "=") 4932 4933 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 4934 return self.binary(expression, ":=") 4935 4936 def escape_sql(self, expression: exp.Escape) -> str: 4937 this = expression.this 4938 if ( 4939 isinstance(this, (exp.Like, exp.ILike)) 4940 and isinstance(this.expression, (exp.All, exp.Any)) 4941 and not self.SUPPORTS_LIKE_QUANTIFIERS 4942 ): 4943 return self._like_sql(this, escape=expression) 4944 return self.binary(expression, "ESCAPE") 4945 4946 def glob_sql(self, expression: exp.Glob) -> str: 4947 return self.binary(expression, "GLOB") 4948 4949 def gt_sql(self, expression: exp.GT) -> str: 4950 return self.binary(expression, ">") 4951 4952 def gte_sql(self, expression: exp.GTE) -> str: 4953 return self.binary(expression, ">=") 4954 4955 def is_sql(self, expression: exp.Is) -> str: 4956 negate = expression.args.get("negate") 4957 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 4958 positive = bool(expression.expression.this) != bool(negate) 4959 return self.sql(expression.this if positive else exp.not_(expression.this)) 4960 return self.binary(expression, "IS NOT" if negate else "IS") 4961 4962 def _like_sql( 4963 self, 4964 expression: exp.Like | exp.ILike, 4965 escape: exp.Escape | None = None, 4966 ) -> str: 4967 this = expression.this 4968 rhs = expression.expression 4969 4970 if isinstance(expression, exp.Like): 4971 exp_class: type[exp.Like | exp.ILike] = exp.Like 4972 op = "LIKE" 4973 else: 4974 exp_class = exp.ILike 4975 op = "ILIKE" 4976 4977 if expression.args.get("negate"): 4978 op = f"NOT {op}" 4979 4980 if isinstance(rhs, (exp.All, exp.Any)) and not self.SUPPORTS_LIKE_QUANTIFIERS: 4981 exprs = rhs.this.unnest() 4982 4983 if isinstance(exprs, exp.Tuple): 4984 exprs = exprs.expressions 4985 else: 4986 exprs = [exprs] 4987 4988 connective = exp.or_ if isinstance(rhs, exp.Any) else exp.and_ 4989 4990 def _make_like(expr: exp.Expression) -> exp.Expression: 4991 like: exp.Expression = exp_class( 4992 this=this, expression=expr, negate=expression.args.get("negate") 4993 ) 4994 if escape: 4995 like = exp.Escape(this=like, expression=escape.expression.copy()) 4996 return like 4997 4998 like_expr: exp.Expr = _make_like(exprs[0]) 4999 for expr in exprs[1:]: 5000 like_expr = connective(like_expr, _make_like(expr), copy=False) 5001 5002 parent = escape.parent if escape else expression.parent 5003 if not isinstance(parent, (type(like_expr), exp.Paren)) and isinstance( 5004 parent, exp.Condition 5005 ): 5006 like_expr = exp.paren(like_expr, copy=False) 5007 5008 return self.sql(like_expr) 5009 5010 return self.binary(expression, op) 5011 5012 def like_sql(self, expression: exp.Like) -> str: 5013 return self._like_sql(expression) 5014 5015 def ilike_sql(self, expression: exp.ILike) -> str: 5016 return self._like_sql(expression) 5017 5018 def match_sql(self, expression: exp.Match) -> str: 5019 if expression.args.get("kind") or expression.args.get("analyzer"): 5020 self.unsupported("MATCH variants and USING ANALYZER are not supported in this dialect") 5021 return self.binary(expression, "MATCH") 5022 5023 def similarto_sql(self, expression: exp.SimilarTo) -> str: 5024 return self.binary(expression, "SIMILAR TO") 5025 5026 def lt_sql(self, expression: exp.LT) -> str: 5027 return self.binary(expression, "<") 5028 5029 def lte_sql(self, expression: exp.LTE) -> str: 5030 return self.binary(expression, "<=") 5031 5032 def mod_sql(self, expression: exp.Mod) -> str: 5033 self.nullif_zero_divisor(expression) 5034 this = self.sql(expression, "this") 5035 expr = self.sql(expression, "expression") 5036 sql = f"{this} {self.maybe_comment(self.MOD_OPERATOR, comments=expression.comments)} {expr}" 5037 5038 parent = expression.parent 5039 if isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression: 5040 return f"({sql})" 5041 5042 return sql 5043 5044 def mul_sql(self, expression: exp.Mul) -> str: 5045 return self.binary(expression, "*") 5046 5047 def neq_sql(self, expression: exp.NEQ) -> str: 5048 return self.binary(expression, "<>") 5049 5050 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 5051 return self.binary(expression, "IS NOT DISTINCT FROM") 5052 5053 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 5054 return self.binary(expression, "IS DISTINCT FROM") 5055 5056 def sub_sql(self, expression: exp.Sub) -> str: 5057 return self.binary(expression, "-") 5058 5059 def trycast_sql(self, expression: exp.TryCast) -> str: 5060 return self.cast_sql(expression, safe_prefix="TRY_") 5061 5062 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 5063 return self.cast_sql(expression) 5064 5065 def try_sql(self, expression: exp.Try) -> str: 5066 if not self.TRY_SUPPORTED: 5067 self.unsupported("Unsupported TRY function") 5068 return self.sql(expression, "this") 5069 5070 return self.func("TRY", expression.this) 5071 5072 def log_sql(self, expression: exp.Log) -> str: 5073 this = expression.this 5074 expr = expression.expression 5075 5076 if self.dialect.LOG_BASE_FIRST is False: 5077 this, expr = expr, this 5078 elif self.dialect.LOG_BASE_FIRST is None and expr: 5079 if this.name in ("2", "10"): 5080 return self.func(f"LOG{this.name}", expr) 5081 5082 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 5083 5084 return self.func("LOG", this, expr) 5085 5086 def use_sql(self, expression: exp.Use) -> str: 5087 kind = self.sql(expression, "kind") 5088 kind = f" {kind}" if kind else "" 5089 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 5090 this = f" {this}" if this else "" 5091 return f"USE{kind}{this}" 5092 5093 def binary(self, expression: exp.Binary, op: str) -> str: 5094 sqls: list[str] = [] 5095 stack: list[None | str | exp.Expr] = [expression] 5096 binary_type = type(expression) 5097 is_is = binary_type is exp.Is and op in ("IS", "IS NOT") 5098 negate = expression.args.get("negate") 5099 5100 while stack: 5101 node = stack.pop() 5102 5103 if type(node) is binary_type and ( 5104 node is expression 5105 or (is_is and not isinstance(node.expression, exp.Boolean)) 5106 or node.args.get("negate") == negate 5107 ): 5108 op_func = node.args.get("operator") 5109 if op_func: 5110 op = self.sql(op_func) 5111 if op not in self.BARE_OPERATORS: 5112 op = f"OPERATOR({op})" 5113 elif is_is: 5114 op = "IS NOT" if node.args.get("negate") else "IS" 5115 5116 stack.append(node.args.get("expression")) 5117 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 5118 stack.append(node.args.get("this")) 5119 else: 5120 sqls.append(self.sql(node)) 5121 5122 return "".join(sqls) 5123 5124 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 5125 to_clause = self.sql(expression, "to") 5126 if to_clause: 5127 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 5128 5129 return self.function_fallback_sql(expression) 5130 5131 def function_fallback_sql(self, expression: exp.Func) -> str: 5132 args = [] 5133 5134 for key in expression.arg_types: 5135 arg_value = expression.args.get(key) 5136 5137 if isinstance(arg_value, list): 5138 for value in arg_value: 5139 args.append(value) 5140 elif arg_value is not None: 5141 args.append(arg_value) 5142 5143 return self.func(self.function_name(expression), *args) 5144 5145 def function_name(self, expression: exp.Func) -> str: 5146 name_key = self.dialect.ORIGINAL_NAME_META_KEY 5147 return (expression.meta_get(name_key) if name_key else None) or expression.sql_name() 5148 5149 def func( 5150 self, 5151 name: str, 5152 *args: t.Any, 5153 prefix: str = "(", 5154 suffix: str = ")", 5155 normalize: bool = True, 5156 ) -> str: 5157 name = self.normalize_func(name) if normalize else name 5158 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 5159 5160 def format_args(self, *args: t.Any, sep: str = ", ") -> str: 5161 arg_sqls = tuple( 5162 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 5163 ) 5164 if self.pretty and self.too_wide(arg_sqls): 5165 return self.indent( 5166 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 5167 ) 5168 return sep.join(arg_sqls) 5169 5170 def too_wide(self, args: t.Iterable) -> bool: 5171 return sum(len(arg) for arg in args) > self.max_text_width 5172 5173 def format_time( 5174 self, 5175 expression: exp.Expr, 5176 inverse_time_mapping: dict[str, str] | None = None, 5177 inverse_time_trie: dict | None = None, 5178 ) -> str | None: 5179 return format_time( 5180 self.sql(expression, "format"), 5181 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 5182 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 5183 ) 5184 5185 def expressions( 5186 self, 5187 expression: exp.Expr | None = None, 5188 key: str | None = None, 5189 sqls: t.Collection[str | exp.Expr] | None = None, 5190 flat: bool = False, 5191 indent: bool = True, 5192 skip_first: bool = False, 5193 skip_last: bool = False, 5194 sep: str = ", ", 5195 prefix: str = "", 5196 dynamic: bool = False, 5197 new_line: bool = False, 5198 ) -> str: 5199 expressions = expression.args.get(key or "expressions") if expression else sqls 5200 5201 if not expressions: 5202 return "" 5203 5204 if flat: 5205 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 5206 5207 num_sqls = len(expressions) 5208 result_sqls = [] 5209 5210 for i, e in enumerate(expressions): 5211 sql = self.sql(e, comment=False) 5212 if not sql: 5213 continue 5214 5215 comments = self.maybe_comment("", e) if isinstance(e, exp.Expr) else "" 5216 5217 if self.pretty: 5218 if self.leading_comma: 5219 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 5220 else: 5221 result_sqls.append( 5222 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 5223 ) 5224 else: 5225 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 5226 5227 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 5228 if new_line: 5229 result_sqls.insert(0, "") 5230 result_sqls.append("") 5231 result_sql = "\n".join(s.rstrip() for s in result_sqls) 5232 else: 5233 result_sql = "".join(result_sqls) 5234 5235 return ( 5236 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 5237 if indent 5238 else result_sql 5239 ) 5240 5241 def op_expressions(self, op: str, expression: exp.Expr, flat: bool = False) -> str: 5242 flat = flat or isinstance(expression.parent, exp.Properties) 5243 expressions_sql = self.expressions(expression, flat=flat) 5244 if flat: 5245 return f"{op} {expressions_sql}" 5246 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 5247 5248 def naked_property(self, expression: exp.Property) -> str: 5249 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 5250 if not property_name: 5251 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 5252 return f"{property_name} {self.sql(expression, 'this')}" 5253 5254 def tag_sql(self, expression: exp.Tag) -> str: 5255 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 5256 5257 def token_sql(self, token_type: TokenType) -> str: 5258 return self.TOKEN_MAPPING.get(token_type, token_type.name) 5259 5260 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 5261 this = self.sql(expression, "this") 5262 expressions = self.no_identify(self.expressions, expression) 5263 expressions = ( 5264 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 5265 ) 5266 return f"{this}{expressions}" if expressions.strip() != "" else this 5267 5268 def macrooverloads_sql(self, expression: exp.MacroOverloads) -> str: 5269 return self.expressions(expression, flat=True) 5270 5271 def macrooverload_sql(self, expression: exp.MacroOverload) -> str: 5272 params = self.no_identify(self.expressions, expression, flat=True) 5273 body = self.sql(expression, "this") 5274 prefix = "TABLE " if expression.args.get("is_table") else "" 5275 return f"({params}) AS {prefix}{body}" 5276 5277 def joinhint_sql(self, expression: exp.JoinHint) -> str: 5278 this = self.sql(expression, "this") 5279 expressions = self.expressions(expression, flat=True) 5280 return f"{this}({expressions})" 5281 5282 def kwarg_sql(self, expression: exp.Kwarg) -> str: 5283 return self.binary(expression, "=>") 5284 5285 def when_sql(self, expression: exp.When) -> str: 5286 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 5287 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 5288 condition = self.sql(expression, "condition") 5289 condition = f" AND {condition}" if condition else "" 5290 5291 then_expression = expression.args.get("then") 5292 if isinstance(then_expression, exp.Insert): 5293 this = ( 5294 "ALL BY NAME" 5295 if self.MERGE_ALL_BY_NAME and isinstance(then_expression.this, exp.Star) 5296 else self.sql(then_expression, "this") 5297 ) 5298 this = f"INSERT {this}" if this else "INSERT" 5299 then = self.sql(then_expression, "expression") 5300 then = f"{this} VALUES {then}" if then else this 5301 elif isinstance(then_expression, exp.Update): 5302 if isinstance(then_expression.args.get("expressions"), exp.Star): 5303 then = ( 5304 "UPDATE ALL BY NAME" 5305 if self.MERGE_ALL_BY_NAME 5306 else f"UPDATE {self.sql(then_expression, 'expressions')}" 5307 ) 5308 elif ( 5309 self.MERGE_ALL_BY_NAME 5310 and len(then_expression.expressions) == 1 5311 and isinstance(then_expression.expressions[0], exp.Star) 5312 ): 5313 then = "UPDATE ALL BY NAME" 5314 else: 5315 expressions_sql = self.expressions(then_expression) 5316 then = f"UPDATE SET{self.sep()}{expressions_sql}" if expressions_sql else "UPDATE" 5317 else: 5318 then = self.sql(then_expression) 5319 5320 if isinstance(then_expression, (exp.Insert, exp.Update)): 5321 where = self.sql(then_expression, "where") 5322 if where and not self.SUPPORTS_MERGE_WHERE: 5323 kind = "INSERT" if isinstance(then_expression, exp.Insert) else "UPDATE" 5324 self.unsupported(f"WHERE clause in MERGE {kind} is not supported") 5325 where = "" 5326 then = f"{then}{where}" 5327 return f"WHEN {matched}{source}{condition} THEN {then}" 5328 5329 def whens_sql(self, expression: exp.Whens) -> str: 5330 return self.expressions(expression, sep=" ", indent=False) 5331 5332 def merge_sql(self, expression: exp.Merge) -> str: 5333 schema_evolution = "" 5334 if expression.args.get("schema_evolution"): 5335 min_version = self.MERGE_SCHEMA_EVOLUTION_MIN_VERSION 5336 if min_version and self.dialect.version >= min_version: 5337 schema_evolution = " WITH SCHEMA EVOLUTION" 5338 else: 5339 self.unsupported("MERGE WITH SCHEMA EVOLUTION is not supported") 5340 5341 table = expression.this 5342 table_alias = "" 5343 5344 hints = table.args.get("hints") 5345 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 5346 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 5347 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 5348 5349 this = self.sql(table) 5350 using = f"USING {self.sql(expression, 'using')}" 5351 whens = self.sql(expression, "whens") 5352 5353 on = self.sql(expression, "on") 5354 on = f"ON {on}" if on else "" 5355 5356 if not on: 5357 on = self.expressions(expression, key="using_cond") 5358 on = f"USING ({on})" if on else "" 5359 5360 returning = self.sql(expression, "returning") 5361 if returning: 5362 whens = f"{whens}{returning}" 5363 5364 sep = self.sep() 5365 5366 return self.prepend_ctes( 5367 expression, 5368 f"MERGE{schema_evolution} INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 5369 ) 5370 5371 @unsupported_args("format") 5372 def tochar_sql(self, expression: exp.ToChar) -> str: 5373 return self.sql(exp.cast(expression.this, exp.DType.TEXT)) 5374 5375 @unsupported_args("default") 5376 def tonumber_sql(self, expression: exp.ToNumber) -> str: 5377 if not self.SUPPORTS_TO_NUMBER: 5378 self.unsupported("Unsupported TO_NUMBER function") 5379 return self._tonumber_cast_sql(expression) 5380 5381 fmt = expression.args.get("format") 5382 if not fmt: 5383 self.unsupported("Conversion format is required for TO_NUMBER") 5384 return self._tonumber_cast_sql(expression) 5385 5386 return self.func("TO_NUMBER", expression.this, fmt) 5387 5388 def _tonumber_cast_sql(self, expression: exp.ToNumber) -> str: 5389 if expression.args.get("safe"): 5390 return self.sql(exp.TryCast(this=expression.this, to=exp.DataType.build("DOUBLE"))) 5391 return self.sql(exp.cast(expression.this, exp.DType.DOUBLE)) 5392 5393 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 5394 this = self.sql(expression, "this") 5395 kind = self.sql(expression, "kind") 5396 settings_sql = self.expressions(expression, key="settings", sep=" ") 5397 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 5398 return f"{this}({kind}{args})" 5399 5400 def dictrange_sql(self, expression: exp.DictRange) -> str: 5401 this = self.sql(expression, "this") 5402 max = self.sql(expression, "max") 5403 min = self.sql(expression, "min") 5404 return f"{this}(MIN {min} MAX {max})" 5405 5406 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 5407 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 5408 5409 def aggregatekeyproperty_sql(self, expression: exp.AggregateKeyProperty) -> str: 5410 return f"AGGREGATE KEY ({self.expressions(expression, flat=True)})" 5411 5412 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 5413 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 5414 5415 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 5416 def uniquekeyproperty_sql( 5417 self, expression: exp.UniqueKeyProperty, prefix: str = "UNIQUE KEY" 5418 ) -> str: 5419 return f"{prefix} ({self.expressions(expression, flat=True)})" 5420 5421 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 5422 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 5423 expressions = self.expressions(expression, flat=True) 5424 expressions = f" {self.wrap(expressions)}" if expressions else "" 5425 buckets = self.sql(expression, "buckets") 5426 kind = self.sql(expression, "kind") 5427 buckets = f" BUCKETS {buckets}" if buckets else "" 5428 order = self.sql(expression, "order") 5429 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 5430 5431 def oncluster_sql(self, expression: exp.OnCluster) -> str: 5432 return "" 5433 5434 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 5435 expressions = self.expressions(expression, key="expressions", flat=True) 5436 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 5437 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 5438 buckets = self.sql(expression, "buckets") 5439 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 5440 5441 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 5442 this = self.sql(expression, "this") 5443 having = self.sql(expression, "having") 5444 5445 if having: 5446 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 5447 5448 return self.func("ANY_VALUE", this) 5449 5450 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 5451 transform = self.func("TRANSFORM", *expression.expressions) 5452 row_format_before = self.sql(expression, "row_format_before") 5453 row_format_before = f" {row_format_before}" if row_format_before else "" 5454 record_writer = self.sql(expression, "record_writer") 5455 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 5456 using = f" USING {self.sql(expression, 'command_script')}" 5457 schema = self.sql(expression, "schema") 5458 schema = f" AS {schema}" if schema else "" 5459 row_format_after = self.sql(expression, "row_format_after") 5460 row_format_after = f" {row_format_after}" if row_format_after else "" 5461 record_reader = self.sql(expression, "record_reader") 5462 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 5463 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 5464 5465 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 5466 key_block_size = self.sql(expression, "key_block_size") 5467 if key_block_size: 5468 return f"KEY_BLOCK_SIZE = {key_block_size}" 5469 5470 using = self.sql(expression, "using") 5471 if using: 5472 return f"USING {using}" 5473 5474 parser = self.sql(expression, "parser") 5475 if parser: 5476 return f"WITH PARSER {parser}" 5477 5478 comment = self.sql(expression, "comment") 5479 if comment: 5480 return f"COMMENT {comment}" 5481 5482 visible = expression.args.get("visible") 5483 if visible is not None: 5484 return "VISIBLE" if visible else "INVISIBLE" 5485 5486 engine_attr = self.sql(expression, "engine_attr") 5487 if engine_attr: 5488 return f"ENGINE_ATTRIBUTE = {engine_attr}" 5489 5490 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 5491 if secondary_engine_attr: 5492 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 5493 5494 self.unsupported("Unsupported index constraint option.") 5495 return "" 5496 5497 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 5498 enforced = " ENFORCED" if expression.args.get("enforced") else "" 5499 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 5500 5501 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 5502 kind = self.sql(expression, "kind") 5503 kind = f"{kind} INDEX" if kind else "INDEX" 5504 this = self.sql(expression, "this") 5505 this = f" {this}" if this else "" 5506 index_type = self.sql(expression, "index_type") 5507 index_type = f" USING {index_type}" if index_type else "" 5508 expressions = self.expressions(expression, flat=True) 5509 expressions = f" ({expressions})" if expressions else "" 5510 options = self.expressions(expression, key="options", sep=" ") 5511 options = f" {options}" if options else "" 5512 return f"{kind}{this}{index_type}{expressions}{options}" 5513 5514 def nvl2_sql(self, expression: exp.Nvl2) -> str: 5515 if self.NVL2_SUPPORTED: 5516 return self.function_fallback_sql(expression) 5517 5518 case = exp.Case().when( 5519 expression.this.is_(exp.null()).not_(copy=False), 5520 expression.args["true"], 5521 copy=False, 5522 ) 5523 else_cond = expression.args.get("false") 5524 if else_cond: 5525 case.else_(else_cond, copy=False) 5526 5527 return self.sql(case) 5528 5529 def nthvalue_sql(self, expression: exp.NthValue) -> str: 5530 if expression.args.get("from_first") is False: 5531 self.unsupported("NTH_VALUE FROM LAST is not supported") 5532 5533 return self.function_fallback_sql(expression) 5534 5535 def comprehension_sql(self, expression: exp.Comprehension) -> str: 5536 this = self.sql(expression, "this") 5537 expr = self.sql(expression, "expression") 5538 position = self.sql(expression, "position") 5539 position = f", {position}" if position else "" 5540 iterator = self.sql(expression, "iterator") 5541 condition = self.sql(expression, "condition") 5542 condition = f" IF {condition}" if condition else "" 5543 return f"{this} FOR {expr}{position} IN {iterator}{condition}" 5544 5545 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 5546 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 5547 5548 def opclass_sql(self, expression: exp.Opclass) -> str: 5549 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 5550 5551 def _ml_sql(self, expression: exp.Func, name: str) -> str: 5552 model = self.sql(expression, "this") 5553 model = f"MODEL {model}" 5554 expr = expression.expression 5555 if expr: 5556 expr_sql = self.sql(expression, "expression") 5557 expr_sql = f"TABLE {expr_sql}" if isinstance(expr, exp.Table) else expr_sql 5558 else: 5559 expr_sql = None 5560 5561 parameters = self.sql(expression, "params_struct") or None 5562 5563 return self.func(name, model, expr_sql, parameters) 5564 5565 def predict_sql(self, expression: exp.Predict) -> str: 5566 return self._ml_sql(expression, "PREDICT") 5567 5568 def generateembedding_sql(self, expression: exp.GenerateEmbedding) -> str: 5569 name = "GENERATE_TEXT_EMBEDDING" if expression.args.get("is_text") else "GENERATE_EMBEDDING" 5570 return self._ml_sql(expression, name) 5571 5572 def generatetext_sql(self, expression: exp.GenerateText) -> str: 5573 return self._ml_sql(expression, "GENERATE_TEXT") 5574 5575 def generatetable_sql(self, expression: exp.GenerateTable) -> str: 5576 return self._ml_sql(expression, "GENERATE_TABLE") 5577 5578 def generatebool_sql(self, expression: exp.GenerateBool) -> str: 5579 return self._ml_sql(expression, "GENERATE_BOOL") 5580 5581 def generateint_sql(self, expression: exp.GenerateInt) -> str: 5582 return self._ml_sql(expression, "GENERATE_INT") 5583 5584 def generatedouble_sql(self, expression: exp.GenerateDouble) -> str: 5585 return self._ml_sql(expression, "GENERATE_DOUBLE") 5586 5587 def mltranslate_sql(self, expression: exp.MLTranslate) -> str: 5588 return self._ml_sql(expression, "TRANSLATE") 5589 5590 def mlforecast_sql(self, expression: exp.MLForecast) -> str: 5591 return self._ml_sql(expression, "FORECAST") 5592 5593 def aiforecast_sql(self, expression: exp.AIForecast) -> str: 5594 this_sql = self.sql(expression, "this") 5595 if isinstance(expression.this, exp.Table): 5596 this_sql = f"TABLE {this_sql}" 5597 5598 return self.func( 5599 "FORECAST", 5600 this_sql, 5601 expression.args.get("data_col"), 5602 expression.args.get("timestamp_col"), 5603 expression.args.get("model"), 5604 expression.args.get("id_cols"), 5605 expression.args.get("horizon"), 5606 expression.args.get("forecast_end_timestamp"), 5607 expression.args.get("confidence_level"), 5608 expression.args.get("output_historical_time_series"), 5609 expression.args.get("context_window"), 5610 ) 5611 5612 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 5613 this_sql = self.sql(expression, "this") 5614 if isinstance(expression.this, exp.Table): 5615 this_sql = f"TABLE {this_sql}" 5616 5617 return self.func( 5618 "FEATURES_AT_TIME", 5619 this_sql, 5620 expression.args.get("time"), 5621 expression.args.get("num_rows"), 5622 expression.args.get("ignore_feature_nulls"), 5623 ) 5624 5625 def vectorsearch_sql(self, expression: exp.VectorSearch) -> str: 5626 this_sql = self.sql(expression, "this") 5627 if isinstance(expression.this, exp.Table): 5628 this_sql = f"TABLE {this_sql}" 5629 5630 query_table = self.sql(expression, "query_table") 5631 if isinstance(expression.args["query_table"], exp.Table): 5632 query_table = f"TABLE {query_table}" 5633 5634 return self.func( 5635 "VECTOR_SEARCH", 5636 this_sql, 5637 expression.args.get("column_to_search"), 5638 query_table, 5639 expression.args.get("query_column_to_search"), 5640 expression.args.get("top_k"), 5641 expression.args.get("distance_type"), 5642 expression.args.get("options"), 5643 ) 5644 5645 def forin_sql(self, expression: exp.ForIn) -> str: 5646 this = self.sql(expression, "this") 5647 expression_sql = self.sql(expression, "expression") 5648 return f"FOR {this} DO {expression_sql}" 5649 5650 @unsupported_args("partition_start", "partition_end", "force", "mode") 5651 def refresh_sql(self, expression: exp.Refresh) -> str: 5652 this = self.sql(expression, "this") 5653 kind = "" if isinstance(expression.this, exp.Literal) else f"{expression.text('kind')} " 5654 return f"REFRESH {kind}{this}" 5655 5656 def toarray_sql(self, expression: exp.ToArray) -> str: 5657 arg = expression.this 5658 if not arg.type: 5659 import sqlglot.optimizer.annotate_types 5660 5661 arg = sqlglot.optimizer.annotate_types.annotate_types(arg, dialect=self.dialect) 5662 5663 if arg.is_type(exp.DType.ARRAY): 5664 return self.sql(arg) 5665 5666 cond_for_null = arg.is_(exp.null()) 5667 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 5668 5669 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 5670 this = expression.this 5671 time_format = self.format_time(expression) 5672 5673 if time_format: 5674 return self.sql( 5675 exp.cast( 5676 exp.StrToTime(this=this, format=expression.args["format"]), 5677 exp.DType.TIME, 5678 ) 5679 ) 5680 5681 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 5682 return self.sql(this) 5683 5684 return self.sql(exp.cast(this, exp.DType.TIME)) 5685 5686 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 5687 this = expression.this 5688 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DType.TIMESTAMP): 5689 return self.sql(this) 5690 5691 return self.sql(exp.cast(this, exp.DType.TIMESTAMP, dialect=self.dialect)) 5692 5693 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 5694 this = expression.this 5695 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DType.DATETIME): 5696 return self.sql(this) 5697 5698 return self.sql(exp.cast(this, exp.DType.DATETIME, dialect=self.dialect)) 5699 5700 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 5701 this = expression.this 5702 time_format = self.format_time(expression) 5703 safe = expression.args.get("safe") 5704 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 5705 return self.sql( 5706 exp.cast( 5707 exp.StrToTime(this=this, format=expression.args["format"], safe=safe), 5708 exp.DType.DATE, 5709 ) 5710 ) 5711 5712 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DType.DATE): 5713 return self.sql(this) 5714 5715 if safe: 5716 return self.sql(exp.TryCast(this=this, to=exp.DataType(this=exp.DType.DATE))) 5717 5718 return self.sql(exp.cast(this, exp.DType.DATE)) 5719 5720 def unixdate_sql(self, expression: exp.UnixDate) -> str: 5721 return self.sql( 5722 exp.func( 5723 "DATEDIFF", 5724 expression.this, 5725 exp.cast(exp.Literal.string("1970-01-01"), exp.DType.DATE), 5726 "day", 5727 ) 5728 ) 5729 5730 def lastday_sql(self, expression: exp.LastDay) -> str: 5731 if self.LAST_DAY_SUPPORTS_DATE_PART: 5732 return self.function_fallback_sql(expression) 5733 5734 unit = expression.args.get("unit") 5735 if unit and unit.name.upper() != "MONTH": 5736 self.unsupported("Date parts are not supported in LAST_DAY.") 5737 5738 return self.func("LAST_DAY", expression.this) 5739 5740 def dateadd_sql(self, expression: exp.DateAdd) -> str: 5741 import sqlglot.dialects.dialect 5742 5743 return self.func( 5744 "DATE_ADD", 5745 expression.this, 5746 expression.expression, 5747 sqlglot.dialects.dialect.unit_to_str(expression), 5748 ) 5749 5750 def arrayinsert_sql(self, expression: exp.ArrayInsert, index_offset: int = 0) -> str: 5751 this = expression.this 5752 position = expression.args["position"] 5753 offset = index_offset - (expression.args.get("offset") or 0) 5754 5755 if offset: 5756 if position.is_int: 5757 value = position.to_py() 5758 if value >= 0: 5759 position = exp.Literal.number(value + offset) 5760 elif offset < 0 and value == -1: 5761 # 1-based -1 appends, which a 0-based position can only express as the size 5762 position = exp.ArraySize(this=this.copy()) 5763 else: 5764 # Negative positions count from the end, so they shift in the opposite 5765 # direction, e.g. 0-based -1 (before the last element) is 1-based -2 5766 position = exp.Literal.number(value - offset) 5767 else: 5768 self.unsupported("ARRAY_INSERT position can only be converted if it's a literal") 5769 5770 return self.func("ARRAY_INSERT", this, position, expression.expression) 5771 5772 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 5773 if self.CAN_IMPLEMENT_ARRAY_ANY: 5774 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 5775 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 5776 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 5777 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 5778 5779 import sqlglot.dialects.dialect 5780 5781 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 5782 if self.dialect.__class__ != sqlglot.dialects.dialect.Dialect: 5783 self.unsupported("ARRAY_ANY is unsupported") 5784 5785 return self.function_fallback_sql(expression) 5786 5787 def struct_sql(self, expression: exp.Struct) -> str: 5788 expression.set( 5789 "expressions", 5790 [ 5791 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 5792 if isinstance(e, exp.PropertyEQ) 5793 else e 5794 for e in expression.expressions 5795 ], 5796 ) 5797 5798 return self.function_fallback_sql(expression) 5799 5800 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 5801 low = self.sql(expression, "this") 5802 high = self.sql(expression, "expression") 5803 5804 return f"{low} TO {high}" 5805 5806 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 5807 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 5808 tables = f" {self.expressions(expression)}" 5809 5810 exists = " IF EXISTS" if expression.args.get("exists") else "" 5811 5812 on_cluster = self.sql(expression, "cluster") 5813 on_cluster = f" {on_cluster}" if on_cluster else "" 5814 5815 identity = self.sql(expression, "identity") 5816 identity = f" {identity} IDENTITY" if identity else "" 5817 5818 option = self.sql(expression, "option") 5819 option = f" {option}" if option else "" 5820 5821 partition = self.sql(expression, "partition") 5822 partition = f" {partition}" if partition else "" 5823 5824 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 5825 5826 # This transpiles T-SQL's CONVERT function 5827 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 5828 def convert_sql(self, expression: exp.Convert) -> str: 5829 to = expression.this 5830 value = expression.expression 5831 style = expression.args.get("style") 5832 safe = expression.args.get("safe") 5833 strict = expression.args.get("strict") 5834 5835 if not to or not value: 5836 return "" 5837 5838 # Retrieve length of datatype and override to default if not specified 5839 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5840 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 5841 5842 transformed: exp.Expr | None = None 5843 cast = exp.Cast if strict else exp.TryCast 5844 5845 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 5846 if isinstance(style, exp.Literal) and style.is_int: 5847 import sqlglot.dialects.tsql 5848 5849 style_value = style.name 5850 converted_style = sqlglot.dialects.tsql.TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 5851 if not converted_style: 5852 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 5853 5854 fmt = exp.Literal.string(converted_style) 5855 5856 if to.this == exp.DType.DATE: 5857 transformed = exp.StrToDate(this=value, format=fmt) 5858 elif to.this in (exp.DType.DATETIME, exp.DType.DATETIME2): 5859 transformed = exp.StrToTime(this=value, format=fmt) 5860 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5861 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 5862 elif to.this == exp.DType.TEXT: 5863 transformed = exp.TimeToStr(this=value, format=fmt) 5864 5865 if not transformed: 5866 transformed = cast(this=value, to=to, safe=safe) 5867 5868 return self.sql(transformed) 5869 5870 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 5871 this = expression.this 5872 if isinstance(this, exp.JSONPathWildcard): 5873 this = self.json_path_part(this) 5874 return f".{this}" if this else "" 5875 5876 quoted = expression.args.get("quoted") 5877 if not ( 5878 quoted and self.JSON_PATH_KEY_QUOTED_FORCES_BRACKETS 5879 ) and self.SAFE_JSON_PATH_KEY_RE.match(this): 5880 return f".{this}" 5881 5882 this = self.json_path_part(this) 5883 5884 return ( 5885 f"[{this}]" 5886 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 5887 else f".{this}" 5888 ) 5889 5890 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 5891 this = self.json_path_part(expression.this) 5892 return f"[{this}]" if this else "" 5893 5894 def _simplify_unless_literal(self, expression: E) -> E: 5895 if not isinstance(expression, exp.Literal): 5896 import sqlglot.optimizer.simplify 5897 5898 expression = sqlglot.optimizer.simplify.simplify(expression, dialect=self.dialect) 5899 5900 return expression 5901 5902 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 5903 this = expression.this 5904 if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS): 5905 self.unsupported( 5906 f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}" 5907 ) 5908 return self.sql(this) 5909 5910 if self.IGNORE_NULLS_IN_FUNC and not expression.meta_get("inline"): 5911 if self.IGNORE_NULLS_BEFORE_ORDER: 5912 from sqlglot.optimizer.scope import find_all_in_scope 5913 5914 # The first modifier here will be the one closest to the AggFunc's arg 5915 mods = sorted( 5916 find_all_in_scope(expression, exp.HavingMax, exp.Order, exp.Limit), 5917 key=lambda x: ( 5918 0 5919 if isinstance(x, exp.HavingMax) 5920 else (1 if isinstance(x, exp.Order) else 2) 5921 ), 5922 ) 5923 5924 if mods: 5925 mod = mods[0] 5926 this = expression.__class__(this=mod.this.copy()) 5927 this.meta["inline"] = True 5928 mod.this.replace(this) 5929 return self.sql(expression.this) 5930 5931 agg_func = expression.find(exp.AggFunc) 5932 5933 if agg_func: 5934 agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})" 5935 return self.maybe_comment(agg_func_sql, comments=agg_func.comments) 5936 5937 return f"{self.sql(expression, 'this')} {text}" 5938 5939 def _replace_line_breaks(self, string: str) -> str: 5940 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 5941 if self.pretty: 5942 return string.replace("\n", self.SENTINEL_LINE_BREAK) 5943 return string 5944 5945 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 5946 option = self.sql(expression, "this") 5947 5948 if expression.expressions: 5949 upper = option.upper() 5950 5951 # Snowflake FILE_FORMAT options are separated by whitespace 5952 sep = " " if upper == "FILE_FORMAT" else ", " 5953 5954 # Databricks copy/format options do not set their list of values with EQ 5955 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 5956 values = self.expressions(expression, flat=True, sep=sep) 5957 return f"{option}{op}({values})" 5958 5959 value = self.sql(expression, "expression") 5960 5961 if not value: 5962 return option 5963 5964 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 5965 5966 return f"{option}{op}{value}" 5967 5968 def credentials_sql(self, expression: exp.Credentials) -> str: 5969 cred_expr = expression.args.get("credentials") 5970 if isinstance(cred_expr, exp.Literal): 5971 # Redshift case: CREDENTIALS <string> 5972 credentials = self.sql(expression, "credentials") 5973 credentials = f"CREDENTIALS {credentials}" if credentials else "" 5974 else: 5975 # Snowflake case: CREDENTIALS = (...) 5976 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 5977 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 5978 5979 storage = self.sql(expression, "storage") 5980 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 5981 5982 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 5983 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 5984 5985 iam_role = self.sql(expression, "iam_role") 5986 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 5987 5988 region = self.sql(expression, "region") 5989 region = f" REGION {region}" if region else "" 5990 5991 return f"{credentials}{storage}{encryption}{iam_role}{region}" 5992 5993 def copy_sql(self, expression: exp.Copy) -> str: 5994 this = self.sql(expression, "this") 5995 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 5996 5997 credentials = self.sql(expression, "credentials") 5998 credentials = self.seg(credentials) if credentials else "" 5999 files = self.expressions(expression, key="files", flat=True) 6000 kind = self.seg("FROM" if expression.args.get("kind") else "TO") if files else "" 6001 6002 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 6003 params = self.expressions( 6004 expression, 6005 key="params", 6006 sep=sep, 6007 new_line=True, 6008 skip_last=True, 6009 skip_first=True, 6010 indent=self.COPY_PARAMS_ARE_WRAPPED, 6011 ) 6012 6013 if params: 6014 if self.COPY_PARAMS_ARE_WRAPPED: 6015 params = f" WITH ({params})" 6016 elif not self.pretty and (files or credentials): 6017 params = f" {params}" 6018 6019 return f"COPY{this}{kind} {files}{credentials}{params}" 6020 6021 def semicolon_sql(self, expression: exp.Semicolon) -> str: 6022 return "" 6023 6024 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 6025 on_sql = "ON" if expression.args.get("on") else "OFF" 6026 filter_col: str | None = self.sql(expression, "filter_column") 6027 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 6028 retention_period: str | None = self.sql(expression, "retention_period") 6029 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 6030 6031 if filter_col or retention_period: 6032 on_sql = self.func("ON", filter_col, retention_period) 6033 6034 return f"DATA_DELETION={on_sql}" 6035 6036 def maskingpolicycolumnconstraint_sql( 6037 self, expression: exp.MaskingPolicyColumnConstraint 6038 ) -> str: 6039 this = self.sql(expression, "this") 6040 expressions = self.expressions(expression, flat=True) 6041 expressions = f" USING ({expressions})" if expressions else "" 6042 return f"MASKING POLICY {this}{expressions}" 6043 6044 def gapfill_sql(self, expression: exp.GapFill) -> str: 6045 this = self.sql(expression, "this") 6046 if isinstance(expression.this, exp.Table): 6047 this = f"TABLE {this}" 6048 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 6049 6050 def scope_resolution(self, rhs: str, scope_name: str) -> str: 6051 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 6052 6053 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 6054 this = self.sql(expression, "this") 6055 expr = expression.expression 6056 6057 if isinstance(expr, exp.Func): 6058 # T-SQL's CLR functions are case sensitive 6059 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 6060 else: 6061 expr = self.sql(expression, "expression") 6062 6063 return self.scope_resolution(expr, this) 6064 6065 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 6066 if self.PARSE_JSON_NAME is None: 6067 return self.sql(expression.this) 6068 6069 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 6070 6071 def rand_sql(self, expression: exp.Rand) -> str: 6072 lower = self.sql(expression, "lower") 6073 upper = self.sql(expression, "upper") 6074 6075 if lower and upper: 6076 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 6077 return self.func("RAND", expression.this) 6078 6079 def changes_sql(self, expression: exp.Changes) -> str: 6080 information = self.sql(expression, "information") 6081 information = f"INFORMATION => {information}" 6082 at_before = self.sql(expression, "at_before") 6083 at_before = f"{self.seg('')}{at_before}" if at_before else "" 6084 end = self.sql(expression, "end") 6085 end = f"{self.seg('')}{end}" if end else "" 6086 6087 return f"CHANGES ({information}){at_before}{end}" 6088 6089 def pad_sql(self, expression: exp.Pad) -> str: 6090 prefix = "L" if expression.args.get("is_left") else "R" 6091 6092 fill_pattern = self.sql(expression, "fill_pattern") or None 6093 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 6094 fill_pattern = "' '" 6095 6096 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 6097 6098 def summarize_sql(self, expression: exp.Summarize) -> str: 6099 table = " TABLE" if expression.args.get("table") else "" 6100 return f"SUMMARIZE{table} {self.sql(expression.this)}" 6101 6102 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 6103 generate_series = exp.GenerateSeries(**expression.args) 6104 6105 parent = expression.parent 6106 if isinstance(parent, (exp.Alias, exp.TableAlias)): 6107 parent = parent.parent 6108 6109 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 6110 return self.sql(exp.Unnest(expressions=[generate_series])) 6111 6112 if isinstance(parent, exp.Select): 6113 self.unsupported("GenerateSeries projection unnesting is not supported.") 6114 6115 return self.sql(generate_series) 6116 6117 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 6118 if self.SUPPORTS_CONVERT_TIMEZONE: 6119 return self.function_fallback_sql(expression) 6120 6121 source_tz = expression.args.get("source_tz") 6122 target_tz = expression.args.get("target_tz") 6123 timestamp = expression.args.get("timestamp") 6124 6125 if source_tz and timestamp: 6126 timestamp = exp.AtTimeZone( 6127 this=exp.cast(timestamp, exp.DType.TIMESTAMPNTZ), zone=source_tz 6128 ) 6129 6130 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 6131 6132 return self.sql(expr) 6133 6134 def json_sql(self, expression: exp.JSON) -> str: 6135 this = self.sql(expression, "this") 6136 this = f" {this}" if this else "" 6137 6138 _with = expression.args.get("with_") 6139 6140 if _with is None: 6141 with_sql = "" 6142 elif not _with: 6143 with_sql = " WITHOUT" 6144 else: 6145 with_sql = " WITH" 6146 6147 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 6148 6149 return f"JSON{this}{with_sql}{unique_sql}" 6150 6151 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 6152 path = self.sql(expression, "path") 6153 returning = self.sql(expression, "returning") 6154 returning = f" RETURNING {returning}" if returning else "" 6155 6156 on_condition = self.sql(expression, "on_condition") 6157 on_condition = f" {on_condition}" if on_condition else "" 6158 6159 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 6160 6161 def skipjsoncolumn_sql(self, expression: exp.SkipJSONColumn) -> str: 6162 regexp = " REGEXP" if expression.args.get("regexp") else "" 6163 return f"SKIP{regexp} {self.sql(expression.expression)}" 6164 6165 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 6166 else_ = "ELSE " if expression.args.get("else_") else "" 6167 condition = self.sql(expression, "expression") 6168 condition = f"WHEN {condition} THEN " if condition else else_ 6169 insert = self.sql(expression, "this")[len("INSERT") :].strip() 6170 return f"{condition}{insert}" 6171 6172 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 6173 kind = self.sql(expression, "kind") 6174 source = self.sql(expression, "source") 6175 6176 if kind: 6177 expressions = self.seg(self.expressions(expression, sep=" ")) 6178 sql = f"INSERT {kind}{expressions}{self.seg(source)}" 6179 else: 6180 # If kind isn't present, we have Hive's FROM-first form: 6181 # FROM x INSERT ... SELECT ... [INSERT ... SELECT ...] 6182 inserts = self.sep().join(self.sql(e) for e in expression.expressions) 6183 sql = f"FROM {source}{self.seg(inserts)}" 6184 6185 return self.prepend_ctes(expression, sql) 6186 6187 def oncondition_sql(self, expression: exp.OnCondition) -> str: 6188 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 6189 empty = expression.args.get("empty") 6190 empty = ( 6191 f"DEFAULT {empty} ON EMPTY" 6192 if isinstance(empty, exp.Expr) 6193 else self.sql(expression, "empty") 6194 ) 6195 6196 error = expression.args.get("error") 6197 error = ( 6198 f"DEFAULT {error} ON ERROR" 6199 if isinstance(error, exp.Expr) 6200 else self.sql(expression, "error") 6201 ) 6202 6203 if error and empty: 6204 error = ( 6205 f"{empty} {error}" 6206 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 6207 else f"{error} {empty}" 6208 ) 6209 empty = "" 6210 6211 null = self.sql(expression, "null") 6212 6213 return f"{empty}{error}{null}" 6214 6215 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 6216 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 6217 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 6218 6219 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 6220 this = self.sql(expression, "this") 6221 path = self.sql(expression, "path") 6222 6223 passing = self.expressions(expression, "passing") 6224 passing = f" PASSING {passing}" if passing else "" 6225 6226 on_condition = self.sql(expression, "on_condition") 6227 on_condition = f" {on_condition}" if on_condition else "" 6228 6229 path = f"{path}{passing}{on_condition}" 6230 6231 return self.func("JSON_EXISTS", this, path) 6232 6233 def _add_arrayagg_null_filter( 6234 self, 6235 array_agg_sql: str, 6236 array_agg_expr: exp.ArrayAgg, 6237 column_expr: exp.Expr, 6238 ) -> str: 6239 """ 6240 Add NULL filter to ARRAY_AGG if dialect requires it. 6241 6242 Args: 6243 array_agg_sql: The generated ARRAY_AGG SQL string 6244 array_agg_expr: The ArrayAgg expression node 6245 column_expr: The column/expression to filter (before ORDER BY wrapping) 6246 6247 Returns: 6248 SQL string with FILTER clause added if needed 6249 """ 6250 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 6251 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 6252 if not ( 6253 self.dialect.ARRAY_AGG_INCLUDES_NULLS and array_agg_expr.args.get("nulls_excluded") 6254 ): 6255 return array_agg_sql 6256 6257 parent = array_agg_expr.parent 6258 if isinstance(parent, exp.Filter): 6259 parent_cond = parent.expression.this 6260 parent_cond.replace(parent_cond.and_(column_expr.is_(exp.null()).not_())) 6261 elif column_expr.find(exp.Column): 6262 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 6263 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 6264 this_sql = ( 6265 self.expressions(column_expr) 6266 if isinstance(column_expr, exp.Distinct) 6267 else self.sql(column_expr) 6268 ) 6269 array_agg_sql = f"{array_agg_sql} FILTER(WHERE {this_sql} IS NOT NULL)" 6270 6271 return array_agg_sql 6272 6273 @unsupported_args("count") 6274 def min_sql(self, expression: exp.Min) -> str: 6275 return self.function_fallback_sql(expression) 6276 6277 @unsupported_args("count") 6278 def max_sql(self, expression: exp.Max) -> str: 6279 return self.function_fallback_sql(expression) 6280 6281 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 6282 array_agg = self.function_fallback_sql(expression) 6283 column_expr = expression.this 6284 if isinstance(column_expr, exp.Order): 6285 column_expr = column_expr.this 6286 6287 return self._add_arrayagg_null_filter(array_agg, expression, column_expr) 6288 6289 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 6290 # Only the SQLGlot dialect serializes the internal origin for round-tripping. 6291 origin = expression.args.get("origin") if self.dialect == "" else None 6292 kind = expression.args.get("kind") 6293 if origin is not None and kind is None: 6294 kind = exp.Literal.string("START") 6295 6296 return self.func( 6297 "TIME_SLICE", expression.this, expression.expression, expression.unit, kind, origin 6298 ) 6299 6300 def slice_sql(self, expression: exp.Slice) -> str: 6301 if "[" in self.dialect.tokenizer_class._IDENTIFIERS: 6302 self.unsupported("Slices are not supported") 6303 6304 step = self.sql(expression, "step") 6305 # An omitted end is written as `-` before a step, since `::` is the cast operator 6306 end = self.sql(expression.expression) or ("-" if step else "") 6307 begin = self.sql(expression.this) 6308 6309 sql = f"{end}:{step}" if step else end 6310 return f"{begin}:{sql}" if sql else f"{begin}:" 6311 6312 def apply_sql(self, expression: exp.Apply) -> str: 6313 this = self.sql(expression, "this") 6314 expr = self.sql(expression, "expression") 6315 6316 return f"{this} APPLY({expr})" 6317 6318 def _grant_or_revoke_sql( 6319 self, 6320 expression: exp.Grant | exp.Revoke, 6321 keyword: str, 6322 preposition: str, 6323 grant_option_prefix: str = "", 6324 grant_option_suffix: str = "", 6325 ) -> str: 6326 privileges_sql = self.expressions(expression, key="privileges", flat=True) 6327 6328 kind = self.sql(expression, "kind") 6329 kind = f" {kind}" if kind else "" 6330 6331 securable = self.sql(expression, "securable") 6332 securable = f" {securable}" if securable else "" 6333 6334 principals = self.expressions(expression, key="principals", flat=True) 6335 6336 if not expression.args.get("grant_option"): 6337 grant_option_prefix = grant_option_suffix = "" 6338 6339 # cascade for revoke only 6340 cascade = self.sql(expression, "cascade") 6341 cascade = f" {cascade}" if cascade else "" 6342 6343 return f"{keyword} {grant_option_prefix}{privileges_sql} ON{kind}{securable} {preposition} {principals}{grant_option_suffix}{cascade}" 6344 6345 def grant_sql(self, expression: exp.Grant) -> str: 6346 return self._grant_or_revoke_sql( 6347 expression, 6348 keyword="GRANT", 6349 preposition="TO", 6350 grant_option_suffix=" WITH GRANT OPTION", 6351 ) 6352 6353 def revoke_sql(self, expression: exp.Revoke) -> str: 6354 return self._grant_or_revoke_sql( 6355 expression, 6356 keyword="REVOKE", 6357 preposition="FROM", 6358 grant_option_prefix="GRANT OPTION FOR ", 6359 ) 6360 6361 def grantprivilege_sql(self, expression: exp.GrantPrivilege) -> str: 6362 this = self.sql(expression, "this") 6363 columns = self.expressions(expression, flat=True) 6364 columns = f"({columns})" if columns else "" 6365 6366 return f"{this}{columns}" 6367 6368 def grantprincipal_sql(self, expression: exp.GrantPrincipal) -> str: 6369 this = self.sql(expression, "this") 6370 6371 kind = self.sql(expression, "kind") 6372 kind = f"{kind} " if kind else "" 6373 6374 return f"{kind}{this}" 6375 6376 def columns_sql(self, expression: exp.Columns) -> str: 6377 func = self.function_fallback_sql(expression) 6378 if expression.args.get("unpack"): 6379 func = f"*{func}" 6380 6381 return func 6382 6383 def overlay_sql(self, expression: exp.Overlay) -> str: 6384 this = self.sql(expression, "this") 6385 expr = self.sql(expression, "expression") 6386 from_sql = self.sql(expression, "from_") 6387 for_sql = self.sql(expression, "for_") 6388 for_sql = f" FOR {for_sql}" if for_sql else "" 6389 6390 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 6391 6392 @unsupported_args("format") 6393 def todouble_sql(self, expression: exp.ToDouble) -> str: 6394 cast = exp.TryCast if expression.args.get("safe") else exp.Cast 6395 return self.sql(cast(this=expression.this, to=exp.DType.DOUBLE.into_expr())) 6396 6397 def string_sql(self, expression: exp.String) -> str: 6398 this = expression.this 6399 zone = expression.args.get("zone") 6400 6401 if zone: 6402 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 6403 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 6404 # set for source_tz to transpile the time conversion before the STRING cast 6405 this = exp.ConvertTimezone( 6406 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 6407 ) 6408 6409 return self.sql(exp.cast(this, exp.DType.VARCHAR)) 6410 6411 def median_sql(self, expression: exp.Median) -> str: 6412 if not self.SUPPORTS_MEDIAN: 6413 return self.sql( 6414 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 6415 ) 6416 6417 return self.function_fallback_sql(expression) 6418 6419 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 6420 filler = self.sql(expression, "this") 6421 filler = f" {filler}" if filler else "" 6422 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 6423 return f"TRUNCATE{filler} {with_count}" 6424 6425 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 6426 if self.SUPPORTS_UNIX_SECONDS: 6427 return self.function_fallback_sql(expression) 6428 6429 start_ts = exp.cast(exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DType.TIMESTAMPTZ) 6430 6431 return self.sql( 6432 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 6433 ) 6434 6435 def arraysort_sql(self, expression: exp.ArraySort) -> str: 6436 asc = expression.args.get("asc") 6437 nulls_first = expression.args.get("nulls_first") 6438 if (asc and asc != exp.true()) or (nulls_first and nulls_first != exp.false()): 6439 self.unsupported("ARRAY_SORT only sorts ascending with NULLs last") 6440 return self.func("ARRAY_SORT", expression.this, expression.expression) 6441 6442 def variance_sql(self, expression: exp.Variance, window: exp.Window | None = None) -> str: 6443 this = expression.this 6444 name = self.VARIANCE_NAME or self.function_name(expression) 6445 if not expression.args.get("single_value_returns_zero"): 6446 return self.func(name, this) 6447 6448 node: exp.Expr = expression 6449 while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)): 6450 node = node.parent 6451 if window is None and isinstance(node.parent, exp.Window) and node.arg_key == "this": 6452 self.unsupported("VARIANCE returning 0 for a single value is not supported in a window") 6453 return self.func(name, this) 6454 6455 expression.set("single_value_returns_zero", None) 6456 count: exp.Expr 6457 variance: exp.Expr = expression 6458 if window: 6459 count = window.copy() 6460 count.set("this", exp.Count(this=count.this.this)) 6461 variance = window 6462 else: 6463 count = exp.Count(this=this.copy()) 6464 6465 return self.sql( 6466 exp.case(count, copy=False) 6467 .when(0, exp.null(), copy=False) 6468 .when(1, 0, copy=False) 6469 .else_(variance, copy=False) 6470 ) 6471 6472 def arraysize_sql(self, expression: exp.ArraySize) -> str: 6473 dim = expression.expression 6474 6475 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 6476 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 6477 if not (dim.is_int and dim.name == "1"): 6478 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 6479 dim = None 6480 6481 # If dimension is required but not specified, default initialize it 6482 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 6483 dim = exp.Literal.number(1) 6484 6485 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 6486 6487 def attach_sql(self, expression: exp.Attach) -> str: 6488 this = self.sql(expression, "this") 6489 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 6490 expressions = self.expressions(expression) 6491 expressions = f" ({expressions})" if expressions else "" 6492 6493 return f"ATTACH{exists_sql} {this}{expressions}" 6494 6495 def detach_sql(self, expression: exp.Detach) -> str: 6496 kind = self.sql(expression, "kind") 6497 kind = f" {kind}" if kind else "" 6498 # the DATABASE keyword is required if IF EXISTS is set for DuckDB 6499 # ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax 6500 exists = " IF EXISTS" if expression.args.get("exists") else "" 6501 if exists: 6502 kind = kind or " DATABASE" 6503 6504 this = self.sql(expression, "this") 6505 this = f" {this}" if this else "" 6506 cluster = self.sql(expression, "cluster") 6507 cluster = f" {cluster}" if cluster else "" 6508 permanent = " PERMANENTLY" if expression.args.get("permanent") else "" 6509 sync = " SYNC" if expression.args.get("sync") else "" 6510 return f"DETACH{kind}{exists}{this}{cluster}{permanent}{sync}" 6511 6512 def attachoption_sql(self, expression: exp.AttachOption) -> str: 6513 this = self.sql(expression, "this") 6514 value = self.sql(expression, "expression") 6515 value = f" {value}" if value else "" 6516 return f"{this}{value}" 6517 6518 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 6519 return ( 6520 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 6521 ) 6522 6523 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 6524 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 6525 encode = f"{encode} {self.sql(expression, 'this')}" 6526 6527 properties = expression.args.get("properties") 6528 if properties: 6529 encode = f"{encode} {self.properties(properties)}" 6530 6531 return encode 6532 6533 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 6534 this = self.sql(expression, "this") 6535 include = f"INCLUDE {this}" 6536 6537 column_def = self.sql(expression, "column_def") 6538 if column_def: 6539 include = f"{include} {column_def}" 6540 6541 alias = self.sql(expression, "alias") 6542 if alias: 6543 include = f"{include} AS {alias}" 6544 6545 return include 6546 6547 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 6548 prefix = "EVALNAME" if expression.args.get("evalname") else "NAME" 6549 name = f"{prefix} {self.sql(expression, 'this')}" 6550 return self.func("XMLELEMENT", name, *expression.expressions) 6551 6552 def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str: 6553 this = self.sql(expression, "this") 6554 expr = self.sql(expression, "expression") 6555 expr = f"({expr})" if expr else "" 6556 return f"{this}{expr}" 6557 6558 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 6559 partitions = self.expressions(expression, "partition_expressions") 6560 create = self.expressions(expression, "create_expressions") 6561 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 6562 6563 def partitionbyrangepropertydynamic_sql( 6564 self, expression: exp.PartitionByRangePropertyDynamic 6565 ) -> str: 6566 start = self.sql(expression, "start") 6567 end = self.sql(expression, "end") 6568 6569 every = expression.args["every"] 6570 if isinstance(every, exp.Interval) and every.this.is_string: 6571 every.this.replace(exp.Literal.number(every.name)) 6572 6573 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 6574 6575 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 6576 name = self.sql(expression, "this") 6577 values = self.expressions(expression, flat=True) 6578 6579 return f"NAME {name} VALUE {values}" 6580 6581 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 6582 kind = self.sql(expression, "kind") 6583 sample = self.sql(expression, "sample") 6584 return f"SAMPLE {sample} {kind}" 6585 6586 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 6587 kind = self.sql(expression, "kind") 6588 option = self.sql(expression, "option") 6589 option = f" {option}" if option else "" 6590 this = self.sql(expression, "this") 6591 this = f" {this}" if this else "" 6592 columns = self.expressions(expression) 6593 columns = f" {columns}" if columns else "" 6594 return f"{kind}{option} STATISTICS{this}{columns}" 6595 6596 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 6597 this = self.sql(expression, "this") 6598 columns = self.expressions(expression) 6599 inner_expression = self.sql(expression, "expression") 6600 inner_expression = f" {inner_expression}" if inner_expression else "" 6601 update_options = self.sql(expression, "update_options") 6602 update_options = f" {update_options} UPDATE" if update_options else "" 6603 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 6604 6605 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 6606 kind = self.sql(expression, "kind") 6607 kind = f" {kind}" if kind else "" 6608 return f"DELETE{kind} STATISTICS" 6609 6610 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 6611 inner_expression = self.sql(expression, "expression") 6612 return f"LIST CHAINED ROWS{inner_expression}" 6613 6614 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 6615 kind = self.sql(expression, "kind") 6616 this = self.sql(expression, "this") 6617 this = f" {this}" if this else "" 6618 inner_expression = self.sql(expression, "expression") 6619 return f"VALIDATE {kind}{this}{inner_expression}" 6620 6621 def analyze_sql(self, expression: exp.Analyze) -> str: 6622 options = self.expressions(expression, key="options", sep=" ") 6623 options = f" {options}" if options else "" 6624 kind = self.sql(expression, "kind") 6625 kind = f" {kind}" if kind else "" 6626 tables = self.expressions(expression, key="tables", flat=True) 6627 tables = f" {tables}" if tables else "" 6628 mode = self.sql(expression, "mode") 6629 mode = f" {mode}" if mode else "" 6630 properties = self.sql(expression, "properties") 6631 properties = f" {properties}" if properties else "" 6632 partition = self.sql(expression, "partition") 6633 partition = f" {partition}" if partition else "" 6634 inner_expression = self.sql(expression, "expression") 6635 inner_expression = f" {inner_expression}" if inner_expression else "" 6636 return f"ANALYZE{options}{kind}{tables}{partition}{mode}{inner_expression}{properties}" 6637 6638 def xmltable_sql(self, expression: exp.XMLTable) -> str: 6639 this = self.sql(expression, "this") 6640 namespaces = self.expressions(expression, key="namespaces") 6641 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 6642 passing = self.expressions(expression, key="passing") 6643 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 6644 columns = self.expressions(expression, key="columns") 6645 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 6646 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 6647 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 6648 6649 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 6650 this = self.sql(expression, "this") 6651 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 6652 6653 def export_sql(self, expression: exp.Export) -> str: 6654 this = self.sql(expression, "this") 6655 connection = self.sql(expression, "connection") 6656 connection = f"WITH CONNECTION {connection} " if connection else "" 6657 options = self.sql(expression, "options") 6658 return f"EXPORT DATA {connection}{options} AS {this}" 6659 6660 def declare_sql(self, expression: exp.Declare) -> str: 6661 replace = "OR REPLACE " if expression.args.get("replace") else "" 6662 return f"DECLARE {replace}{self.expressions(expression, flat=True)}" 6663 6664 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 6665 variables = self.expressions(expression, "this") 6666 default = self.sql(expression, "default") 6667 default = f" {self.DECLARE_DEFAULT_ASSIGNMENT} {default}" if default else "" 6668 6669 kind = self.sql(expression, "kind") 6670 if isinstance(expression.args.get("kind"), exp.Schema): 6671 kind = f"TABLE {kind}" 6672 6673 kind = f" {kind}" if kind else "" 6674 6675 return f"{variables}{kind}{default}" 6676 6677 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 6678 kind = self.sql(expression, "kind") 6679 this = self.sql(expression, "this") 6680 set = self.sql(expression, "expression") 6681 to = self.sql(expression, "to") 6682 to = f" TO {to}" if to else "" 6683 default = self.sql(expression, "default") 6684 default = f" DEFAULT {default}" if default else "" 6685 using = self.sql(expression, "using") 6686 using = f" USING {using}" if using else "" 6687 6688 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 6689 6690 return f"{kind_sql} {this} SET {set}{to}{default}{using}" 6691 6692 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 6693 params = self.expressions(expression, key="params", flat=True) 6694 return self.func(expression.name, *expression.expressions) + f"({params})" 6695 6696 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 6697 return self.func(expression.name, *expression.expressions) 6698 6699 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 6700 return self.anonymousaggfunc_sql(expression) 6701 6702 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 6703 return self.parameterizedagg_sql(expression) 6704 6705 def show_sql(self, expression: exp.Show) -> str: 6706 self.unsupported("Unsupported SHOW statement") 6707 return "" 6708 6709 def install_sql(self, expression: exp.Install) -> str: 6710 self.unsupported("Unsupported INSTALL statement") 6711 return "" 6712 6713 def liststage_sql(self, expression: exp.ListStage) -> str: 6714 pattern = self.sql(expression, "pattern") 6715 pattern = f" PATTERN = {pattern}" if pattern else "" 6716 return f"LIST {self.sql(expression, 'this')}{pattern}" 6717 6718 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 6719 # Snowflake GET/PUT statements: 6720 # PUT <file> <internalStage> <properties> 6721 # GET <internalStage> <file> <properties> 6722 props = expression.args.get("properties") 6723 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 6724 this = self.sql(expression, "this") 6725 target = self.sql(expression, "target") 6726 6727 if isinstance(expression, exp.Put): 6728 return f"PUT {this} {target}{props_sql}" 6729 else: 6730 return f"GET {target} {this}{props_sql}" 6731 6732 def translatecharacters_sql(self, expression: exp.TranslateCharacters) -> str: 6733 this = self.sql(expression, "this") 6734 expr = self.sql(expression, "expression") 6735 with_error = " WITH ERROR" if expression.args.get("with_error") else "" 6736 return f"TRANSLATE({this} USING {expr}{with_error})" 6737 6738 def decodecase_sql(self, expression: exp.DecodeCase) -> str: 6739 if self.SUPPORTS_DECODE_CASE: 6740 return self.func("DECODE", *expression.expressions) 6741 6742 decode_expr, *expressions = expression.expressions 6743 6744 ifs = [] 6745 for search, result in zip(expressions[::2], expressions[1::2]): 6746 if isinstance(search, exp.Literal): 6747 ifs.append(exp.If(this=decode_expr.eq(search), true=result)) 6748 elif isinstance(search, exp.Null): 6749 ifs.append(exp.If(this=decode_expr.is_(exp.Null()), true=result)) 6750 else: 6751 if isinstance(search, exp.Binary): 6752 search = exp.paren(search) 6753 6754 cond = exp.or_( 6755 decode_expr.eq(search), 6756 exp.and_(decode_expr.is_(exp.Null()), search.is_(exp.Null()), copy=False), 6757 copy=False, 6758 ) 6759 ifs.append(exp.If(this=cond, true=result)) 6760 6761 case = exp.Case(ifs=ifs, default=expressions[-1] if len(expressions) % 2 == 1 else None) 6762 return self.sql(case) 6763 6764 def semanticview_sql(self, expression: exp.SemanticView) -> str: 6765 this = self.sql(expression, "this") 6766 this = self.seg(this, sep="") 6767 dimensions = self.expressions( 6768 expression, "dimensions", dynamic=True, skip_first=True, skip_last=True 6769 ) 6770 dimensions = self.seg(f"DIMENSIONS {dimensions}") if dimensions else "" 6771 metrics = self.expressions( 6772 expression, "metrics", dynamic=True, skip_first=True, skip_last=True 6773 ) 6774 metrics = self.seg(f"METRICS {metrics}") if metrics else "" 6775 facts = self.expressions(expression, "facts", dynamic=True, skip_first=True, skip_last=True) 6776 facts = self.seg(f"FACTS {facts}") if facts else "" 6777 where = self.sql(expression, "where") 6778 where = self.seg(f"WHERE {where}") if where else "" 6779 body = self.indent(this + metrics + dimensions + facts + where, skip_first=True) 6780 return f"SEMANTIC_VIEW({body}{self.seg(')', sep='')}" 6781 6782 def getextract_sql(self, expression: exp.GetExtract) -> str: 6783 this = expression.this 6784 expr = expression.expression 6785 6786 if not this.type or not expression.type: 6787 import sqlglot.optimizer.annotate_types 6788 6789 this = sqlglot.optimizer.annotate_types.annotate_types(this, dialect=self.dialect) 6790 6791 if this.is_type(*(exp.DType.ARRAY, exp.DType.MAP)): 6792 return self.sql(exp.Bracket(this=this, expressions=[expr])) 6793 6794 return self.sql(exp.JSONExtract(this=this, expression=self.dialect.to_json_path(expr))) 6795 6796 def datefromunixdate_sql(self, expression: exp.DateFromUnixDate) -> str: 6797 return self.sql( 6798 exp.DateAdd( 6799 this=exp.cast(exp.Literal.string("1970-01-01"), exp.DType.DATE), 6800 expression=expression.this, 6801 unit=exp.var("DAY"), 6802 ) 6803 ) 6804 6805 def space_sql(self: Generator, expression: exp.Space) -> str: 6806 return self.sql(exp.Repeat(this=exp.Literal.string(" "), times=expression.this)) 6807 6808 def buildproperty_sql(self, expression: exp.BuildProperty) -> str: 6809 return f"BUILD {self.sql(expression, 'this')}" 6810 6811 def refreshtriggerproperty_sql(self, expression: exp.RefreshTriggerProperty) -> str: 6812 method = self.sql(expression, "method") 6813 kind = expression.args.get("kind") 6814 if not kind: 6815 return f"REFRESH {method}" 6816 6817 every = self.sql(expression, "every") 6818 unit = self.sql(expression, "unit") 6819 every = f" EVERY {every} {unit}" if every else "" 6820 starts = self.sql(expression, "starts") 6821 starts = f" STARTS {starts}" if starts else "" 6822 6823 return f"REFRESH {method} ON {kind}{every}{starts}" 6824 6825 def modelattribute_sql(self, expression: exp.ModelAttribute) -> str: 6826 self.unsupported("The model!attribute syntax is not supported") 6827 return "" 6828 6829 def directorystage_sql(self, expression: exp.DirectoryStage) -> str: 6830 return self.func("DIRECTORY", expression.this) 6831 6832 def uuid_sql(self, expression: exp.Uuid) -> str: 6833 is_string = expression.args.get("is_string", False) 6834 uuid_func_sql = self.func("UUID") 6835 6836 if is_string and not self.dialect.UUID_IS_STRING_TYPE: 6837 return self.sql(exp.cast(uuid_func_sql, exp.DType.VARCHAR, dialect=self.dialect)) 6838 6839 return uuid_func_sql 6840 6841 def initcap_sql(self, expression: exp.Initcap) -> str: 6842 delimiters = expression.expression 6843 6844 if delimiters: 6845 # do not generate delimiters arg if we are round-tripping from default delimiters 6846 if ( 6847 delimiters.is_string 6848 and delimiters.this == self.dialect.INITCAP_DEFAULT_DELIMITER_CHARS 6849 ): 6850 delimiters = None 6851 elif not self.dialect.INITCAP_SUPPORTS_CUSTOM_DELIMITERS: 6852 self.unsupported("INITCAP does not support custom delimiters") 6853 delimiters = None 6854 6855 return self.func("INITCAP", expression.this, delimiters) 6856 6857 def localtime_sql(self, expression: exp.Localtime) -> str: 6858 this = expression.this 6859 return self.func("LOCALTIME", this) if this else "LOCALTIME" 6860 6861 def localtimestamp_sql(self, expression: exp.Localtimestamp) -> str: 6862 this = expression.this 6863 return self.func("LOCALTIMESTAMP", this) if this else "LOCALTIMESTAMP" 6864 6865 def weekstart_name(self, expression: exp.WeekStart) -> str: 6866 import sqlglot.dialects.dialect 6867 6868 # WEEK(<day>) is BigQuery-only syntax, so it degrades to the plain WEEK unit 6869 this = expression.this.name.upper() 6870 6871 dow_from_week_start_day = sqlglot.dialects.dialect.WEEK_START_DAY_TO_DOW.get(this) 6872 dow_from_week_offset = sqlglot.dialects.dialect.week_offset_to_dow(self.dialect.WEEK_OFFSET) 6873 6874 if dow_from_week_start_day != dow_from_week_offset: 6875 self.unsupported( 6876 f"WEEK({this}) is not supported; falling back to the default week start day" 6877 ) 6878 6879 return "WEEK" 6880 6881 def weekstart_sql(self, expression: exp.WeekStart) -> str: 6882 name = self.weekstart_name(expression) 6883 6884 # DateTrunc stores string literal units, whereas TimeUnit expressions store keywords 6885 if isinstance(expression.parent, exp.DateTrunc): 6886 return self.sql(exp.Literal.string(name)) 6887 6888 return name 6889 6890 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 6891 self._warn_unsupported_arg(expression, "century_from_zero") 6892 unit = expression.unit 6893 if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"): 6894 self.unsupported(f"Unexpected interval unit: {unit.name}") 6895 6896 return self.function_fallback_sql(expression) 6897 6898 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 6899 args = expression.expressions 6900 if len(args) > 1 and not self.SUPPORTS_MULTI_ARG_CHR: 6901 # CHAR(72, 105) -> CHR(72) || CHR(105) 6902 chars: list[exp.Expr] = [exp.Chr(expressions=[arg.copy()]) for arg in args] 6903 return self.sql(reduce(lambda x, y: exp.DPipe(this=x, expression=y), chars)) 6904 6905 this = self.expressions(expression) 6906 charset = self.sql(expression, "charset") 6907 using = f" USING {charset}" if charset else "" 6908 return self.func(name, this + using) 6909 6910 def weightstring_sql(self, expression: exp.WeightString) -> str: 6911 to = self.sql(expression, "to") 6912 to = f" AS {to}" if to else "" 6913 return self.func("WEIGHT_STRING", f"{self.sql(expression, 'this')}{to}") 6914 6915 def block_sql(self, expression: exp.Block) -> str: 6916 expressions = self.expressions(expression, sep="; ", flat=True) 6917 begin = "BEGIN " if expression.args.get("begin") else "" 6918 return f"{begin}{expressions}" if expressions else "" 6919 6920 def functionspecification_sql(self, expression: exp.FunctionSpecification) -> str: 6921 self.unsupported("Unsupported Inline UDFs syntax") 6922 return "" 6923 6924 def storedprocedure_sql(self, expression: exp.StoredProcedure) -> str: 6925 self.unsupported("Unsupported Stored Procedure syntax") 6926 return "" 6927 6928 def ifblock_sql(self, expression: exp.IfBlock) -> str: 6929 self.unsupported("Unsupported If block syntax") 6930 return "" 6931 6932 def casestatement_sql(self, expression: exp.CaseStatement) -> str: 6933 self.unsupported("Unsupported Case statement syntax") 6934 return "" 6935 6936 def whileblock_sql(self, expression: exp.WhileBlock) -> str: 6937 self.unsupported("Unsupported While block syntax") 6938 return "" 6939 6940 def loopblock_sql(self, expression: exp.LoopBlock) -> str: 6941 self.unsupported("Unsupported Loop block syntax") 6942 return "" 6943 6944 def repeatblock_sql(self, expression: exp.RepeatBlock) -> str: 6945 self.unsupported("Unsupported Repeat block syntax") 6946 return "" 6947 6948 def leave_sql(self, expression: exp.Leave) -> str: 6949 self.unsupported("Unsupported Leave syntax") 6950 return "" 6951 6952 def iterate_sql(self, expression: exp.Iterate) -> str: 6953 self.unsupported("Unsupported Iterate syntax") 6954 return "" 6955 6956 def execute_sql(self, expression: exp.Execute) -> str: 6957 self.unsupported("Unsupported Execute syntax") 6958 return "" 6959 6960 def executesql_sql(self, expression: exp.ExecuteSql) -> str: 6961 self.unsupported("Unsupported Execute syntax") 6962 return "" 6963 6964 def executeimmediate_sql(self, expression: exp.ExecuteImmediate) -> str: 6965 if not self.SUPPORTS_EXECUTE_IMMEDIATE: 6966 self.unsupported("EXECUTE IMMEDIATE is not supported") 6967 return "" 6968 using = self.expressions(expression, flat=True) 6969 using = f" USING {using}" if using else "" 6970 return f"EXECUTE IMMEDIATE {self.sql(expression, 'this')}{using}" 6971 6972 def altermodifysqlsecurity_sql(self, expression: exp.AlterModifySqlSecurity) -> str: 6973 props = self.expressions(expression, sep=" ") 6974 return f"MODIFY {props}" 6975 6976 def usingproperty_sql(self, expression: exp.UsingProperty) -> str: 6977 kind = expression.args.get("kind") 6978 return f"USING {kind} {self.sql(expression, 'this')}" 6979 6980 def renameindex_sql(self, expression: exp.RenameIndex) -> str: 6981 this = self.sql(expression, "this") 6982 to = self.sql(expression, "to") 6983 return f"RENAME INDEX {this} TO {to}"
Generator converts a given syntax tree to the corresponding SQL string.
Arguments:
- pretty: Whether to format the produced SQL string. Default: False.
- identify: Determines when an identifier should be quoted. Possible values are: False (default): Never quote, except in cases where it's mandatory by the dialect. True: Always quote except for specials cases. 'safe': Only quote identifiers that are case insensitive.
- normalize: Whether to normalize identifiers to lowercase. Default: False.
- pad: The pad size in a formatted string. For example, this affects the indentation of a projection in a query, relative to its nesting level. Default: 2.
- indent: The indentation size in a formatted string. For example, this affects the
indentation of subqueries and filters under a
WHEREclause. Default: 2. - normalize_functions: How to normalize function names. Possible values are: "upper" or True (default): Convert names to uppercase. "lower": Convert names to lowercase. False: Disables function name normalization.
- unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. Default ErrorLevel.WARN.
- max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. This is only relevant if unsupported_level is ErrorLevel.RAISE. Default: 3
- leading_comma: Whether the comma is leading or trailing in select expressions. This is only relevant when generating in pretty mode. Default: False
- max_text_width: The max number of characters in a segment before creating new lines in pretty mode. The default is on the smaller end because the length only represents a segment and not the true line length. Default: 80
- comments: Whether to preserve comments in the output SQL code. Default: True
Generator( pretty: bool | int | None = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: str | bool | None = None, unsupported_level: sqlglot.errors.ErrorLevel = <ErrorLevel.WARN: 'WARN'>, max_unsupported: int = 3, leading_comma: bool = False, max_text_width: int = 80, comments: bool = True, dialect: Union[str, sqlglot.dialects.Dialect, type[sqlglot.dialects.Dialect], NoneType] = None)
970 def __init__( 971 self, 972 pretty: bool | int | None = None, 973 identify: str | bool = False, 974 normalize: bool = False, 975 pad: int = 2, 976 indent: int = 2, 977 normalize_functions: str | bool | None = None, 978 unsupported_level: ErrorLevel = ErrorLevel.WARN, 979 max_unsupported: int = 3, 980 leading_comma: bool = False, 981 max_text_width: int = 80, 982 comments: bool = True, 983 dialect: DialectType = None, 984 ): 985 import sqlglot 986 import sqlglot.dialects.dialect 987 988 self.pretty = pretty if pretty is not None else sqlglot.pretty 989 self.identify = identify 990 self.normalize = normalize 991 self.pad = pad 992 self._indent = indent 993 self.unsupported_level = unsupported_level 994 self.max_unsupported = max_unsupported 995 self.leading_comma = leading_comma 996 self.max_text_width = max_text_width 997 self.comments = comments 998 self.dialect = sqlglot.dialects.dialect.Dialect.get_or_raise(dialect) 999 1000 # This is both a Dialect property and a Generator argument, so we prioritize the latter 1001 self.normalize_functions = ( 1002 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 1003 ) 1004 1005 self.unsupported_messages: list[str] = [] 1006 self._escaped_quote_end: str = ( 1007 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 1008 ) 1009 self._escaped_byte_quote_end: str = ( 1010 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.BYTE_END 1011 if self.dialect.BYTE_END 1012 else "" 1013 ) 1014 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 1015 self._identifier_escaped_sequences = self.dialect.IDENTIFIER_ESCAPED_SEQUENCES 1016 1017 self._next_name = name_sequence("_t") 1018 1019 self._identifier_start = self.dialect.IDENTIFIER_START 1020 self._identifier_end = self.dialect.IDENTIFIER_END 1021 1022 self._quote_json_path_key_using_brackets = True 1023 1024 cls = type(self) 1025 dispatch = _DISPATCH_CACHE.get(cls) 1026 if dispatch is None: 1027 dispatch = _build_dispatch(cls) 1028 _DISPATCH_CACHE[cls] = dispatch 1029 self._dispatch = dispatch
TRANSFORMS: ClassVar[dict[type[sqlglot.expressions.core.Expr], Callable[..., str]]] =
{<class 'sqlglot.expressions.query.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.query.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.core.Adjacent'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainedBy'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.AssumeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.BinaryColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.string.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.CurrentCatalog'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.SessionUser'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApiProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.EndStatement'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.math.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.HybridProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.datatypes.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAnyTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsAllTopKeys'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBContainsTopKey'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBDeleteAtPath'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONBPathExists'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObject'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.json.JSONObjectAgg'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.functions.NetFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsLeft'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.ExtendsRight'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.PositionalColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.InvisibleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.ZeroFillColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.core.SafeFunc'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.TableColumn'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ddl.TriggerExecute'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcDate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTime'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.temporal.UtcTimestamp'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.query.Variadic'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.array.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.constraints.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.properties.ForceProperty'>: <function Generator.<lambda>>}
WINDOW_FUNCS_WITH_NULL_ORDERING: ClassVar[tuple[type[sqlglot.expressions.core.Expression], ...]] =
()
SUPPORTED_JSON_PATH_PARTS: ClassVar =
{<class 'sqlglot.expressions.query.JSONPathScript'>, <class 'sqlglot.expressions.query.JSONPathRoot'>, <class 'sqlglot.expressions.query.JSONPathRecursive'>, <class 'sqlglot.expressions.query.JSONPathKey'>, <class 'sqlglot.expressions.query.JSONPathWildcard'>, <class 'sqlglot.expressions.query.JSONPathFilter'>, <class 'sqlglot.expressions.query.JSONPathUnion'>, <class 'sqlglot.expressions.query.JSONPathSubscript'>, <class 'sqlglot.expressions.query.JSONPathSelector'>, <class 'sqlglot.expressions.query.JSONPathSlice'>}
TYPE_MAPPING: ClassVar =
{<DType.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <DType.NCHAR: 'NCHAR'>: 'CHAR', <DType.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <DType.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <DType.LONGTEXT: 'LONGTEXT'>: 'TEXT', <DType.TINYTEXT: 'TINYTEXT'>: 'TEXT', <DType.BLOB: 'BLOB'>: 'VARBINARY', <DType.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <DType.LONGBLOB: 'LONGBLOB'>: 'BLOB', <DType.TINYBLOB: 'TINYBLOB'>: 'BLOB', <DType.INET: 'INET'>: 'INET', <DType.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <DType.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TYPE_PARAM_SETTINGS: ClassVar[dict[sqlglot.expressions.datatypes.DType, tuple[tuple[int, ...], tuple[int | None, ...]]]] =
{}
TIME_PART_SINGULARS: ClassVar =
{'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS: ClassVar =
{'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function <lambda>>, 'qualify': <function <lambda>>}
PROPERTIES_LOCATION: ClassVar =
{<class 'sqlglot.expressions.properties.AggregateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AllowedValuesProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AlgorithmProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApiProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ApplicationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.AutoIncrementProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.AutoRefreshProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BackupProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.BlockCompressionProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CalledOnNullInputProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CatalogProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CharacterSetProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ChecksumProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.CollateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ComputeProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.CopyGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.CopyTagsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.query.Cluster'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusteredByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ClusterProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DistributedByProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DuplicateKeyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DataBlocksizeProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.DatabaseProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DataDeletionProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DefinerProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DictRange'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.DynamicProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.DistKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.DistStyleProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.EmptyProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EncodeProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.EngineProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.EnviromentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.HandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ParameterStyleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExecuteAsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ExternalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.FallbackProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.FileFormatProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.FreespaceProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.GlobalProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.HeapProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.HybridProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.InheritsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IcebergProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.IgnoreGrantsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.IncludeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.InteractiveProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.IsolatedLoadingProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.JournalProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.LanguageProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LikeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LocationProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.LockingProperty'>: <PropertiesLocation.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.properties.LogProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.MaskingProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MaterializedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.MergeBlockRatioProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.ModuleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.NetworkProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.NoPrimaryIndexProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OnProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OnCommitProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.OptionsProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.query.Order'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.OutputModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PartitionedByProperty'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.PartitionedOfProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.PhysicalProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.constraints.PrimaryKey'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Property'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.RefreshTriggerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RemoteWithConnectionModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ReturnsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RollupProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowAccessProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.RowFormatProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatDelimitedProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.RowFormatSerdeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SampleProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SchemaCommentProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SecureProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SecurityIntegrationProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SerdeProperties'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.Set'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SettingsProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SetProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.SetConfigProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SharingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.SequenceProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.ddl.TriggerProperties'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.SortKeyProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.SqlReadWriteProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.SqlSecurityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StabilityProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageHandlerProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.StorageProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.StreamingTableProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.StrictProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.Tags'>: <PropertiesLocation.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.properties.TableSpaceProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.TemporaryProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.ToTableProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.TransientProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.TransformModelProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ddl.MergeTreeTTL'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.UnloggedProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.UsingProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.UsingTemplateProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.ViewAttributeProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.VirtualProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.VolatileProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.properties.WithDataProperty'>: <PropertiesLocation.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.properties.WithJournalTableProperty'>: <PropertiesLocation.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.properties.WithProcedureOptions'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSchemaBindingProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithSystemVersioningProperty'>: <PropertiesLocation.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.properties.WithoutRowidProperty'>: <PropertiesLocation.UNSUPPORTED: 'UNSUPPORTED'>, <class 'sqlglot.expressions.properties.ForceProperty'>: <PropertiesLocation.POST_CREATE: 'POST_CREATE'>}
WITH_SEPARATED_COMMENTS: ClassVar[tuple[type[sqlglot.expressions.core.Expr], ...]] =
(<class 'sqlglot.expressions.ddl.Command'>, <class 'sqlglot.expressions.ddl.Create'>, <class 'sqlglot.expressions.ddl.Describe'>, <class 'sqlglot.expressions.dml.Delete'>, <class 'sqlglot.expressions.ddl.Drop'>, <class 'sqlglot.expressions.query.From'>, <class 'sqlglot.expressions.dml.Insert'>, <class 'sqlglot.expressions.query.Join'>, <class 'sqlglot.expressions.query.MultitableInserts'>, <class 'sqlglot.expressions.query.Order'>, <class 'sqlglot.expressions.query.Group'>, <class 'sqlglot.expressions.query.Having'>, <class 'sqlglot.expressions.query.Select'>, <class 'sqlglot.expressions.query.SetOperation'>, <class 'sqlglot.expressions.dml.Update'>, <class 'sqlglot.expressions.query.Where'>, <class 'sqlglot.expressions.query.With'>)
EXCLUDE_COMMENTS: ClassVar[tuple[type[sqlglot.expressions.core.Expr], ...]] =
(<class 'sqlglot.expressions.core.Binary'>, <class 'sqlglot.expressions.query.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: ClassVar[tuple[type[sqlglot.expressions.core.Expr], ...]] =
(<class 'sqlglot.expressions.core.Column'>, <class 'sqlglot.expressions.core.Literal'>, <class 'sqlglot.expressions.core.Neg'>, <class 'sqlglot.expressions.core.Paren'>)
PARAMETERIZABLE_TEXT_TYPES: ClassVar =
{<DType.NCHAR: 'NCHAR'>, <DType.VARCHAR: 'VARCHAR'>, <DType.NVARCHAR: 'NVARCHAR'>, <DType.CHAR: 'CHAR'>}
RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: ClassVar[tuple[type[sqlglot.expressions.core.Expr], ...]] =
()
MOD_PAREN_PARENT_TYPES: ClassVar[tuple[type[sqlglot.expressions.core.Expr], ...]] =
(<class 'sqlglot.expressions.core.Mul'>, <class 'sqlglot.expressions.core.Div'>, <class 'sqlglot.expressions.core.IntDiv'>, <class 'sqlglot.expressions.core.Mod'>)
1031 def generate(self, expression: exp.Expr, copy: bool = True) -> str: 1032 """ 1033 Generates the SQL string corresponding to the given syntax tree. 1034 1035 Args: 1036 expression: The syntax tree. 1037 copy: Whether to copy the expression. The generator performs mutations so 1038 it is safer to copy. 1039 1040 Returns: 1041 The SQL string corresponding to `expression`. 1042 """ 1043 if copy: 1044 expression = expression.copy() 1045 1046 expression = self.preprocess(expression) 1047 1048 self.unsupported_messages = [] 1049 sql = self.sql(expression) 1050 # A trailing newline in a raw command can terminate a line comment. 1051 sql = sql.lstrip() if isinstance(expression, exp.Command) else sql.strip() 1052 1053 if self.pretty: 1054 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 1055 1056 if self.unsupported_level == ErrorLevel.IGNORE: 1057 return sql 1058 1059 if self.unsupported_level == ErrorLevel.WARN: 1060 for msg in self.unsupported_messages: 1061 logger.warning(msg) 1062 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 1063 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 1064 1065 return sql
Generates the SQL string corresponding to the given syntax tree.
Arguments:
- expression: The syntax tree.
- copy: Whether to copy the expression. The generator performs mutations so it is safer to copy.
Returns:
The SQL string corresponding to
expression.
1067 def preprocess(self, expression: exp.Expr) -> exp.Expr: 1068 """Apply generic preprocessing transformations to a given expression.""" 1069 expression = self._move_ctes_to_top_level(expression) 1070 1071 if self.ENSURE_BOOLS: 1072 import sqlglot.transforms 1073 1074 expression = sqlglot.transforms.ensure_bools(expression) 1075 1076 return expression
Apply generic preprocessing transformations to a given expression.
def
sanitize_comment(self, comment: str) -> str:
1111 def sanitize_comment(self, comment: str) -> str: 1112 comment = " " + comment if comment[0].strip() else comment 1113 comment = comment + " " if comment[-1].strip() else comment 1114 1115 # Escape block comment markers to prevent premature closure or unintended nesting. 1116 # This is necessary because single-line comments (--) are converted to block comments 1117 # (/* */) on output, and any */ in the original text would close the comment early. 1118 comment = comment.replace("*/", "* /").replace("/*", "/ *") 1119 1120 return comment
def
maybe_comment( self, sql: str, expression: sqlglot.expressions.core.Expr | None = None, comments: list[str] | None = None, separated: bool = False) -> str:
1122 def maybe_comment( 1123 self, 1124 sql: str, 1125 expression: exp.Expr | None = None, 1126 comments: list[str] | None = None, 1127 separated: bool = False, 1128 ) -> str: 1129 comments = ( 1130 ((expression and expression.comments) if comments is None else comments) # type: ignore 1131 if self.comments 1132 else None 1133 ) 1134 1135 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 1136 return sql 1137 1138 comments_list = [ 1139 f"/*{self._replace_line_breaks(self.sanitize_comment(comment))}*/" 1140 for comment in comments 1141 if comment 1142 ] 1143 1144 if not comments_list: 1145 return sql 1146 1147 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 1148 comments_sql = self.sep().join(comments_list) 1149 return ( 1150 f"{self.sep()}{comments_sql}{sql}" 1151 if not sql or sql[0].isspace() 1152 else f"{comments_sql}{self.sep()}{sql}" 1153 ) 1154 1155 return f"{sql} {' '.join(comments_list)}"
1157 def wrap(self, expression: exp.Expr | str) -> str: 1158 this_sql = ( 1159 self.sql(expression) 1160 if isinstance(expression, exp.UNWRAPPED_QUERIES) 1161 else self.sql(expression, "this") 1162 ) 1163 if not this_sql: 1164 return "()" 1165 1166 this_sql = self.indent(this_sql, level=1, pad=0) 1167 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def
indent( self, sql: str, level: int = 0, pad: int | None = None, skip_first: bool = False, skip_last: bool = False) -> str:
1183 def indent( 1184 self, 1185 sql: str, 1186 level: int = 0, 1187 pad: int | None = None, 1188 skip_first: bool = False, 1189 skip_last: bool = False, 1190 ) -> str: 1191 if not self.pretty or not sql: 1192 return sql 1193 1194 pad = self.pad if pad is None else pad 1195 lines = sql.split("\n") 1196 1197 return "\n".join( 1198 ( 1199 line 1200 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 1201 else f"{' ' * (level * self._indent + pad)}{line}" 1202 ) 1203 for i, line in enumerate(lines) 1204 )
def
sql( self, expression: str | sqlglot.expressions.core.Expr | None, key: str | None = None, comment: bool = True) -> str:
1206 def sql( 1207 self, 1208 expression: str | exp.Expr | None, 1209 key: str | None = None, 1210 comment: bool = True, 1211 ) -> str: 1212 if not expression: 1213 return "" 1214 1215 if isinstance(expression, str): 1216 return expression 1217 1218 if key: 1219 value = expression.args.get(key) 1220 if value: 1221 return self.sql(value) 1222 return "" 1223 1224 handler = self._dispatch.get(expression.__class__) 1225 1226 if handler: 1227 sql = handler(self, expression) 1228 elif isinstance(expression, exp.Func): 1229 sql = self.function_fallback_sql(expression) 1230 elif isinstance(expression, exp.Property): 1231 sql = self.property_sql(expression) 1232 else: 1233 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 1234 1235 return self.maybe_comment(sql, expression) if self.comments and comment else sql
1242 def cache_sql(self, expression: exp.Cache) -> str: 1243 lazy = " LAZY" if expression.args.get("lazy") else "" 1244 table = self.sql(expression, "this") 1245 options = expression.args.get("options") 1246 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 1247 sql = self.sql(expression, "expression") 1248 sql = f" AS{self.sep()}{sql}" if sql else "" 1249 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 1250 return self.prepend_ctes(expression, sql)
1256 def column_parts(self, expression: exp.Column) -> str: 1257 if expression.args.get("shadow") and self.dialect.PROJECTION_ALIASES_SHADOW_SOURCE_NAMES: 1258 # The qualifier would be captured by a colliding projection alias (see qualify_columns) 1259 return self.sql(expression, "this") 1260 1261 return ".".join( 1262 self.sql(part) 1263 for part in ( 1264 expression.args.get("catalog"), 1265 expression.args.get("db"), 1266 expression.args.get("table"), 1267 expression.args.get("this"), 1268 ) 1269 if part 1270 )
1272 def column_sql(self, expression: exp.Column) -> str: 1273 join_mark = " (+)" if expression.args.get("join_mark") else "" 1274 1275 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 1276 join_mark = "" 1277 self.unsupported("Outer join syntax using the (+) operator is not supported.") 1278 1279 return f"{self.column_parts(expression)}{join_mark}"
1290 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 1291 column = self.sql(expression, "this") 1292 kind = self.sql(expression, "kind") 1293 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 1294 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 1295 kind = f"{sep}{kind}" if kind else "" 1296 constraints = f" {constraints}" if constraints else "" 1297 position = self.sql(expression, "position") 1298 position = f" {position}" if position else "" 1299 1300 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1301 kind = "" 1302 1303 return f"{exists}{column}{kind}{constraints}{position}"
def
columnconstraint_sql( self, expression: sqlglot.expressions.constraints.ColumnConstraint) -> str:
def
computedcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.ComputedColumnConstraint) -> str:
1310 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1311 this = self.sql(expression, "this") 1312 if expression.args.get("not_null"): 1313 persisted = " PERSISTED NOT NULL" 1314 elif expression.args.get("persisted"): 1315 persisted = " PERSISTED" 1316 else: 1317 persisted = "" 1318 1319 return f"AS {this}{persisted}"
def
autoincrementcolumnconstraint_sql( self, _: sqlglot.expressions.constraints.AutoIncrementColumnConstraint) -> str:
def
compresscolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.GeneratedAsIdentityColumnConstraint) -> str:
1332 def generatedasidentitycolumnconstraint_sql( 1333 self, expression: exp.GeneratedAsIdentityColumnConstraint 1334 ) -> str: 1335 this = "" 1336 if expression.this is not None: 1337 on_null = " ON NULL" if expression.args.get("on_null") else "" 1338 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1339 1340 start = expression.args.get("start") 1341 start = f"START WITH {start}" if start else "" 1342 increment = expression.args.get("increment") 1343 increment = f" INCREMENT BY {increment}" if increment else "" 1344 minvalue = expression.args.get("minvalue") 1345 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1346 maxvalue = expression.args.get("maxvalue") 1347 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1348 cycle = expression.args.get("cycle") 1349 cycle_sql = "" 1350 1351 if cycle is not None: 1352 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1353 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1354 1355 sequence_opts = "" 1356 if start or increment or cycle_sql: 1357 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1358 sequence_opts = f" ({sequence_opts.strip()})" 1359 1360 expr = self.sql(expression, "expression") 1361 expr = f"({expr})" if expr else "IDENTITY" 1362 1363 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.GeneratedAsRowColumnConstraint) -> str:
1365 def generatedasrowcolumnconstraint_sql( 1366 self, expression: exp.GeneratedAsRowColumnConstraint 1367 ) -> str: 1368 start = "START" if expression.args.get("start") else "END" 1369 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1370 return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def
periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.constraints.PeriodForSystemTimeConstraint) -> str:
def
notnullcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.NotNullColumnConstraint) -> str:
def
primarykeycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.PrimaryKeyColumnConstraint) -> str:
1382 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1383 on_conflict = self.sql(expression, "on_conflict") 1384 on_conflict = f" {on_conflict}" if on_conflict else "" 1385 desc = expression.args.get("desc") 1386 if desc is not None: 1387 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}{on_conflict}" 1388 options = self.expressions(expression, key="options", flat=True, sep=" ") 1389 options = f" {options}" if options else "" 1390 include = self.sql(expression, "include") 1391 return f"PRIMARY KEY{on_conflict}{include}{options}"
def
uniquecolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.UniqueColumnConstraint) -> str:
1393 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1394 this = self.sql(expression, "this") 1395 this = f" {this}" if this else "" 1396 index_type = expression.args.get("index_type") 1397 index_type = f" USING {index_type}" if index_type else "" 1398 on_conflict = self.sql(expression, "on_conflict") 1399 on_conflict = f" {on_conflict}" if on_conflict else "" 1400 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1401 options = self.expressions(expression, key="options", flat=True, sep=" ") 1402 options = f" {options}" if options else "" 1403 include = self.sql(expression, "include") 1404 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{include}{options}"
def
inoutcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.InOutColumnConstraint) -> str:
1406 def inoutcolumnconstraint_sql(self, expression: exp.InOutColumnConstraint) -> str: 1407 input_ = expression.args.get("input_") 1408 output = expression.args.get("output") 1409 variadic = expression.args.get("variadic") 1410 1411 # VARIADIC is mutually exclusive with IN/OUT/INOUT 1412 if variadic: 1413 return "VARIADIC" 1414 1415 if input_ and output: 1416 return f"IN{self.INOUT_SEPARATOR}OUT" 1417 if input_: 1418 return "IN" 1419 if output: 1420 return "OUT" 1421 1422 return ""
def
createable_sql( self, expression: sqlglot.expressions.ddl.Create, locations: collections.defaultdict) -> str:
1427 def create_sql(self, expression: exp.Create) -> str: 1428 kind = self.sql(expression, "kind") 1429 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1430 1431 properties = expression.args.get("properties") 1432 1433 if ( 1434 kind == "TRIGGER" 1435 and properties 1436 and properties.expressions 1437 and isinstance(properties.expressions[0], exp.TriggerProperties) 1438 and properties.expressions[0].args.get("constraint") 1439 ): 1440 kind = f"CONSTRAINT {kind}" 1441 1442 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1443 1444 this = self.createable_sql(expression, properties_locs) 1445 1446 properties_sql = "" 1447 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1448 exp.Properties.Location.POST_WITH 1449 ): 1450 props_ast = exp.Properties( 1451 expressions=[ 1452 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1453 *properties_locs[exp.Properties.Location.POST_WITH], 1454 ] 1455 ) 1456 props_ast.parent = expression 1457 properties_sql = self.sql(props_ast) 1458 1459 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1460 properties_sql = self.sep() + properties_sql 1461 elif not self.pretty: 1462 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1463 properties_sql = f" {properties_sql}" 1464 1465 begin = " BEGIN" if expression.args.get("begin") else "" 1466 1467 expression_sql = self.sql(expression, "expression") 1468 if expression_sql: 1469 expression_sql = f"{begin}{self.sep()}{expression_sql}" 1470 1471 if not isinstance(expression.expression, exp.MacroOverloads) and ( 1472 self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return) 1473 ): 1474 postalias_props_sql = "" 1475 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1476 postalias_props_sql = self.properties( 1477 exp.Properties( 1478 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1479 ), 1480 wrapped=False, 1481 ) 1482 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1483 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1484 1485 postindex_props_sql = "" 1486 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1487 postindex_props_sql = self.properties( 1488 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1489 wrapped=False, 1490 prefix=" ", 1491 ) 1492 1493 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1494 indexes = f" {indexes}" if indexes else "" 1495 index_sql = indexes + postindex_props_sql 1496 1497 replace = " OR REPLACE" if expression.args.get("replace") else "" 1498 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1499 unique = " UNIQUE" if expression.args.get("unique") else "" 1500 1501 clustered = expression.args.get("clustered") 1502 if clustered is None: 1503 clustered_sql = "" 1504 elif clustered: 1505 clustered_sql = " CLUSTERED COLUMNSTORE" 1506 else: 1507 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1508 1509 postcreate_props_sql = "" 1510 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1511 postcreate_props_sql = self.properties( 1512 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1513 sep=" ", 1514 prefix=" ", 1515 wrapped=False, 1516 ) 1517 1518 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1519 1520 postexpression_props_sql = "" 1521 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1522 postexpression_props_sql = self.properties( 1523 exp.Properties( 1524 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1525 ), 1526 sep=" ", 1527 prefix=" ", 1528 wrapped=False, 1529 ) 1530 1531 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1532 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1533 no_schema_binding = ( 1534 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1535 ) 1536 1537 clone = self.sql(expression, "clone") 1538 clone = f" {clone}" if clone else "" 1539 1540 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1541 properties_expression = f"{expression_sql}{properties_sql}" 1542 else: 1543 properties_expression = f"{properties_sql}{expression_sql}" 1544 1545 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1546 return self.prepend_ctes(expression, expression_sql)
1548 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1549 start = self.sql(expression, "start") 1550 start = f"START WITH {start}" if start else "" 1551 increment = self.sql(expression, "increment") 1552 increment = f" INCREMENT BY {increment}" if increment else "" 1553 minvalue = self.sql(expression, "minvalue") 1554 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1555 maxvalue = self.sql(expression, "maxvalue") 1556 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1557 owned = self.sql(expression, "owned") 1558 owned = f" OWNED BY {owned}" if owned else "" 1559 1560 cache = expression.args.get("cache") 1561 if cache is None: 1562 cache_str = "" 1563 elif cache is True: 1564 cache_str = " CACHE" 1565 else: 1566 cache_str = f" CACHE {cache}" 1567 1568 options = self.expressions(expression, key="options", flat=True, sep=" ") 1569 options = f" {options}" if options else "" 1570 1571 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1573 def triggerproperties_sql(self, expression: exp.TriggerProperties) -> str: 1574 timing = expression.args.get("timing", "") 1575 events = " OR ".join(self.sql(event) for event in expression.args.get("events") or []) 1576 timing_events = f"{timing} {events}".strip() if timing or events else "" 1577 1578 parts = [timing_events, "ON", self.sql(expression, "table")] 1579 1580 if referenced_table := expression.args.get("referenced_table"): 1581 parts.extend(["FROM", self.sql(referenced_table)]) 1582 1583 if deferrable := expression.args.get("deferrable"): 1584 parts.append(deferrable) 1585 1586 if initially := expression.args.get("initially"): 1587 parts.append(f"INITIALLY {initially}") 1588 1589 if referencing := expression.args.get("referencing"): 1590 parts.append(self.sql(referencing)) 1591 1592 if for_each := expression.args.get("for_each"): 1593 parts.append(f"FOR EACH {for_each}") 1594 1595 if when := expression.args.get("when"): 1596 parts.append(f"WHEN ({self.sql(when)})") 1597 1598 parts.append(self.sql(expression, "execute")) 1599 1600 return self.sep().join(parts)
1602 def triggerreferencing_sql(self, expression: exp.TriggerReferencing) -> str: 1603 parts = [] 1604 1605 if old_alias := expression.args.get("old"): 1606 parts.append(f"OLD TABLE AS {self.sql(old_alias)}") 1607 1608 if new_alias := expression.args.get("new"): 1609 parts.append(f"NEW TABLE AS {self.sql(new_alias)}") 1610 1611 return f"REFERENCING {' '.join(parts)}"
1620 def clone_sql(self, expression: exp.Clone) -> str: 1621 this = self.sql(expression, "this") 1622 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1623 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1624 return f"{shallow}{keyword} {this}"
1626 def describe_sql(self, expression: exp.Describe) -> str: 1627 style = expression.args.get("style") 1628 style = f" {style}" if style else "" 1629 partition = self.sql(expression, "partition") 1630 partition = f" {partition}" if partition else "" 1631 format = self.sql(expression, "format") 1632 format = f" {format}" if format else "" 1633 as_json = " AS JSON" if expression.args.get("as_json") else "" 1634 1635 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}{as_json}"
1647 def with_sql(self, expression: exp.With) -> str: 1648 udfs = self.expressions(expression, key="udfs", flat=True) 1649 udfs = f"WITH {udfs}" if udfs else "" 1650 1651 sql = self.expressions(expression, flat=True) 1652 1653 recursive = ( 1654 "RECURSIVE " 1655 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1656 else "" 1657 ) 1658 search = self.sql(expression, "search") 1659 search = f" {search}" if search else "" 1660 cycle = self.sql(expression, "cycle") 1661 cycle = f" {cycle}" if cycle else "" 1662 1663 sql = f"WITH {recursive}{sql}{search}{cycle}" if sql else "" 1664 return f"{udfs} {sql}" if udfs and sql else f"{udfs}{sql}"
1666 def cte_sql(self, expression: exp.CTE) -> str: 1667 alias = expression.args.get("alias") 1668 if alias: 1669 alias.add_comments(expression.pop_comments()) 1670 1671 alias_sql = self.sql(expression, "alias") 1672 1673 materialized = expression.args.get("materialized") 1674 if materialized is False: 1675 materialized = "NOT MATERIALIZED " 1676 elif materialized: 1677 materialized = "MATERIALIZED " 1678 1679 key_expressions = self.expressions(expression, key="key_expressions", flat=True) 1680 key_expressions = f" USING KEY ({key_expressions})" if key_expressions else "" 1681 1682 return f"{alias_sql}{key_expressions} AS {materialized or ''}{self.wrap(expression)}"
1684 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1685 alias = self.sql(expression, "this") 1686 columns = self.expressions(expression, key="columns", flat=True) 1687 columns = f"({columns})" if columns else "" 1688 1689 if ( 1690 columns 1691 and not self.SUPPORTS_TABLE_ALIAS_COLUMNS 1692 and not (self.SUPPORTS_NAMED_CTE_COLUMNS and isinstance(expression.parent, exp.CTE)) 1693 ): 1694 columns = "" 1695 self.unsupported("Named columns are not supported in table alias.") 1696 1697 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1698 alias = self._next_name() 1699 1700 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.query.HexString, binary_function_repr: str | None = None) -> str:
1708 def hexstring_sql( 1709 self, expression: exp.HexString, binary_function_repr: str | None = None 1710 ) -> str: 1711 if expression.args.get("is_character"): 1712 self.unsupported("Hexadecimal character literals are only supported in Teradata") 1713 this = expression.this.replace("'", "''") 1714 return f"'{this}'XC" 1715 1716 this = self.sql(expression, "this") 1717 is_integer_type = expression.args.get("is_integer") 1718 1719 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1720 not self.dialect.HEX_START and not binary_function_repr 1721 ): 1722 # Integer representation will be returned if: 1723 # - The read dialect treats the hex value as integer literal but not the write 1724 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1725 return f"{int(this, 16)}" 1726 1727 if not is_integer_type: 1728 # Read dialect treats the hex value as BINARY/BLOB 1729 if binary_function_repr: 1730 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1731 return self.func(binary_function_repr, exp.Literal.string(this)) 1732 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1733 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1734 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1735 1736 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1738 def bytestring_sql(self, expression: exp.ByteString) -> str: 1739 this = self.sql(expression, "this") 1740 is_bytes = bool(expression.args.get("is_bytes")) 1741 if is_bytes and self.BYTE_STRING_FUNCTION: 1742 # Hex digits can be quoted directly without escaping. 1743 return self.func(self.BYTE_STRING_FUNCTION, f"'{this.encode('latin-1').hex()}'") 1744 1745 if self.dialect.BYTE_START: 1746 escaped_byte_string = self.escape_str( 1747 this, 1748 escape_backslash=bool( 1749 self.dialect.tokenizer_class.NUMERIC_ESCAPES 1750 or self.dialect.tokenizer_class.DROP_UNKNOWN_ESCAPES 1751 ), 1752 delimiter=self.dialect.BYTE_END, 1753 escaped_delimiter=self._escaped_byte_quote_end, 1754 is_byte_string=True, 1755 is_bytes=is_bytes, 1756 ) 1757 delimited_byte_string = ( 1758 f"{self.dialect.BYTE_START}{escaped_byte_string}{self.dialect.BYTE_END}" 1759 ) 1760 if is_bytes and not self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1761 return self.sql( 1762 exp.cast(delimited_byte_string, exp.DType.BINARY, dialect=self.dialect) 1763 ) 1764 if not is_bytes and self.dialect.BYTE_STRING_IS_BYTES_TYPE: 1765 return self.sql( 1766 exp.cast(delimited_byte_string, exp.DType.VARCHAR, dialect=self.dialect) 1767 ) 1768 1769 return delimited_byte_string 1770 1771 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1772 return self.sql(exp.Literal.string(this)) 1773 1774 self.unsupported(f"Byte strings are not supported for {self.dialect.__class__.__name__}") 1775 return ""
1777 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1778 this = self.sql(expression, "this") 1779 escape = expression.args.get("escape") 1780 unicode_start = self.dialect.UNICODE_START 1781 1782 if unicode_start: 1783 escape_substitute = r"\\\1" 1784 left_quote, right_quote = unicode_start, self.dialect.UNICODE_END or "" 1785 else: 1786 escape_substitute = r"\\u\1" 1787 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1788 1789 if escape: 1790 escape_pattern = re.compile(rf"{re.escape(escape.name)}(\d+)") 1791 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1792 else: 1793 escape_pattern = ESCAPED_UNICODE_RE 1794 escape_sql = "" 1795 1796 if not unicode_start or (escape and not self.SUPPORTS_UESCAPE): 1797 this = escape_pattern.sub(self.UNICODE_SUBSTITUTE or escape_substitute, this) 1798 1799 if unicode_start: 1800 # A Unicode literal only escapes its delimiter by doubling it; the escape character 1801 # introduces a code point, so the dialect's ordinary string escapes don't apply here 1802 this = self._replace_line_breaks(this).replace(right_quote, right_quote * 2) 1803 else: 1804 this = self.escape_str(this, escape_backslash=False) 1805 1806 return f"{left_quote}{this}{right_quote}{escape_sql}"
1808 def rawstring_sql(self, expression: exp.RawString) -> str: 1809 string = expression.this 1810 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1811 string = string.replace("\\", "\\\\") 1812 1813 string = self.escape_str(string, escape_backslash=False) 1814 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
def
datatype_param_bound_limiter( self, expression: sqlglot.expressions.datatypes.DataType, type_value: sqlglot.expressions.datatypes.DType, defaults: tuple[int, ...], bounds: tuple[int | None, ...]) -> sqlglot.expressions.datatypes.DataType:
1822 def datatype_param_bound_limiter( 1823 self, 1824 expression: exp.DataType, 1825 type_value: exp.DType, 1826 defaults: tuple[int, ...], 1827 bounds: tuple[int | None, ...], 1828 ) -> exp.DataType: 1829 params = expression.expressions 1830 1831 if not params: 1832 if defaults: 1833 expression.set( 1834 "expressions", 1835 [exp.DataTypeParam(this=exp.Literal.number(d)) for d in defaults], 1836 ) 1837 return expression 1838 1839 if not bounds: 1840 return expression 1841 1842 for i, param in enumerate(params): 1843 bound = bounds[i] if i < len(bounds) else None 1844 if bound is None: 1845 continue 1846 1847 param_value = param.this if isinstance(param, exp.DataTypeParam) else param 1848 value = ( 1849 param_value.to_py() 1850 if isinstance(param_value, exp.Literal) and param_value.is_number 1851 else None 1852 ) 1853 if isinstance(value, (int, Decimal)) and value > bound: 1854 self.unsupported( 1855 f"{type_value.value} parameter {param_value.name} exceeds " 1856 f"{self.dialect.__class__.__name__}'s maximum of {bound}; capping" 1857 ) 1858 params[i] = exp.DataTypeParam(this=exp.Literal.number(bound)) 1859 1860 return expression
1862 def datatype_sql(self, expression: exp.DataType) -> str: 1863 nested = "" 1864 values = "" 1865 1866 expr_nested = expression.args.get("nested") 1867 type_value = expression.this 1868 1869 if ( 1870 not expr_nested 1871 and isinstance(type_value, exp.DType) 1872 and (settings := self.TYPE_PARAM_SETTINGS.get(type_value)) 1873 ): 1874 expression = self.datatype_param_bound_limiter(expression, type_value, *settings) 1875 1876 interior = ( 1877 self.expressions( 1878 expression, dynamic=True, new_line=True, skip_first=True, skip_last=True 1879 ) 1880 if expr_nested and self.pretty 1881 else self.expressions(expression, flat=True) 1882 ) 1883 1884 if type_value in self.UNSUPPORTED_TYPES: 1885 self.unsupported( 1886 f"Data type {type_value.value} is not supported when targeting {self.dialect.__class__.__name__}" 1887 ) 1888 1889 type_sql: t.Any = "" 1890 if type_value == exp.DType.USERDEFINED and expression.args.get("kind"): 1891 type_sql = self.sql(expression, "kind") 1892 elif type_value == exp.DType.CHARACTER_SET: 1893 char = f"CHAR({interior})" if interior else "CHAR" 1894 return f"{char} CHARACTER SET {self.sql(expression, 'kind')}" 1895 else: 1896 type_sql = ( 1897 self.TYPE_MAPPING.get(type_value, type_value.value) 1898 if isinstance(type_value, exp.DType) 1899 else type_value 1900 ) 1901 1902 if interior: 1903 if expr_nested: 1904 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1905 if expression.args.get("values") is not None: 1906 delimiters = ("[", "]") if type_value == exp.DType.ARRAY else ("(", ")") 1907 values = self.expressions(expression, key="values", flat=True) 1908 values = f"{delimiters[0]}{values}{delimiters[1]}" 1909 elif type_value == exp.DType.INTERVAL: 1910 nested = f" {interior}" 1911 else: 1912 nested = f"({interior})" 1913 1914 type_sql = f"{type_sql}{nested}{values}" 1915 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1916 exp.DType.TIMETZ, 1917 exp.DType.TIMESTAMPTZ, 1918 ): 1919 type_sql = f"{type_sql} WITH TIME ZONE" 1920 1921 collate = self.sql(expression, "collate") 1922 if collate: 1923 type_sql = f"{type_sql} COLLATE {collate}" 1924 1925 return type_sql
1927 def directory_sql(self, expression: exp.Directory) -> str: 1928 local = "LOCAL " if expression.args.get("local") else "" 1929 row_format = self.sql(expression, "row_format") 1930 row_format = f" {row_format}" if row_format else "" 1931 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1933 def delete_sql(self, expression: exp.Delete) -> str: 1934 hint = self.sql(expression, "hint") 1935 this = self.sql(expression, "this") 1936 this = f" FROM {this}" if this else "" 1937 using = self.expressions(expression, key="using") 1938 using = f" USING {using}" if using else "" 1939 cluster = self.sql(expression, "cluster") 1940 cluster = f" {cluster}" if cluster else "" 1941 where = self.sql(expression, "where") 1942 returning = self.sql(expression, "returning") 1943 order = self.sql(expression, "order") 1944 limit = self.sql(expression, "limit") 1945 tables = self.expressions(expression, key="tables") 1946 tables = f" {tables}" if tables else "" 1947 if self.RETURNING_END: 1948 expression_sql = f"{this}{using}{cluster}{where}{returning}{order}{limit}" 1949 else: 1950 expression_sql = f"{returning}{this}{using}{cluster}{where}{order}{limit}" 1951 return self.prepend_ctes(expression, f"DELETE{hint}{tables}{expression_sql}")
1953 def drop_sql(self, expression: exp.Drop) -> str: 1954 tables = self.expressions(expression, key="tables", flat=True) 1955 expressions = self.expressions(expression, flat=True) 1956 expressions = f" ({expressions})" if expressions else "" 1957 kind = expression.args["kind"] 1958 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1959 iceberg = ( 1960 " ICEBERG" 1961 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 1962 else "" 1963 ) 1964 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1965 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1966 on_cluster = self.sql(expression, "cluster") 1967 on_cluster = f" {on_cluster}" if on_cluster else "" 1968 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1969 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1970 cascade = " CASCADE" if expression.args.get("cascade") else "" 1971 restrict = " RESTRICT" if expression.args.get("restrict") else "" 1972 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1973 purge = " PURGE" if expression.args.get("purge") else "" 1974 sync = " SYNC" if expression.args.get("sync") else "" 1975 force = " FORCE" if expression.args.get("force") else "" 1976 return f"DROP{temporary}{materialized}{iceberg} {kind}{concurrently_sql}{exists_sql}{tables}{on_cluster}{expressions}{cascade}{restrict}{constraints}{purge}{sync}{force}"
1978 def set_operation(self, expression: exp.SetOperation) -> str: 1979 op_type = type(expression) 1980 op_name = op_type.key.upper() 1981 1982 distinct = expression.args.get("distinct") 1983 if ( 1984 distinct is False 1985 and op_type in (exp.Except, exp.Intersect) 1986 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1987 ): 1988 self.unsupported(f"{op_name} ALL is not supported") 1989 1990 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1991 1992 if distinct is None: 1993 distinct = default_distinct 1994 if distinct is None: 1995 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1996 1997 if distinct is default_distinct: 1998 distinct_or_all = "" 1999 else: 2000 distinct_or_all = " DISTINCT" if distinct else " ALL" 2001 2002 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 2003 side_kind = f"{side_kind} " if side_kind else "" 2004 2005 by_name = " BY NAME" if expression.args.get("by_name") else "" 2006 on = self.expressions(expression, key="on", flat=True) 2007 on = f" ON ({on})" if on else "" 2008 2009 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
2011 def set_operations(self, expression: exp.SetOperation) -> str: 2012 if not self.SET_OP_MODIFIERS: 2013 limit = expression.args.get("limit") 2014 order = expression.args.get("order") 2015 offset = expression.args.get("offset") 2016 2017 if limit or order or offset: 2018 select = self._move_ctes_to_top_level( 2019 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 2020 ) 2021 2022 for arg in ("limit", "order", "offset"): 2023 if value := expression.args.get(arg): 2024 select.set(arg, value.pop()) 2025 return self.sql(select) 2026 2027 sqls: list[str] = [] 2028 stack: list[str | exp.Expr | int | None] = [expression] 2029 depth = 0 2030 open_parens = "" 2031 2032 while stack: 2033 node = stack.pop() 2034 2035 if isinstance(node, int): 2036 # Closes a plain grouping opened below, restoring its depth 2037 depth = node 2038 sqls[-1] += self.sep("") + self.indent(")", level=depth, pad=0) 2039 elif isinstance(node, exp.SetOperation): 2040 stack.append(node.expression) 2041 stack.append( 2042 self.maybe_comment( 2043 self.set_operation(node), comments=node.comments, separated=True 2044 ) 2045 ) 2046 left = node.this 2047 if ( 2048 not self.SET_OP_PARENTHESIZED_OPERANDS 2049 and not self.dialect.INTERSECT_BINDS_TIGHTER_THAN_UNION_AND_EXCEPT 2050 ): 2051 # Left grouping is implicit, so skip the `SELECT * FROM (...)` wrapper: 2052 # it renames duplicate columns and deepens recursion. Inner CTEs and 2053 # modifiers still need the wrapper. 2054 wrappers: list[exp.Subquery] = [] 2055 inner = left 2056 while isinstance(inner, exp.Subquery) and inner.is_wrapper: 2057 wrappers.append(inner) 2058 inner = inner.this 2059 2060 if ( 2061 isinstance(inner, exp.SetOperation) 2062 and not inner.args.get("with_") 2063 and not any(inner.args.get(key) for key in exp.QUERY_MODIFIERS) 2064 ): 2065 for wrapper in wrappers: 2066 inner.add_comments(wrapper.pop_comments()) 2067 left = inner 2068 elif ( 2069 self.SET_OP_PARENTHESIZED_OPERANDS 2070 and isinstance(left, exp.Subquery) 2071 and left.is_wrapper 2072 and not left.comments 2073 and isinstance(left.this, exp.SetOperation) 2074 and not left.this.args.get("with_") 2075 and not any(left.this.args.get(key) for key in exp.QUERY_MODIFIERS) 2076 ): 2077 # Write a plain grouping's parentheses here rather than recursing through 2078 # subquery_sql: left-to-right chains nest one grouping per INTERSECT, and 2079 # long ones would exhaust the stack. The depth pushed here marks the close. 2080 open_parens += self.indent("(", level=depth, pad=0) + self.sep("") 2081 stack.append(depth) 2082 depth += 1 2083 left = left.this 2084 stack.append(left) 2085 else: 2086 if ( 2087 not self.SET_OP_LIMITS 2088 and isinstance(node, exp.Select) 2089 and node.args.get("limit") 2090 ): 2091 node = node.subquery(copy=False) 2092 if not self.SET_OP_PARENTHESIZED_OPERANDS and isinstance(node, exp.Subquery): 2093 node = exp.select("*").from_(node, copy=False) 2094 sqls.append(open_parens + self.indent(self.sql(node), level=depth, pad=0)) 2095 open_parens = "" 2096 2097 this = self.sep().join(sqls) 2098 this = self.query_modifiers(expression, this) 2099 return self.prepend_ctes(expression, this)
2101 def fetch_sql(self, expression: exp.Fetch) -> str: 2102 direction = expression.args.get("direction") 2103 direction = f" {direction}" if direction else "" 2104 count = self.sql(expression, "count") 2105 count = f" {count}" if count else "" 2106 limit_options = self.sql(expression, "limit_options") 2107 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 2108 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
2110 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 2111 percent = " PERCENT" if expression.args.get("percent") else "" 2112 rows = " ROWS" if expression.args.get("rows") else "" 2113 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 2114 if not with_ties and rows: 2115 with_ties = " ONLY" 2116 return f"{percent}{rows}{with_ties}"
2123 def per_sql(self, expression: exp.Per) -> str: 2124 keys = ", ".join( 2125 f"{self.sql(key, 'this')} {self.sql(key, 'with_fill')}" 2126 if isinstance(key, exp.Ordered) and key.args.get("with_fill") 2127 else self.sql(key) 2128 for key in expression.expressions 2129 ) 2130 return f"{self.sql(expression, 'this')} PER ({keys})"
2139 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 2140 using = self.sql(expression, "using") 2141 using = f" USING {using}" if using else "" 2142 columns = self.expressions(expression, key="columns", flat=True) 2143 columns = f"({columns})" if columns else "" 2144 partition_by = self.expressions(expression, key="partition_by", flat=True) 2145 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 2146 where = self.sql(expression, "where") 2147 include = self.expressions(expression, key="include", flat=True) 2148 if include: 2149 include = f" INCLUDE ({include})" 2150 with_storage = self.expressions(expression, key="with_storage", flat=True) 2151 with_storage = f" WITH ({with_storage})" if with_storage else "" 2152 tablespace = self.sql(expression, "tablespace") 2153 if tablespace: 2154 prefix = "" if isinstance(expression.parent, exp.Index) else " USING INDEX" 2155 tablespace = f"{prefix} TABLESPACE {tablespace}" 2156 on = self.sql(expression, "on") 2157 on = f" ON {on}" if on else "" 2158 2159 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
2161 def index_sql(self, expression: exp.Index) -> str: 2162 unique = "UNIQUE " if expression.args.get("unique") else "" 2163 primary = "PRIMARY " if expression.args.get("primary") else "" 2164 amp = "AMP " if expression.args.get("amp") else "" 2165 name = self.sql(expression, "this") 2166 name = f"{name} " if name else "" 2167 table = self.sql(expression, "table") 2168 table = f"{self.INDEX_ON} {table}" if table else "" 2169 2170 index = "INDEX " if not table else "" 2171 2172 params = self.sql(expression, "params") 2173 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
2175 def dynamicidentifier_sql(self, expression: exp.DynamicIdentifier) -> str: 2176 this = expression.this 2177 if this and this.is_string: 2178 resolved = maybe_parse(this.name).sql(self.dialect) 2179 if "expressions" in expression.args: 2180 # `IDENTIFIER(...)` invoked as a function, e.g. `IDENTIFIER('my_func')(1, 2)` 2181 # We can't safely emit the call to other dialects since name/arg semantics may differ 2182 self.unsupported( 2183 "Transpiling dynamically-invoked IDENTIFIER() functions is unsupported" 2184 ) 2185 return resolved 2186 self.unsupported("IDENTIFIER() with non-literal arguments is not supported") 2187 return self.func("IDENTIFIER", this)
2189 def identifier_sql(self, expression: exp.Identifier) -> str: 2190 text = expression.name 2191 lower = text.lower() 2192 quoted = expression.quoted 2193 text = lower if self.normalize and not quoted else text 2194 if self._identifier_escaped_sequences: 2195 for char, escaped in self._identifier_escaped_sequences.items(): 2196 text = text.replace(char, escaped) 2197 text = text.replace(self._identifier_end, self._escaped_identifier_end) 2198 if ( 2199 quoted 2200 or self.dialect.can_quote(expression, self.identify) 2201 or lower in self.RESERVED_KEYWORDS 2202 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 2203 ): 2204 text = ( 2205 f"{self._identifier_start}{self._replace_line_breaks(text)}{self._identifier_end}" 2206 ) 2207 return text
2222 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 2223 input_format = self.sql(expression, "input_format") 2224 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 2225 output_format = self.sql(expression, "output_format") 2226 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 2227 return self.sep().join((input_format, output_format))
2237 def properties_sql(self, expression: exp.Properties) -> str: 2238 root_properties = [] 2239 with_properties = [] 2240 2241 for p in expression.expressions: 2242 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2243 if p_loc == exp.Properties.Location.POST_WITH: 2244 with_properties.append(p) 2245 elif p_loc == exp.Properties.Location.POST_SCHEMA: 2246 root_properties.append(p) 2247 2248 root_props_ast = exp.Properties(expressions=root_properties) 2249 root_props_ast.parent = expression.parent 2250 2251 with_props_ast = exp.Properties(expressions=with_properties) 2252 with_props_ast.parent = expression.parent 2253 2254 root_props = self.root_properties(root_props_ast) 2255 with_props = self.with_properties(with_props_ast) 2256 2257 if root_props and with_props and not self.pretty: 2258 with_props = " " + with_props 2259 2260 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.properties.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
2267 def properties( 2268 self, 2269 properties: exp.Properties, 2270 prefix: str = "", 2271 sep: str = ", ", 2272 suffix: str = "", 2273 wrapped: bool = True, 2274 ) -> str: 2275 if properties.expressions: 2276 expressions = self.expressions(properties, sep=sep, indent=False) 2277 if expressions: 2278 expressions = self.wrap(expressions) if wrapped else expressions 2279 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 2280 return ""
def
locate_properties( self, properties: sqlglot.expressions.properties.Properties) -> collections.defaultdict:
2285 def locate_properties(self, properties: exp.Properties) -> defaultdict: 2286 properties_locs = defaultdict(list) 2287 for p in properties.expressions: 2288 p_loc = self.PROPERTIES_LOCATION[p.__class__] 2289 if p_loc != exp.Properties.Location.UNSUPPORTED: 2290 properties_locs[p_loc].append(p) 2291 else: 2292 self.unsupported(f"Unsupported property {p.key}") 2293 2294 return properties_locs
def
property_name( self, expression: sqlglot.expressions.properties.Property, string_key: bool = False) -> str:
2301 def property_sql(self, expression: exp.Property) -> str: 2302 property_cls = expression.__class__ 2303 if property_cls == exp.Property: 2304 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 2305 2306 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 2307 if not property_name: 2308 self.unsupported(f"Unsupported property {expression.key}") 2309 return "" 2310 2311 return f"{property_name}={self.sql(expression, 'this')}"
2316 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 2317 if self.SUPPORTS_CREATE_TABLE_LIKE: 2318 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 2319 options = f" {options}" if options else "" 2320 2321 like = f"LIKE {self.sql(expression, 'this')}{options}" 2322 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 2323 like = f"({like})" 2324 2325 return like 2326 2327 if expression.expressions: 2328 self.unsupported("Transpilation of LIKE property options is unsupported") 2329 2330 select = exp.select("*").from_(expression.this).limit(0) 2331 return f"AS {self.sql(select)}"
2338 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 2339 no = "NO " if expression.args.get("no") else "" 2340 local = expression.args.get("local") 2341 local = f"{local} " if local else "" 2342 dual = "DUAL " if expression.args.get("dual") else "" 2343 before = "BEFORE " if expression.args.get("before") else "" 2344 after = "AFTER " if expression.args.get("after") else "" 2345 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
freespaceproperty_sql( self, expression: sqlglot.expressions.properties.FreespaceProperty) -> str:
def
mergeblockratioproperty_sql( self, expression: sqlglot.expressions.properties.MergeBlockRatioProperty) -> str:
2361 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 2362 if expression.args.get("no"): 2363 return "NO MERGEBLOCKRATIO" 2364 if expression.args.get("default"): 2365 return "DEFAULT MERGEBLOCKRATIO" 2366 2367 percent = " PERCENT" if expression.args.get("percent") else "" 2368 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
def
datablocksizeproperty_sql( self, expression: sqlglot.expressions.properties.DataBlocksizeProperty) -> str:
2375 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 2376 default = expression.args.get("default") 2377 minimum = expression.args.get("minimum") 2378 maximum = expression.args.get("maximum") 2379 if default or minimum or maximum: 2380 if default: 2381 prop = "DEFAULT" 2382 elif minimum: 2383 prop = "MINIMUM" 2384 else: 2385 prop = "MAXIMUM" 2386 return f"{prop} DATABLOCKSIZE" 2387 units = expression.args.get("units") 2388 units = f" {units}" if units else "" 2389 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql( self, expression: sqlglot.expressions.properties.BlockCompressionProperty) -> str:
2391 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 2392 autotemp = expression.args.get("autotemp") 2393 always = expression.args.get("always") 2394 default = expression.args.get("default") 2395 manual = expression.args.get("manual") 2396 never = expression.args.get("never") 2397 2398 if autotemp is not None: 2399 prop = f"AUTOTEMP({self.expressions(autotemp)})" 2400 elif always: 2401 prop = "ALWAYS" 2402 elif default: 2403 prop = "DEFAULT" 2404 elif manual: 2405 prop = "MANUAL" 2406 elif never: 2407 prop = "NEVER" 2408 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql( self, expression: sqlglot.expressions.properties.IsolatedLoadingProperty) -> str:
2410 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 2411 no = expression.args.get("no") 2412 no = " NO" if no else "" 2413 concurrent = expression.args.get("concurrent") 2414 concurrent = " CONCURRENT" if concurrent else "" 2415 target = self.sql(expression, "target") 2416 target = f" {target}" if target else "" 2417 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
def
partitionboundspec_sql( self, expression: sqlglot.expressions.properties.PartitionBoundSpec) -> str:
2419 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 2420 if isinstance(expression.this, list): 2421 return f"IN ({self.expressions(expression, key='this', flat=True)})" 2422 if expression.this: 2423 modulus = self.sql(expression, "this") 2424 remainder = self.sql(expression, "expression") 2425 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 2426 2427 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 2428 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 2429 return f"FROM ({from_expressions}) TO ({to_expressions})"
def
partitionedofproperty_sql( self, expression: sqlglot.expressions.properties.PartitionedOfProperty) -> str:
2431 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 2432 this = self.sql(expression, "this") 2433 2434 for_values_or_default = expression.expression 2435 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 2436 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 2437 else: 2438 for_values_or_default = " DEFAULT" 2439 2440 return f"PARTITION OF {this}{for_values_or_default}"
2442 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 2443 kind = expression.args.get("kind") 2444 this = f" {self.sql(expression, 'this')}" if expression.this else "" 2445 for_or_in = expression.args.get("for_or_in") 2446 for_or_in = f" {for_or_in}" if for_or_in else "" 2447 lock_type = expression.args.get("lock_type") 2448 override = " OVERRIDE" if expression.args.get("override") else "" 2449 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
2455 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 2456 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 2457 statistics = expression.args.get("statistics") 2458 statistics_sql = "" 2459 if statistics is not None: 2460 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 2461 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.properties.WithSystemVersioningProperty) -> str:
2463 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 2464 this = self.sql(expression, "this") 2465 this = f"HISTORY_TABLE={this}" if this else "" 2466 data_consistency: str | None = self.sql(expression, "data_consistency") 2467 data_consistency = ( 2468 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 2469 ) 2470 retention_period: str | None = self.sql(expression, "retention_period") 2471 retention_period = ( 2472 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 2473 ) 2474 2475 if this: 2476 on_sql = self.func("ON", this, data_consistency, retention_period) 2477 else: 2478 on_sql = "ON" if expression.args.get("on") else "OFF" 2479 2480 sql = f"SYSTEM_VERSIONING={on_sql}" 2481 2482 return f"WITH({sql})" if expression.args.get("with_") else sql
2484 def insert_sql(self, expression: exp.Insert) -> str: 2485 hint = self.sql(expression, "hint") 2486 overwrite = expression.args.get("overwrite") 2487 2488 if isinstance(expression.this, exp.Directory): 2489 this = " OVERWRITE" if overwrite else " INTO" 2490 else: 2491 this = self.INSERT_OVERWRITE if overwrite else " INTO" 2492 2493 stored = self.sql(expression, "stored") 2494 stored = f" {stored}" if stored else "" 2495 alternative = expression.args.get("alternative") 2496 alternative = f" OR {alternative}" if alternative else "" 2497 ignore = " IGNORE" if expression.args.get("ignore") else "" 2498 is_function = expression.args.get("is_function") 2499 if is_function: 2500 this = f"{this} FUNCTION" 2501 this = f"{this} {self.sql(expression, 'this')}" 2502 2503 exists = " IF EXISTS" if expression.args.get("exists") else "" 2504 where = self.sql(expression, "where") 2505 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 2506 using = self.expressions(expression, key="using", flat=True) 2507 using = f"{self.sep()}REPLACE USING ({using})" if using else "" 2508 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 2509 on_conflict = self.sql(expression, "conflict") 2510 on_conflict = f" {on_conflict}" if on_conflict else "" 2511 by_name = " BY NAME" if expression.args.get("by_name") else "" 2512 default_values = "DEFAULT VALUES" if expression.args.get("default") else "" 2513 returning = self.sql(expression, "returning") 2514 2515 if self.RETURNING_END: 2516 expression_sql = f"{expression_sql}{on_conflict}{default_values}{returning}" 2517 else: 2518 expression_sql = f"{returning}{expression_sql}{on_conflict}" 2519 2520 partition_by = self.sql(expression, "partition") 2521 partition_by = f" {partition_by}" if partition_by else "" 2522 settings = self.sql(expression, "settings") 2523 settings = f" {settings}" if settings else "" 2524 2525 source = self.sql(expression, "source") 2526 source = f"TABLE {source}" if source else "" 2527 2528 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{using}{expression_sql}{source}" 2529 return self.prepend_ctes(expression, sql)
2547 def onconflict_sql(self, expression: exp.OnConflict) -> str: 2548 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 2549 2550 constraint = self.sql(expression, "constraint") 2551 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 2552 2553 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 2554 if conflict_keys: 2555 conflict_keys = f"({conflict_keys})" 2556 2557 index_predicate = self.sql(expression, "index_predicate") 2558 conflict_keys = f"{conflict_keys}{index_predicate} " 2559 2560 action = self.sql(expression, "action") 2561 2562 expressions = self.expressions(expression, flat=True) 2563 if expressions: 2564 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 2565 expressions = f" {set_keyword}{expressions}" 2566 2567 where = self.sql(expression, "where") 2568 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql( self, expression: sqlglot.expressions.properties.RowFormatDelimitedProperty) -> str:
2573 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 2574 fields = self.sql(expression, "fields") 2575 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 2576 escaped = self.sql(expression, "escaped") 2577 escaped = f" ESCAPED BY {escaped}" if escaped else "" 2578 items = self.sql(expression, "collection_items") 2579 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 2580 keys = self.sql(expression, "map_keys") 2581 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 2582 lines = self.sql(expression, "lines") 2583 lines = f" LINES TERMINATED BY {lines}" if lines else "" 2584 null = self.sql(expression, "null") 2585 null = f" NULL DEFINED AS {null}" if null else "" 2586 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
2614 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 2615 table = self.table_parts(expression) 2616 only = "ONLY " if expression.args.get("only") else "" 2617 partition = self.sql(expression, "partition") 2618 partition = f" {partition}" if partition else "" 2619 version = self.sql(expression, "version") 2620 version = f" {version}" if version else "" 2621 alias = self.sql(expression, "alias") 2622 alias = f"{sep}{alias}" if alias else "" 2623 2624 sample = self.sql(expression, "sample") 2625 post_alias = "" 2626 pre_alias = "" 2627 2628 if self.dialect.ALIAS_POST_TABLESAMPLE: 2629 pre_alias = sample 2630 else: 2631 post_alias = sample 2632 2633 if self.dialect.ALIAS_POST_VERSION: 2634 pre_alias = f"{pre_alias}{version}" 2635 else: 2636 post_alias = f"{post_alias}{version}" 2637 2638 hints = self.expressions(expression, key="hints", sep=" ") 2639 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2640 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2641 joins = self.indent( 2642 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2643 ) 2644 laterals = self.expressions(expression, key="laterals", sep="") 2645 2646 file_format = self.sql(expression, "format") 2647 pattern = self.sql(expression, "pattern") 2648 if file_format: 2649 pattern = f", PATTERN => {pattern}" if pattern else "" 2650 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2651 elif pattern: 2652 file_format = f" (PATTERN => {pattern})" 2653 2654 ordinality = expression.args.get("ordinality") or "" 2655 if ordinality: 2656 ordinality = f" WITH ORDINALITY{alias}" 2657 alias = "" 2658 2659 when = self.sql(expression, "when") 2660 if when: 2661 if self.HISTORICAL_DATA_POST_ALIAS: 2662 alias = f"{alias} {when}" 2663 else: 2664 table = f"{table} {when}" 2665 2666 changes = self.sql(expression, "changes") 2667 changes = f" {changes}" if changes else "" 2668 2669 rows_from = self.expressions(expression, key="rows_from") 2670 if rows_from: 2671 table = f"ROWS FROM {self.wrap(rows_from)}" 2672 2673 indexed = expression.args.get("indexed") 2674 if indexed is not None: 2675 indexed = f" INDEXED BY {self.sql(indexed)}" if indexed else " NOT INDEXED" 2676 else: 2677 indexed = "" 2678 2679 return f"{only}{table}{changes}{partition}{file_format}{pre_alias}{alias}{indexed}{hints}{pivots}{post_alias}{joins}{laterals}{ordinality}"
2685 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2686 table = self.func("TABLE", expression.this) 2687 alias = self.sql(expression, "alias") 2688 alias = f" AS {alias}" if alias else "" 2689 sample = self.sql(expression, "sample") 2690 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2691 joins = self.indent( 2692 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2693 ) 2694 return f"{table}{alias}{pivots}{sample}{joins}"
def
tablesample_sql( self, expression: sqlglot.expressions.query.TableSample, tablesample_keyword: str | None = None) -> str:
2696 def tablesample_sql( 2697 self, 2698 expression: exp.TableSample, 2699 tablesample_keyword: str | None = None, 2700 ) -> str: 2701 if expression.expressions: 2702 self.unsupported("Multiple sample sets are not supported") 2703 return "" 2704 2705 method = self.sql(expression, "method") 2706 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2707 numerator = self.sql(expression, "bucket_numerator") 2708 denominator = self.sql(expression, "bucket_denominator") 2709 field = self.sql(expression, "bucket_field") 2710 field = f" ON {field}" if field else "" 2711 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2712 seed = self.sql(expression, "seed") 2713 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2714 2715 size = self.sql(expression, "size") 2716 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2717 size = f"{size} ROWS" 2718 2719 percent = self.sql(expression, "percent") 2720 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2721 percent = f"{percent} PERCENT" 2722 2723 expr = f"{bucket}{percent}{size}" 2724 if self.TABLESAMPLE_REQUIRES_PARENS: 2725 expr = f"({expr})" 2726 2727 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2808 def pivot_sql(self, expression: exp.Pivot) -> str: 2809 expressions = self.expressions(expression, flat=True) 2810 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2811 2812 group = self.sql(expression, "group") 2813 2814 if expression.this: 2815 this = self.sql(expression, "this") 2816 if not expressions: 2817 sql = f"UNPIVOT {this}" 2818 else: 2819 on = f"{self.seg('ON')} {expressions}" 2820 into = self.sql(expression, "into") 2821 into = f"{self.seg('INTO')} {into}" if into else "" 2822 using = self.expressions(expression, key="using", flat=True) 2823 using = f"{self.seg('USING')} {using}" if using else "" 2824 sql = f"{direction} {this}{on}{into}{using}{group}" 2825 return self.prepend_ctes(expression, sql) 2826 2827 if not expression.unpivot: 2828 # Wrap IN-list values with explicit aliases where the target dialect would differ 2829 new_field_exprs = self._pivot_in_value_aliases(expression) 2830 if new_field_exprs is not None: 2831 expression.fields[0].set("expressions", new_field_exprs) 2832 2833 alias = self.sql(expression, "alias") 2834 if alias: 2835 alias = f" AS {alias}" if self.PIVOT_ALIAS_WITH_AS else f" {alias}" 2836 2837 fields = self.expressions( 2838 expression, 2839 "fields", 2840 sep=" ", 2841 dynamic=True, 2842 new_line=True, 2843 skip_first=True, 2844 skip_last=True, 2845 ) 2846 2847 include_nulls = expression.args.get("include_nulls") 2848 if include_nulls is not None: 2849 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2850 else: 2851 nulls = "" 2852 2853 default_on_null = self.sql(expression, "default_on_null") 2854 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2855 sql = f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}" 2856 return self.prepend_ctes(expression, sql)
2899 def update_sql(self, expression: exp.Update) -> str: 2900 hint = self.sql(expression, "hint") 2901 alternative = self.sql(expression, "alternative") 2902 if alternative: 2903 if self.dialect.SUPPORTS_UPDATE_OR or self.dialect == "": 2904 alternative = f" OR {alternative}" 2905 else: 2906 self.unsupported(f"UPDATE OR {alternative} is not supported") 2907 alternative = "" 2908 this = self.sql(expression, "this") 2909 join_sql, from_sql = self._update_from_joins_sql(expression) 2910 set_sql = self.expressions(expression, flat=True) 2911 where_sql = self.sql(expression, "where") 2912 returning = self.sql(expression, "returning") 2913 order = self.sql(expression, "order") 2914 limit = self.sql(expression, "limit") 2915 if self.RETURNING_END: 2916 expression_sql = f"{from_sql}{where_sql}{returning}" 2917 else: 2918 expression_sql = f"{returning}{from_sql}{where_sql}" 2919 options = self.expressions(expression, key="options") 2920 options = f" OPTION({options})" if options else "" 2921 sql = f"UPDATE{hint}{alternative} {this}{join_sql} SET {set_sql}{expression_sql}{order}{limit}{options}" 2922 return self.prepend_ctes(expression, sql)
def
values_sql( self, expression: sqlglot.expressions.query.Values, values_as_table: bool = True) -> str:
2924 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2925 values_as_table = values_as_table and self.VALUES_AS_TABLE 2926 2927 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2928 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2929 args = self.expressions(expression) 2930 alias = self.sql(expression, "alias") 2931 values = f"VALUES{self.seg('')}{args}" 2932 values = ( 2933 f"({values})" 2934 if self.WRAP_DERIVED_VALUES 2935 and ( 2936 alias 2937 or isinstance(expression.parent, (exp.From, exp.Table, exp.MatchRecognize)) 2938 ) 2939 else values 2940 ) 2941 values = self.query_modifiers(expression, values) 2942 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2943 return f"{values} AS {alias}{pivots}" if alias else f"{values}{pivots}" 2944 2945 # Converts `VALUES...` expression into a series of select unions. 2946 alias_node = expression.args.get("alias") 2947 column_names = alias_node and alias_node.columns 2948 2949 selects: list[exp.Query] = [] 2950 2951 for i, tup in enumerate(expression.expressions): 2952 row = tup.expressions 2953 2954 if i == 0 and column_names: 2955 row = [ 2956 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2957 ] 2958 2959 selects.append(exp.Select(expressions=row)) 2960 2961 if self.pretty: 2962 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2963 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2964 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2965 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2966 for key in ("order", "limit", "offset"): 2967 if value := expression.args.get(key): 2968 query.set(key, value.pop()) 2969 subquery = query.subquery(alias_node and alias_node.this, copy=False) 2970 subquery.set("pivots", expression.args.pop("pivots", None)) 2971 return self.subquery_sql(subquery) 2972 2973 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2974 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2975 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2976 return f"({self.query_modifiers(expression, unions)}){alias}{pivots}"
@unsupported_args('expressions')
def
into_sql(self, expression: sqlglot.expressions.query.Into) -> str:
2981 @unsupported_args("expressions") 2982 def into_sql(self, expression: exp.Into) -> str: 2983 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2984 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2985 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2998 def rollupindex_sql(self, expression: exp.RollupIndex) -> str: 2999 this = self.sql(expression, "this") 3000 3001 columns = self.expressions(expression, flat=True) 3002 3003 from_sql = self.sql(expression, "from_index") 3004 from_sql = f" FROM {from_sql}" if from_sql else "" 3005 3006 properties = expression.args.get("properties") 3007 properties_sql = ( 3008 f" {self.properties(properties, prefix='PROPERTIES')}" if properties else "" 3009 ) 3010 3011 return f"{this}({columns}){from_sql}{properties_sql}"
3020 def group_sql(self, expression: exp.Group) -> str: 3021 group_by_all = expression.args.get("all") 3022 if group_by_all is True: 3023 modifier = " ALL" 3024 elif group_by_all is False: 3025 modifier = " DISTINCT" 3026 else: 3027 modifier = "" 3028 3029 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 3030 3031 grouping_sets = self.expressions(expression, key="grouping_sets") 3032 cube = self.expressions(expression, key="cube") 3033 rollup = self.expressions(expression, key="rollup") 3034 3035 groupings = csv( 3036 self.seg(grouping_sets) if grouping_sets else "", 3037 self.seg(cube) if cube else "", 3038 self.seg(rollup) if rollup else "", 3039 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 3040 sep=self.GROUPINGS_SEP, 3041 ) 3042 3043 if ( 3044 expression.expressions 3045 and groupings 3046 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 3047 ): 3048 add_separator = True 3049 3050 if grouping_sets: 3051 if self.SUPPORTS_GROUPING_SETS_AS_SUFFIX: 3052 add_separator = False 3053 else: 3054 self.unsupported( 3055 "GROUPING SETS without a comma after GROUP BY expressions is not supported" 3056 ) 3057 3058 if add_separator: 3059 group_by = f"{group_by}{self.GROUPINGS_SEP}" 3060 3061 return f"{group_by}{groupings}"
3073 def connect_sql(self, expression: exp.Connect) -> str: 3074 start = self.sql(expression, "start") 3075 start = self.seg(f"START WITH {start}") if start else "" 3076 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 3077 connect = self.sql(expression, "connect") 3078 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 3079 return start + connect
3084 def join_sql(self, expression: exp.Join, join_op: str | None = None) -> str: 3085 if ( 3086 match_condition := expression.args.get("match_condition") 3087 ) and not self.SUPPORTS_MATCH_CONDITION: 3088 if self.MATCH_CONDITION_IN_ON and not expression.args.get("using"): 3089 expression = expression.on(match_condition) 3090 expression.set("match_condition", None) 3091 # Snowflake ASOF joins preserve unmatched left rows. 3092 expression.set("side", "LEFT") 3093 else: 3094 self.unsupported("MATCH_CONDITION is not supported") 3095 3096 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 3097 side = None 3098 else: 3099 side = expression.side 3100 3101 op_sql = " ".join( 3102 op 3103 for op in ( 3104 expression.method, 3105 "GLOBAL" if expression.args.get("global_") else None, 3106 side, 3107 expression.kind, 3108 expression.hint if self.JOIN_HINTS else None, 3109 "DIRECTED" if expression.args.get("directed") and self.DIRECTED_JOINS else None, 3110 ) 3111 if op 3112 ) 3113 match_cond = self.sql(expression, "match_condition") 3114 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 3115 nearest = self.sql(expression, "nearest") 3116 nearest = f" {nearest}" if nearest else "" 3117 on_sql = self.sql(expression, "on") 3118 using = expression.args.get("using") 3119 3120 if not on_sql and using: 3121 on_sql = csv(*(self.sql(column) for column in using)) 3122 3123 this = expression.this 3124 this_sql = self.sql(this) 3125 3126 exprs = self.expressions(expression) 3127 if exprs: 3128 this_sql = f"{this_sql},{self.seg(exprs)}" 3129 3130 if on_sql: 3131 on_sql = self.indent(on_sql, skip_first=True) 3132 space = self.seg(" " * self.pad) if self.pretty else " " 3133 if using: 3134 on_sql = f"{space}USING ({on_sql})" 3135 else: 3136 on_sql = f"{space}ON {on_sql}" 3137 elif not op_sql and not nearest: 3138 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 3139 return f" {this_sql}" 3140 3141 return f", {this_sql}" 3142 3143 if join_op: 3144 op_sql = join_op 3145 elif op_sql != "STRAIGHT_JOIN": 3146 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 3147 3148 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3149 return f"{self.seg(op_sql)} {this_sql}{match_cond}{nearest}{on_sql}{pivots}"
3151 def nearest_sql(self, expression: exp.Nearest) -> str: 3152 if not self.SUPPORTS_NEAREST_JOIN: 3153 self.unsupported("NEAREST joins are not supported") 3154 3155 approximate = "APPROX " if expression.args.get("approximate") else "" 3156 metric = "SIMILARITY" if expression.args.get("similarity") else "DISTANCE" 3157 return f"{approximate}NEAREST {self.sql(expression, 'count')} BY {metric} {self.sql(expression, 'this')}"
def
lambda_sql( self, expression: sqlglot.expressions.query.Lambda, arrow_sep: str = '->', wrap: bool = True) -> str:
3164 def lateral_op(self, expression: exp.Lateral) -> str: 3165 cross_apply = expression.args.get("cross_apply") 3166 3167 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 3168 if cross_apply is True: 3169 op = "INNER JOIN " 3170 elif cross_apply is False: 3171 op = "LEFT JOIN " 3172 else: 3173 op = "" 3174 3175 return f"{op}LATERAL"
3177 def lateral_sql(self, expression: exp.Lateral) -> str: 3178 this = self.sql(expression, "this") 3179 3180 if expression.args.get("view"): 3181 alias = expression.args["alias"] 3182 columns = self.expressions(alias, key="columns", flat=True) 3183 table = f" {alias.name}" if alias.name else "" 3184 columns = f" AS {columns}" if columns else "" 3185 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 3186 return f"{op_sql}{self.sep()}{this}{table}{columns}" 3187 3188 table_alias = expression.args.get("alias") 3189 offset = expression.this.args.get("offset") 3190 3191 if ( 3192 self.UNNEST_WITH_ORDINALITY 3193 and table_alias 3194 and isinstance(expression.this, exp.Unnest) 3195 and isinstance(offset, exp.Identifier) 3196 ): 3197 # UNNEST ... WITH ORDINALITY stores the ordinality column's name in Unnest.offset 3198 table_alias = table_alias.copy() 3199 table_alias.append("columns", offset.copy()) 3200 3201 alias = self.sql(table_alias) 3202 alias = f" AS {alias}" if alias else "" 3203 3204 ordinality = expression.args.get("ordinality") or "" 3205 if ordinality: 3206 ordinality = f" WITH ORDINALITY{alias}" 3207 alias = "" 3208 3209 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
3211 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 3212 this = self.sql(expression, "this") 3213 3214 if expression.is_limit_all and not self.dialect.SUPPORTS_LIMIT_ALL: 3215 return this 3216 3217 args = [ 3218 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 3219 for e in (expression.args.get(k) for k in ("offset", "expression")) 3220 if e 3221 ] 3222 3223 args_sql = ", ".join(self.sql(e) for e in args) 3224 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 3225 expressions = self.expressions(expression, flat=True) 3226 limit_options = self.sql(expression, "limit_options") 3227 expressions = f" BY {expressions}" if expressions else "" 3228 3229 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
3231 def offset_sql(self, expression: exp.Offset) -> str: 3232 this = self.sql(expression, "this") 3233 value = expression.expression 3234 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 3235 expressions = self.expressions(expression, flat=True) 3236 expressions = f" BY {expressions}" if expressions else "" 3237 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
3239 def setitem_sql(self, expression: exp.SetItem) -> str: 3240 kind = self.sql(expression, "kind") 3241 if not self.SET_ASSIGNMENT_REQUIRES_VARIABLE_KEYWORD and kind == "VARIABLE": 3242 kind = "" 3243 else: 3244 kind = f"{kind} " if kind else "" 3245 this = self.sql(expression, "this") 3246 expressions = self.expressions(expression) 3247 collate = self.sql(expression, "collate") 3248 collate = f" COLLATE {collate}" if collate else "" 3249 global_ = "GLOBAL " if expression.args.get("global_") else "" 3250 return f"{global_}{kind}{this}{expressions}{collate}"
3257 def queryband_sql(self, expression: exp.QueryBand) -> str: 3258 this = self.sql(expression, "this") 3259 update = " UPDATE" if expression.args.get("update") else "" 3260 scope = self.sql(expression, "scope") 3261 scope = f" FOR {scope}" if scope else "" 3262 3263 return f"QUERY_BAND = {this}{update}{scope}"
3268 def lock_sql(self, expression: exp.Lock) -> str: 3269 if not self.LOCKING_READS_SUPPORTED: 3270 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 3271 return "" 3272 3273 update = expression.args["update"] 3274 key = expression.args.get("key") 3275 if update: 3276 lock_type = "FOR NO KEY UPDATE" if key else "FOR UPDATE" 3277 else: 3278 lock_type = "FOR KEY SHARE" if key else "FOR SHARE" 3279 expressions = self.expressions(expression, flat=True) 3280 expressions = f" OF {expressions}" if expressions else "" 3281 wait = expression.args.get("wait") 3282 3283 if wait is not None: 3284 if isinstance(wait, exp.Literal): 3285 wait = f" WAIT {self.sql(wait)}" 3286 else: 3287 wait = " NOWAIT" if wait else " SKIP LOCKED" 3288 3289 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str( self, text: str, escape_backslash: bool = True, delimiter: str | None = None, escaped_delimiter: str | None = None, is_byte_string: bool = False, is_bytes: bool = False) -> str:
3297 def escape_str( 3298 self, 3299 text: str, 3300 escape_backslash: bool = True, 3301 delimiter: str | None = None, 3302 escaped_delimiter: str | None = None, 3303 is_byte_string: bool = False, 3304 is_bytes: bool = False, 3305 ) -> str: 3306 if is_byte_string: 3307 supports_escape_sequences = self.dialect.BYTE_STRINGS_SUPPORT_ESCAPED_SEQUENCES 3308 else: 3309 supports_escape_sequences = self.dialect.STRINGS_SUPPORT_ESCAPED_SEQUENCES 3310 3311 if supports_escape_sequences: 3312 text = "".join( 3313 self.dialect.ESCAPED_SEQUENCES.get(ch, ch) if escape_backslash or ch != "\\" else ch 3314 for ch in text 3315 ) 3316 3317 if is_bytes and "x" in self.dialect.tokenizer_class.NUMERIC_ESCAPES: 3318 # Escape high bytes so they aren't re-encoded as UTF-8 characters. 3319 text = _HIGH_BYTE_RE.sub(lambda m: f"\\x{ord(m.group()):02x}", text) 3320 3321 delimiter = delimiter or self.dialect.QUOTE_END 3322 escaped_delimiter = escaped_delimiter or self._escaped_quote_end 3323 3324 return self._replace_line_breaks(text).replace(delimiter, escaped_delimiter)
3326 def loaddata_sql(self, expression: exp.LoadData) -> str: 3327 is_overwrite = expression.args.get("overwrite") 3328 overwrite = " OVERWRITE" if is_overwrite else "" 3329 this = self.sql(expression, "this") 3330 3331 files = expression.args.get("files") 3332 if files: 3333 files_sql = self.expressions(files, flat=True) 3334 files_sql = f"FILES{self.wrap(files_sql)}" 3335 if is_overwrite: 3336 this = f" {this}" 3337 elif expression.args.get("temp"): 3338 this = f" INTO TEMP TABLE {this}" 3339 else: 3340 this = f" INTO TABLE {this}" 3341 return f"LOAD DATA{overwrite}{this} FROM {files_sql}" 3342 3343 local = " LOCAL" if expression.args.get("local") else "" 3344 inpath = f" INPATH {self.sql(expression, 'inpath')}" 3345 this = f" INTO TABLE {this}" 3346 partition = self.sql(expression, "partition") 3347 partition = f" {partition}" if partition else "" 3348 input_format = self.sql(expression, "input_format") 3349 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 3350 serde = self.sql(expression, "serde") 3351 serde = f" SERDE {serde}" if serde else "" 3352 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
3366 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 3367 this = self.sql(expression, "this") 3368 this = f"{this} " if this else this 3369 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 3370 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=bool(this) or flat)
3372 def withfill_sql(self, expression: exp.WithFill) -> str: 3373 from_sql = self.sql(expression, "from_") 3374 from_sql = f" FROM {from_sql}" if from_sql else "" 3375 to_sql = self.sql(expression, "to") 3376 to_sql = f" TO {to_sql}" if to_sql else "" 3377 step_sql = self.sql(expression, "step") 3378 step_sql = f" STEP {step_sql}" if step_sql else "" 3379 interpolated_values = [ 3380 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 3381 if isinstance(e, exp.Alias) 3382 else self.sql(e, "this") 3383 for e in expression.args.get("interpolate") or [] 3384 ] 3385 interpolate = ( 3386 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 3387 ) 3388 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
3442 def ordered_sql(self, expression: exp.Ordered) -> str: 3443 desc = expression.args.get("desc") 3444 asc = not desc 3445 3446 nulls_first = expression.args.get("nulls_first") 3447 nulls_last = not nulls_first 3448 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 3449 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 3450 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 3451 3452 this = self.sql(expression, "this") 3453 3454 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 3455 nulls_sort_change = "" 3456 if nulls_first and ( 3457 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 3458 ): 3459 nulls_sort_change = " NULLS FIRST" 3460 elif ( 3461 nulls_last 3462 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 3463 and not nulls_are_last 3464 ): 3465 nulls_sort_change = " NULLS LAST" 3466 3467 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 3468 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 3469 window = expression.find_ancestor(exp.Window, exp.Select) 3470 3471 if isinstance(window, exp.Window): 3472 window_this = window.this 3473 if isinstance(window_this, (exp.IgnoreNulls, exp.RespectNulls)): 3474 window_this = window_this.this 3475 spec = window.args.get("spec") 3476 else: 3477 window_this = None 3478 spec = None 3479 3480 # Some window functions (e.g. LAST_VALUE, RANK) support NULLS FIRST/LAST 3481 # without a spec or with a ROWS spec, but not with RANGE 3482 if not ( 3483 isinstance(window_this, self.WINDOW_FUNCS_WITH_NULL_ORDERING) 3484 and (not spec or spec.text("kind").upper() == "ROWS") 3485 ): 3486 if window_this and spec: 3487 self.unsupported( 3488 f"'{nulls_sort_change.strip()}' translation not supported in window function {window_this.sql_name()}" 3489 ) 3490 nulls_sort_change = "" 3491 elif self.NULL_ORDERING_SUPPORTED is False and ( 3492 (asc and nulls_sort_change == " NULLS LAST") 3493 or (desc and nulls_sort_change == " NULLS FIRST") 3494 ): 3495 # BigQuery does not allow these ordering/nulls combinations when used under 3496 # an aggregation func or under a window containing one 3497 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 3498 3499 if isinstance(ancestor, exp.Window): 3500 ancestor = ancestor.this 3501 if isinstance(ancestor, exp.AggFunc): 3502 self.unsupported( 3503 f"'{nulls_sort_change.strip()}' translation not supported for aggregate function {ancestor.sql_name()} with {sort_order} sort order" 3504 ) 3505 nulls_sort_change = "" 3506 elif self.NULL_ORDERING_SUPPORTED is None: 3507 if expression.this.is_int: 3508 self.unsupported( 3509 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 3510 ) 3511 elif not isinstance(expression.this, exp.Rand): 3512 resolved = self._resolve_ordered_for_null_ordering_simulation(expression) 3513 target = self.sql(resolved) if resolved is not None else this 3514 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 3515 this = f"CASE WHEN {target} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {target}" 3516 nulls_sort_change = "" 3517 3518 with_fill = self.sql(expression, "with_fill") 3519 with_fill = f" {with_fill}" if with_fill else "" 3520 3521 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
def
matchrecognizemeasure_sql(self, expression: sqlglot.expressions.query.MatchRecognizeMeasure) -> str:
3531 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 3532 partition = self.partition_by_sql(expression) 3533 order = self.sql(expression, "order") 3534 measures = self.expressions(expression, key="measures") 3535 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 3536 rows = self.sql(expression, "rows") 3537 rows = self.seg(rows) if rows else "" 3538 after = self.sql(expression, "after") 3539 after = self.seg(after) if after else "" 3540 pattern = self.sql(expression, "pattern") 3541 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 3542 subset = self.expressions(expression, key="subset") 3543 subset = self.seg(f"SUBSET{self.seg(subset)}") if subset else "" 3544 definition_sqls = [ 3545 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 3546 for definition in expression.args.get("define") or [] 3547 ] 3548 definitions = self.expressions(sqls=definition_sqls) 3549 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 3550 body = "".join( 3551 ( 3552 partition, 3553 order, 3554 measures, 3555 rows, 3556 after, 3557 pattern, 3558 subset, 3559 define, 3560 ) 3561 ).lstrip() 3562 alias = self.sql(expression, "alias") 3563 alias = f" {alias}" if alias else "" 3564 sample = self.sql(expression, "sample") 3565 joins = self.indent( 3566 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 3567 ) 3568 source = self.sql(expression, "this") 3569 return f"{source}{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}{sample}{joins}"
3571 def query_modifiers(self, expression: exp.Expr, *sqls: str) -> str: 3572 limit = expression.args.get("limit") 3573 3574 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 3575 count = limit.args.get("count") 3576 # "FETCH FIRST ROWS ONLY" without a count means one row per the SQL 3577 # standard; emitting a bare "LIMIT" here would produce invalid SQL. 3578 limit = exp.Limit( 3579 expression=exp.maybe_copy(count) if count is not None else exp.Literal.number(1) 3580 ) 3581 elif ( 3582 self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit) and not limit.is_limit_all 3583 ): 3584 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 3585 3586 return csv( 3587 *sqls, 3588 *[self.sql(join) for join in expression.args.get("joins") or []], 3589 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 3590 self.sql(expression, "prewhere"), 3591 self.sql(expression, "where"), 3592 self.sql(expression, "connect"), 3593 self.sql(expression, "group"), 3594 self.sql(expression, "having"), 3595 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 3596 self.sql(expression, "order"), 3597 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 3598 *self.after_limit_modifiers(expression), 3599 self.sql(expression, "for_"), 3600 self.options_modifier(expression), 3601 sep="", 3602 )
3608 def forclause_sql(self, expression: exp.ForClause) -> str: 3609 kind = expression.args["kind"] 3610 if kind == "BROWSE": 3611 return f"{self.sep()}FOR BROWSE" 3612 # FOR XML/JSON always carry at least AUTO/PATH. An empty rendering means 3613 # the target dialect doesn't support QueryOption, so we drop the clause. 3614 options = self.expressions(expression, key="expressions") 3615 if not options: 3616 return "" 3617 return f"{self.sep()}FOR {kind}{self.seg(options)}"
def
offset_limit_modifiers( self, expression: sqlglot.expressions.core.Expr, fetch: bool, limit: sqlglot.expressions.query.Fetch | sqlglot.expressions.query.Limit | None) -> list[str]:
3636 def select_sql(self, expression: exp.Select) -> str: 3637 into = expression.args.get("into") 3638 if not self.SUPPORTS_SELECT_INTO and into: 3639 into.pop() 3640 3641 hint = self.sql(expression, "hint") 3642 distinct = self.sql(expression, "distinct") 3643 distinct = f" {distinct}" if distinct else "" 3644 kind = self.sql(expression, "kind") 3645 3646 limit = expression.args.get("limit") 3647 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 3648 top = self.limit_sql(limit, top=True) 3649 limit.pop() 3650 else: 3651 top = "" 3652 3653 expressions = self.expressions(expression) 3654 3655 if kind: 3656 if kind in self.SELECT_KINDS: 3657 kind = f" AS {kind}" 3658 else: 3659 if kind == "STRUCT": 3660 expressions = self.expressions( 3661 sqls=[ 3662 self.sql( 3663 exp.Struct( 3664 expressions=[ 3665 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 3666 if isinstance(e, exp.Alias) 3667 else e 3668 for e in expression.expressions 3669 ] 3670 ) 3671 ) 3672 ] 3673 ) 3674 kind = "" 3675 3676 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 3677 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 3678 3679 exclude = expression.args.get("exclude") 3680 3681 if not self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3682 exclude_sql = self.expressions(sqls=exclude, flat=True) 3683 expressions = f"{expressions}{self.seg('EXCLUDE')} ({exclude_sql})" 3684 3685 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 3686 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 3687 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 3688 expressions = f"{self.sep()}{expressions}" if expressions else expressions 3689 sql = self.query_modifiers( 3690 expression, 3691 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 3692 self.sql(expression, "into", comment=False), 3693 self.sql(expression, "from_", comment=False), 3694 ) 3695 3696 # If both the CTE and SELECT clauses have comments, generate the latter earlier 3697 if expression.args.get("with_"): 3698 sql = self.maybe_comment(sql, expression) 3699 expression.pop_comments() 3700 3701 sql = self.prepend_ctes(expression, sql) 3702 3703 if self.STAR_EXCLUDE_REQUIRES_DERIVED_TABLE and exclude: 3704 expression.set("exclude", None) 3705 subquery = expression.subquery(copy=False) 3706 star = exp.Star(except_=exclude) 3707 sql = self.sql(exp.select(star).from_(subquery, copy=False)) 3708 3709 if not self.SUPPORTS_SELECT_INTO and into: 3710 if into.args.get("temporary"): 3711 table_kind = " TEMPORARY" 3712 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 3713 table_kind = " UNLOGGED" 3714 else: 3715 table_kind = "" 3716 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 3717 3718 return sql
3730 def star_sql(self, expression: exp.Star) -> str: 3731 except_ = self.expressions(expression, key="except_", flat=True) 3732 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 3733 replace = self.expressions(expression, key="replace", flat=True) 3734 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 3735 rename = self.expressions(expression, key="rename", flat=True) 3736 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 3737 ilike = self.sql(expression, "ilike") 3738 ilike = f"{self.seg('ILIKE')} {ilike}" if ilike else "" 3739 return f"*{ilike}{except_}{replace}{rename}"
3755 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 3756 alias = self.sql(expression, "alias") 3757 alias = f"{sep}{alias}" if alias else "" 3758 sample = self.sql(expression, "sample") 3759 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 3760 alias = f"{sample}{alias}" 3761 3762 # Set to None so it's not generated again by self.query_modifiers() 3763 expression.set("sample", None) 3764 3765 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 3766 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 3767 return self.prepend_ctes(expression, sql)
3773 def unnest_sql(self, expression: exp.Unnest) -> str: 3774 args = self.expressions(expression, flat=True) 3775 3776 alias = expression.args.get("alias") 3777 offset = expression.args.get("offset") 3778 3779 if self.UNNEST_WITH_ORDINALITY: 3780 if alias and isinstance(offset, exp.Expr): 3781 alias.append("columns", offset) 3782 expression.set("offset", None) 3783 3784 if alias and self.dialect.UNNEST_COLUMN_ONLY: 3785 columns = alias.columns 3786 alias = self.sql(columns[0]) if columns else "" 3787 else: 3788 alias = self.sql(alias) 3789 3790 alias = f" AS {alias}" if alias else alias 3791 if self.UNNEST_WITH_ORDINALITY: 3792 suffix = f" WITH ORDINALITY{alias}" if offset else alias 3793 else: 3794 if isinstance(offset, exp.Expr): 3795 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 3796 elif offset: 3797 suffix = f"{alias} WITH OFFSET" 3798 else: 3799 suffix = alias 3800 3801 return f"UNNEST({args}){suffix}"
3810 def window_sql(self, expression: exp.Window) -> str: 3811 if ( 3812 isinstance(expression.this, exp.Variance) 3813 and expression.this.args.get("single_value_returns_zero") 3814 and expression.text("over") != "KEEP" 3815 and not self.VARIANCE_RETURNS_ZERO_ON_SINGLE_VALUE 3816 ): 3817 return self.variance_sql(expression.this, window=expression) 3818 3819 this = self.sql(expression, "this") 3820 partition = self.partition_by_sql(expression) 3821 order = expression.args.get("order") 3822 if not order and self.WINDOW_FUNCS_REQUIRING_ORDER and not expression.args.get("alias"): 3823 func = expression.this 3824 if isinstance(func, (exp.IgnoreNulls, exp.RespectNulls)): 3825 func = func.this 3826 if isinstance(func, self.WINDOW_FUNCS_REQUIRING_ORDER): 3827 # Without an ordering all rows of a partition are peers, which is 3828 # also the case when ordering by the partition keys themselves 3829 partition_by = expression.args.get("partition_by") 3830 order = exp.Order( 3831 expressions=[e.copy() for e in partition_by] if partition_by else [exp.null()] 3832 ) 3833 order = self.order_sql(order, flat=True) if order else "" 3834 spec = self.sql(expression, "spec") 3835 alias = self.sql(expression, "alias") 3836 over = self.sql(expression, "over") or "OVER" 3837 3838 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 3839 3840 first = expression.args.get("first") 3841 if first is None: 3842 first = "" 3843 else: 3844 first = "FIRST" if first else "LAST" 3845 3846 if not partition and not order and not spec and alias: 3847 # WINDOW w2 AS w1 is unparseable in DuckDB/Postgres; parens are required. 3848 if expression.arg_key == "windows": 3849 return f"{this} ({alias})" 3850 return f"{this} {alias}" 3851 3852 args = self.format_args( 3853 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 3854 ) 3855 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.query.Window | sqlglot.expressions.query.MatchRecognize) -> str:
def
partitionbyexcluding_sql(self, expression: sqlglot.expressions.query.PartitionByExcluding) -> str:
3864 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 3865 kind = self.sql(expression, "kind") 3866 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 3867 end = ( 3868 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 3869 or "CURRENT ROW" 3870 ) 3871 3872 window_spec = f"{kind} BETWEEN {start} AND {end}" 3873 3874 exclude = self.sql(expression, "exclude") 3875 if exclude: 3876 if self.SUPPORTS_WINDOW_EXCLUDE: 3877 window_spec += f" EXCLUDE {exclude}" 3878 else: 3879 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 3880 3881 return window_spec
3888 def between_sql(self, expression: exp.Between) -> str: 3889 this = self.sql(expression, "this") 3890 low = self.sql(expression, "low") 3891 high = self.sql(expression, "high") 3892 symmetric = expression.args.get("symmetric") 3893 3894 if symmetric and not self.SUPPORTS_BETWEEN_FLAGS: 3895 return f"({this} BETWEEN {low} AND {high} OR {this} BETWEEN {high} AND {low})" 3896 3897 flag = ( 3898 " SYMMETRIC" 3899 if symmetric 3900 else " ASYMMETRIC" 3901 if symmetric is False and self.SUPPORTS_BETWEEN_FLAGS 3902 else "" # silently drop ASYMMETRIC – semantics identical 3903 ) 3904 return f"{this} BETWEEN{flag} {low} AND {high}"
def
bracket_offset_expressions( self, expression: sqlglot.expressions.core.Bracket, index_offset: int | None = None) -> list[sqlglot.expressions.core.Expr]:
3906 def bracket_offset_expressions( 3907 self, expression: exp.Bracket, index_offset: int | None = None 3908 ) -> list[exp.Expr]: 3909 if expression.args.get("json_access"): 3910 return expression.expressions 3911 3912 return apply_index_offset( 3913 expression.this, 3914 expression.expressions, 3915 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 3916 dialect=self.dialect, 3917 )
3930 def any_sql(self, expression: exp.Any) -> str: 3931 this = self.sql(expression, "this") 3932 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 3933 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 3934 this = self.wrap(this) 3935 return f"ANY{this}" 3936 return f"ANY {this}"
3938 def exists_sql(self, expression: exp.Exists) -> str: 3939 predicate = expression.expression 3940 if not predicate: 3941 return f"EXISTS{self.wrap(expression)}" 3942 3943 # Spark's EXISTS(array, lambda) 3944 if self.CAN_IMPLEMENT_ARRAY_ANY: 3945 filtered = exp.ArrayFilter(this=expression.this, expression=predicate) 3946 return self.sql(exp.paren(exp.ArraySize(this=filtered).neq(0))) 3947 3948 self.unsupported("EXISTS with a lambda predicate is unsupported") 3949 return self.function_fallback_sql(expression)
3951 def case_sql(self, expression: exp.Case) -> str: 3952 this = self.sql(expression, "this") 3953 statements = [f"CASE {this}" if this else "CASE"] 3954 3955 for e in expression.args["ifs"]: 3956 statements.append(f"WHEN {self.sql(e, 'this')}") 3957 statements.append(f"THEN {self.sql(e, 'true')}") 3958 3959 default = self.sql(expression, "default") 3960 3961 if default: 3962 statements.append(f"ELSE {default}") 3963 3964 statements.append("END") 3965 3966 if self.pretty and self.too_wide(statements): 3967 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 3968 3969 return " ".join(statements)
3981 def dayofweek_sql(self, expression: exp.DayOfWeek) -> str: 3982 if bool(expression.args.get("zero_based")) == self.DAYOFWEEK_ZERO_BASED: 3983 return self._native_dayofweek_sql(expression) 3984 3985 adjusted = expression + 1 if self.DAYOFWEEK_ZERO_BASED else expression - 1 3986 adjusted.this.set("zero_based", self.DAYOFWEEK_ZERO_BASED) 3987 # The outer DayOfWeek already emits the function's comments. 3988 adjusted.this.pop_comments() 3989 return self.sql(exp.paren(adjusted, copy=False))
3994 def extract_date_part(self, part: exp.Expr) -> exp.Expr: 3995 mapping = self.dialect.EXTRACT_DATE_PART_MAPPING 3996 if self.NORMALIZE_EXTRACT_DATE_PARTS and part.name.upper() not in mapping: 3997 mapping = self.dialect.DATE_PART_MAPPING 3998 if mapping: 3999 import sqlglot.dialects.dialect 4000 4001 return sqlglot.dialects.dialect.map_date_part(part, mapping=mapping) 4002 return part
4004 def extract_sql(self, expression: exp.Extract) -> str: 4005 this = self.extract_date_part(expression.this) 4006 if self.EXTRACT_ALLOWS_QUOTES: 4007 this_sql = self.sql(this) 4008 elif isinstance(this, exp.WeekStart): 4009 this_sql = self.weekstart_name(this) 4010 else: 4011 this_sql = this.name 4012 expression_sql = self.sql(expression, "expression") 4013 4014 return f"EXTRACT({this_sql} FROM {expression_sql})"
4016 def trim_sql(self, expression: exp.Trim) -> str: 4017 trim_type = self.sql(expression, "position") 4018 4019 if trim_type == "LEADING": 4020 func_name = "LTRIM" 4021 elif trim_type == "TRAILING": 4022 func_name = "RTRIM" 4023 else: 4024 func_name = "TRIM" 4025 4026 return self.func(func_name, expression.this, expression.expression)
def
convert_concat_args( self, expression: sqlglot.expressions.core.Func) -> list[sqlglot.expressions.core.Expr]:
4028 def convert_concat_args(self, expression: exp.Func) -> list[exp.Expr]: 4029 args = expression.expressions 4030 if isinstance(expression, exp.ConcatWs): 4031 args = args[1:] # Skip the delimiter 4032 4033 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 4034 args = [exp.cast(e, exp.DType.TEXT) for e in args] 4035 4036 concat_coalesce = ( 4037 self.dialect.CONCAT_WS_COALESCE 4038 if isinstance(expression, exp.ConcatWs) 4039 else self.dialect.CONCAT_COALESCE 4040 ) 4041 4042 if not concat_coalesce and expression.args.get("coalesce"): 4043 4044 def _wrap_with_coalesce(e: exp.Expr) -> exp.Expr: 4045 if not e.type: 4046 import sqlglot.optimizer.annotate_types 4047 4048 e = sqlglot.optimizer.annotate_types.annotate_types(e, dialect=self.dialect) 4049 4050 if e.is_string or e.is_type(exp.DType.ARRAY): 4051 return e 4052 4053 return exp.func("coalesce", e, exp.Literal.string("")) 4054 4055 args = [_wrap_with_coalesce(e) for e in args] 4056 4057 return args
4059 def concat_sql(self, expression: exp.Concat) -> str: 4060 if self.dialect.CONCAT_COALESCE and not expression.args.get("coalesce"): 4061 # Dialect's CONCAT function coalesces NULLs to empty strings, but the expression does not. 4062 # Transpile to double pipe operators, which typically returns NULL if any args are NULL 4063 # instead of coalescing them to empty string. 4064 import sqlglot.dialects.dialect 4065 4066 return sqlglot.dialects.dialect.concat_to_dpipe_sql(self, expression) 4067 4068 expressions = self.convert_concat_args(expression) 4069 4070 # Some dialects don't allow a single-argument CONCAT call 4071 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 4072 return self.sql(expressions[0]) 4073 4074 return self.func("CONCAT", *expressions)
4076 def concatws_sql(self, expression: exp.ConcatWs) -> str: 4077 if self.dialect.CONCAT_WS_COALESCE and not expression.args.get("coalesce"): 4078 # Dialect's CONCAT_WS function skips NULL args, but the expression does not. 4079 # Wrap the entire call in a CASE expression that returns NULL if any input IS NULL. 4080 all_args = expression.expressions 4081 expression.set("coalesce", True) 4082 return self.sql( 4083 exp.case() 4084 .when(exp.or_(*(arg.is_(exp.null()) for arg in all_args)), exp.null()) 4085 .else_(expression) 4086 ) 4087 4088 return self.func( 4089 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 4090 )
4096 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 4097 this = self.sql(expression, "this") 4098 this = f" {this}" if this else "" 4099 expressions = self.expressions(expression, flat=True) 4100 expressions = f" ({expressions})" if expressions else "" 4101 reference = self.sql(expression, "reference") 4102 reference = f" {reference}" if reference else "" 4103 delete = self.sql(expression, "delete") 4104 delete = f" ON DELETE {delete}" if delete else "" 4105 update = self.sql(expression, "update") 4106 update = f" ON UPDATE {update}" if update else "" 4107 options = self.expressions(expression, key="options", flat=True, sep=" ") 4108 options = f" {options}" if options else "" 4109 return f"FOREIGN KEY{this}{expressions}{reference}{delete}{update}{options}"
4111 def primarykey_sql(self, expression: exp.PrimaryKey) -> str: 4112 this = self.sql(expression, "this") 4113 this = f" {this}" if this else "" 4114 expressions = self.expressions(expression, flat=True) 4115 include = self.sql(expression, "include") 4116 options = self.expressions(expression, key="options", flat=True, sep=" ") 4117 options = f" {options}" if options else "" 4118 return f"PRIMARY KEY{this} ({expressions}){include}{options}"
4127 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 4128 if self.MATCH_AGAINST_TABLE_PREFIX: 4129 expressions = [] 4130 for expr in expression.expressions: 4131 if isinstance(expr, exp.Table): 4132 expressions.append(f"TABLE {self.sql(expr)}") 4133 else: 4134 expressions.append(expr) 4135 else: 4136 expressions = expression.expressions 4137 4138 modifier = expression.args.get("modifier") 4139 modifier = f" {modifier}" if modifier else "" 4140 return ( 4141 f"{self.func('MATCH', *expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 4142 )
4156 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 4157 if isinstance(expression, exp.JSONPathPart): 4158 transform = self.TRANSFORMS.get(expression.__class__) 4159 if not callable(transform): 4160 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 4161 return "" 4162 4163 return transform(self, expression) 4164 4165 if isinstance(expression, int): 4166 return str(expression) 4167 4168 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 4169 escaped = expression.replace("'", "\\'") 4170 escaped = f"'{escaped}'" 4171 else: 4172 escaped = expression.replace('"', '\\"') 4173 escaped = f'"{escaped}"' 4174 4175 return escaped
4177 def format_sql(self, expression: exp.Format) -> str: 4178 if ( 4179 expression.args.get("is_fmt") 4180 and expression.this.is_string 4181 and not expression.expressions 4182 and not any(c in expression.name for c in "{}") 4183 ): 4184 return self.sql(expression.this) 4185 4186 self._warn_unsupported_arg(expression, "is_fmt") 4187 return self.function_fallback_sql(expression)
4192 def formatphrase_sql(self, expression: exp.FormatPhrase) -> str: 4193 # Output the Teradata column FORMAT override. 4194 # https://docs.teradata.com/r/Enterprise_IntelliFlex_VMware/SQL-Data-Types-and-Literals/Data-Type-Formats-and-Format-Phrases/FORMAT 4195 this = self.sql(expression, "this") 4196 fmt = self.sql(expression, "format") 4197 return f"{this} (FORMAT {fmt})"
4237 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 4238 null_handling = expression.args.get("null_handling") 4239 null_handling = f" {null_handling}" if null_handling else "" 4240 return_type = self.sql(expression, "return_type") 4241 return_type = f" RETURNING {return_type}" if return_type else "" 4242 strict = " STRICT" if expression.args.get("strict") else "" 4243 return self.func( 4244 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 4245 )
4247 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 4248 this = self.sql(expression, "this") 4249 order = self.sql(expression, "order") 4250 null_handling = expression.args.get("null_handling") 4251 null_handling = f" {null_handling}" if null_handling else "" 4252 return_type = self.sql(expression, "return_type") 4253 return_type = f" RETURNING {return_type}" if return_type else "" 4254 strict = " STRICT" if expression.args.get("strict") else "" 4255 return self.func( 4256 "JSON_ARRAYAGG", 4257 this, 4258 suffix=f"{order}{null_handling}{return_type}{strict})", 4259 )
4261 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 4262 path = self.sql(expression, "path") 4263 path = f" PATH {path}" if path else "" 4264 nested_schema = self.sql(expression, "nested_schema") 4265 4266 if nested_schema: 4267 return f"NESTED{path} {nested_schema}" 4268 4269 this = self.sql(expression, "this") 4270 kind = self.sql(expression, "kind") 4271 kind = f" {kind}" if kind else "" 4272 format_json = " FORMAT JSON" if expression.args.get("format_json") else "" 4273 4274 ordinality = " FOR ORDINALITY" if expression.args.get("ordinality") else "" 4275 return f"{this}{kind}{format_json}{path}{ordinality}"
4280 def jsontable_sql(self, expression: exp.JSONTable) -> str: 4281 this = self.sql(expression, "this") 4282 path = self.sql(expression, "path") 4283 path = f", {path}" if path else "" 4284 error_handling = expression.args.get("error_handling") 4285 error_handling = f" {error_handling}" if error_handling else "" 4286 empty_handling = expression.args.get("empty_handling") 4287 empty_handling = f" {empty_handling}" if empty_handling else "" 4288 schema = self.sql(expression, "schema") 4289 return self.func( 4290 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 4291 )
4293 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 4294 this = self.sql(expression, "this") 4295 kind = self.sql(expression, "kind") 4296 path = self.sql(expression, "path") 4297 path = f" {path}" if path else "" 4298 as_json = " AS JSON" if expression.args.get("as_json") else "" 4299 return f"{this} {kind}{path}{as_json}"
4301 def openjson_sql(self, expression: exp.OpenJSON) -> str: 4302 this = self.sql(expression, "this") 4303 path = self.sql(expression, "path") 4304 path = f", {path}" if path else "" 4305 expressions = self.expressions(expression) 4306 with_ = ( 4307 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 4308 if expressions 4309 else "" 4310 ) 4311 return f"OPENJSON({this}{path}){with_}"
4313 def in_sql(self, expression: exp.In) -> str: 4314 query = expression.args.get("query") 4315 unnest = expression.args.get("unnest") 4316 field = expression.args.get("field") 4317 is_global = " GLOBAL" if expression.args.get("is_global") else "" 4318 4319 if query: 4320 in_sql = self.sql(query) 4321 elif unnest: 4322 in_sql = self.in_unnest_op(unnest) 4323 elif field: 4324 in_sql = self.sql(field) 4325 else: 4326 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 4327 4328 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
4333 def interval_sql(self, expression: exp.Interval) -> str: 4334 include_keyword = not self.AUTO_REFRESH_BARE_INTERVALS or not isinstance( 4335 expression.find_ancestor(exp.AutoRefreshProperty, exp.Select), 4336 exp.AutoRefreshProperty, 4337 ) 4338 interval_keyword = "INTERVAL" if include_keyword else "" 4339 unit_expression = expression.args.get("unit") 4340 unit = self.sql(unit_expression) if unit_expression else "" 4341 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 4342 unit = self.TIME_PART_SINGULARS.get(unit, unit) 4343 unit = f" {unit}" if unit else "" 4344 4345 if self.SINGLE_STRING_INTERVAL: 4346 this = expression.this.name if expression.this else "" 4347 if this: 4348 interval_keyword = f"{interval_keyword} " if interval_keyword else "" 4349 if unit_expression and isinstance(unit_expression, exp.IntervalSpan): 4350 return f"{interval_keyword}{self.sql(exp.Literal.string(this))}{unit}" 4351 return f"{interval_keyword}{self.sql(exp.Literal.string(f'{this}{unit}'))}" 4352 return f"{interval_keyword}{unit}" 4353 4354 this = self.sql(expression, "this") 4355 if this: 4356 if not include_keyword and expression.this.is_string: 4357 this = expression.this.name 4358 if not isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES): 4359 this = f"({this})" 4360 if include_keyword: 4361 this = f" {this}" 4362 4363 return f"{interval_keyword}{this}{unit}"
4368 def reference_sql(self, expression: exp.Reference) -> str: 4369 this = self.sql(expression, "this") 4370 expressions = self.expressions(expression, flat=True) 4371 expressions = f"({expressions})" if expressions else "" 4372 options = self.expressions(expression, key="options", flat=True, sep=" ") 4373 options = f" {options}" if options else "" 4374 return f"REFERENCES {this}{expressions}{options}"
4376 def anonymous_sql(self, expression: exp.Anonymous) -> str: 4377 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 4378 parent = expression.parent 4379 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 4380 4381 return self.func( 4382 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 4383 )
4406 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 4407 alias = expression.args["alias"] 4408 4409 parent = expression.parent 4410 pivot = parent and parent.parent 4411 4412 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 4413 identifier_alias = isinstance(alias, exp.Identifier) 4414 literal_alias = isinstance(alias, exp.Literal) 4415 4416 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4417 alias.replace(exp.Literal.string(alias.output_name)) 4418 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 4419 alias.replace(exp.to_identifier(alias.output_name)) 4420 4421 return self.alias_sql(expression)
def
fromiso8601timestamp_sql( self, expression: sqlglot.expressions.temporal.FromISO8601Timestamp) -> str:
def
fromiso8601timestampnanos_sql( self, expression: sqlglot.expressions.temporal.FromISO8601TimestampNanos) -> str:
def
and_sql( self, expression: sqlglot.expressions.core.And, stack: list[str | sqlglot.expressions.core.Expr] | None = None) -> str:
def
or_sql( self, expression: sqlglot.expressions.core.Or, stack: list[str | sqlglot.expressions.core.Expr] | None = None) -> str:
def
xor_sql( self, expression: sqlglot.expressions.core.Xor, stack: list[str | sqlglot.expressions.core.Expr] | None = None) -> str:
def
connector_sql( self, expression: sqlglot.expressions.core.Connector, op: str, stack: list[str | sqlglot.expressions.core.Expr] | None = None) -> str:
4462 def connector_sql( 4463 self, 4464 expression: exp.Connector, 4465 op: str, 4466 stack: list[str | exp.Expr] | None = None, 4467 ) -> str: 4468 if stack is not None: 4469 stack.append(expression.right) 4470 if expression.comments and self.comments: 4471 op = self.maybe_comment(op, comments=expression.comments) 4472 4473 stack.extend((op, expression.left)) 4474 return op 4475 4476 stack = [expression] 4477 sqls: list[str] = [] 4478 ops = set() 4479 4480 while stack: 4481 node = stack.pop() 4482 if isinstance(node, exp.Connector): 4483 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 4484 else: 4485 sql = self.sql(node) 4486 if sqls and sqls[-1] in ops: 4487 sqls[-1] += f" {sql}" 4488 else: 4489 sqls.append(sql) 4490 4491 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 4492 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.functions.Cast, safe_prefix: str | None = None) -> str:
4512 def cast_sql(self, expression: exp.Cast, safe_prefix: str | None = None) -> str: 4513 format_sql = self.sql(expression, "format") 4514 format_sql = f" FORMAT {format_sql}" if format_sql else "" 4515 to_sql = self.sql(expression, "to") 4516 to_sql = f" {to_sql}" if to_sql else "" 4517 action = self.sql(expression, "action") 4518 action = f" {action}" if action else "" 4519 default = self.sql(expression, "default") 4520 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 4521 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
4552 def optimize_sql(self, expression: exp.Optimize) -> str: 4553 if not self.SUPPORTS_OPTIMIZE: 4554 self.unsupported("OPTIMIZE is only supported in Databricks") 4555 full = " FULL" if expression.args.get("full") else "" 4556 where = self.sql(expression, "where") 4557 columns = self.expressions(expression, key="zorder", flat=True) 4558 zorder = self.seg(f"ZORDER BY ({columns})") if columns else "" 4559 return f"OPTIMIZE {self.sql(expression, 'this')}{full}{where}{zorder}"
4561 def comment_sql(self, expression: exp.Comment) -> str: 4562 this = self.sql(expression, "this") 4563 kind = expression.args["kind"] 4564 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 4565 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 4566 expression_sql = self.sql(expression, "expression") 4567 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
4569 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 4570 this = self.sql(expression, "this") 4571 delete = " DELETE" if expression.args.get("delete") else "" 4572 recompress = self.sql(expression, "recompress") 4573 recompress = f" RECOMPRESS {recompress}" if recompress else "" 4574 to_disk = self.sql(expression, "to_disk") 4575 to_disk = f" TO DISK {to_disk}" if to_disk else "" 4576 to_volume = self.sql(expression, "to_volume") 4577 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 4578 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
4580 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 4581 where = self.sql(expression, "where") 4582 group = self.sql(expression, "group") 4583 aggregates = self.expressions(expression, key="aggregates") 4584 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 4585 4586 if not (where or group or aggregates) and len(expression.expressions) == 1: 4587 return f"TTL {self.expressions(expression, flat=True)}" 4588 4589 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
4608 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 4609 this = self.sql(expression, "this") 4610 4611 exists = "" 4612 if expression.args.get("exists"): 4613 if self.SUPPORTS_ALTER_COLUMN_IF_EXISTS: 4614 exists = " IF EXISTS" 4615 else: 4616 self.unsupported("ALTER COLUMN IF EXISTS is not supported by this dialect") 4617 4618 dtype = self.sql(expression, "dtype") 4619 if dtype: 4620 collate = self.sql(expression, "collate") 4621 collate = f" COLLATE {collate}" if collate else "" 4622 using = self.sql(expression, "using") 4623 using = f" USING {using}" if using else "" 4624 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 4625 null_constraint = self._alter_column_null_constraint_sql(expression) 4626 4627 return ( 4628 f"ALTER COLUMN{exists} {this} {alter_set_type}{dtype}" 4629 f"{collate}{using}{null_constraint}" 4630 ) 4631 4632 default = self.sql(expression, "default") 4633 if default: 4634 return f"ALTER COLUMN{exists} {this} SET DEFAULT {default}" 4635 4636 comment = self.sql(expression, "comment") 4637 if comment: 4638 return f"ALTER COLUMN{exists} {this} COMMENT {comment}" 4639 4640 visible = expression.args.get("visible") 4641 if visible: 4642 return f"ALTER COLUMN{exists} {this} SET {visible}" 4643 4644 allow_null = expression.args.get("allow_null") 4645 drop = expression.args.get("drop") 4646 4647 if not drop and not allow_null: 4648 self.unsupported("Unsupported ALTER COLUMN syntax") 4649 4650 if allow_null is not None: 4651 keyword = "DROP" if drop else "SET" 4652 return f"ALTER COLUMN{exists} {this} {keyword} NOT NULL" 4653 4654 return f"ALTER COLUMN{exists} {this} DROP DEFAULT"
4667 def modifycolumn_sql(self, expression: exp.ModifyColumn) -> str: 4668 this = self.sql(expression, "this") 4669 rename_from = self.sql(expression, "rename_from") 4670 if rename_from: 4671 if not self.SUPPORTS_CHANGE_COLUMN: 4672 self.unsupported("CHANGE COLUMN is not supported in this dialect") 4673 return f"CHANGE COLUMN {rename_from} {this}" 4674 if not self.SUPPORTS_MODIFY_COLUMN: 4675 self.unsupported("MODIFY COLUMN is not supported in this dialect") 4676 return f"MODIFY COLUMN {this}"
4692 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 4693 compound = " COMPOUND" if expression.args.get("compound") else "" 4694 this = self.sql(expression, "this") 4695 expressions = self.expressions(expression, flat=True) 4696 expressions = f"({expressions})" if expressions else "" 4697 return f"ALTER{compound} SORTKEY {this or expressions}"
def
alterrename_sql( self, expression: sqlglot.expressions.ddl.AlterRename, include_to: bool = True) -> str:
4699 def alterrename_sql(self, expression: exp.AlterRename, include_to: bool = True) -> str: 4700 if not self.RENAME_TABLE_WITH_DB: 4701 # Remove db from tables 4702 expression = expression.transform( 4703 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 4704 ).assert_is(exp.AlterRename) 4705 this = self.sql(expression, "this") 4706 to_kw = " TO" if include_to else "" 4707 return f"RENAME{to_kw} {this}"
4722 def alter_sql(self, expression: exp.Alter) -> str: 4723 actions = expression.actions 4724 4725 if ( 4726 not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN 4727 and actions 4728 and isinstance(actions[0], exp.ColumnDef) 4729 ): 4730 actions_sql = self.expressions(expression, key="actions", flat=True) 4731 actions_sql = f"ADD {actions_sql}" 4732 else: 4733 actions_list = [] 4734 for action in actions: 4735 if isinstance(action, (exp.ColumnDef, exp.Schema)): 4736 action_sql = self.add_column_sql(action) 4737 else: 4738 action_sql = self.sql(action) 4739 if isinstance(action, exp.Query): 4740 action_sql = f"AS {action_sql}" 4741 4742 actions_list.append(action_sql) 4743 4744 actions_sql = self.format_args(*actions_list).lstrip("\n") 4745 4746 iceberg = ( 4747 "ICEBERG " 4748 if expression.args.get("iceberg") and self.SUPPORTS_DROP_ALTER_ICEBERG_PROPERTY 4749 else "" 4750 ) 4751 exists = " IF EXISTS" if expression.args.get("exists") else "" 4752 on_cluster = self.sql(expression, "cluster") 4753 on_cluster = f" {on_cluster}" if on_cluster else "" 4754 only = " ONLY" if expression.args.get("only") else "" 4755 options = expression.args.get("options") or [] 4756 options_sql = self.expressions( 4757 sqls=[o for o in options if not isinstance(o, self.ALTER_PARTITION_OPTIONS)] 4758 ) 4759 options_sql = f", {options_sql}" if options_sql and actions_sql else options_sql 4760 partitions_sql = self.expressions( 4761 sqls=[o for o in options if isinstance(o, self.ALTER_PARTITION_OPTIONS)], 4762 sep=" ", 4763 flat=True, 4764 ) 4765 if partitions_sql and (actions_sql or options_sql): 4766 partitions_sql = f" {partitions_sql}" 4767 kind = self.sql(expression, "kind") 4768 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 4769 check = " WITH CHECK" if expression.args.get("check") else "" 4770 cascade = ( 4771 " CASCADE" 4772 if expression.args.get("cascade") and self.dialect.ALTER_TABLE_SUPPORTS_CASCADE 4773 else "" 4774 ) 4775 this = self.sql(expression, "this") 4776 this = f" {this}" if this else "" 4777 4778 return f"ALTER {iceberg}{kind}{exists}{only}{this}{on_cluster}{check}{self.sep()}{actions_sql}{not_valid}{options_sql}{partitions_sql}{cascade}"
4785 def add_column_sql(self, expression: exp.Expr) -> str: 4786 column_text = "" 4787 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 4788 if isinstance(expression, exp.ColumnDef): 4789 column_text = " COLUMN" 4790 elif isinstance(expression, exp.Schema): 4791 column_text = " COLUMNS" 4792 4793 if isinstance(expression, exp.Schema) and not self.ALTER_TABLE_ADD_COLUMNS_WRAPPED: 4794 sql = self.expressions(expression, flat=True) 4795 else: 4796 sql = self.sql(expression) 4797 4798 return f"ADD{column_text} {sql}"
4814 def addpartition_sql(self, expression: exp.AddPartition) -> str: 4815 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 4816 location = self.sql(expression, "location") 4817 location = f" {location}" if location else "" 4818 return f"ADD {exists}{self.sql(expression.this)}{location}"
4820 def distinct_sql(self, expression: exp.Distinct) -> str: 4821 this = self.expressions(expression, flat=True) 4822 4823 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 4824 case = exp.case() 4825 for arg in expression.expressions: 4826 case = case.when(arg.is_(exp.null()), exp.null()) 4827 this = self.sql(case.else_(f"({this})")) 4828 4829 this = f" {this}" if this else "" 4830 4831 on = self.sql(expression, "on") 4832 on = f" ON {on}" if on else "" 4833 return f"DISTINCT{this}{on}"
4847 def intdiv_sql(self, expression: exp.IntDiv) -> str: 4848 if not self.INT_DIV_OPERATOR: 4849 return self._truncated_div_sql(expression.this, expression.expression) 4850 4851 # Integer division binds like %, so those operators chain on its left without parentheses 4852 node: exp.Expr = expression 4853 while isinstance(node, exp.IntDiv): 4854 this = node.this 4855 if not isinstance(this, self.MOD_PAREN_PARENT_TYPES): 4856 node.set("this", exp._wrap(this, exp.Binary)) 4857 node.set("expression", exp._wrap(node.expression, exp.Binary)) 4858 node = this 4859 4860 sql = self.binary(expression, self.INT_DIV_OPERATOR) 4861 4862 parent = expression.parent 4863 if isinstance(parent, (exp.Neg, exp.BitwiseNot)) or ( 4864 isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression 4865 ): 4866 return f"({sql})" 4867 4868 return sql
def
nullif_zero_divisor( self, expression: sqlglot.expressions.core.Div | sqlglot.expressions.core.Mod) -> None:
4887 def div_sql(self, expression: exp.Div) -> str: 4888 l, r = expression.left, expression.right 4889 self.nullif_zero_divisor(expression) 4890 4891 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 4892 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 4893 l.replace(exp.cast(l.copy(), to=exp.DType.DOUBLE)) 4894 4895 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 4896 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 4897 # Native integer division depends on the target's operand types, which may differ 4898 # from the source's (e.g. FLOOR(int) is DOUBLE in DuckDB), unless the operands are 4899 # integer literals or casts 4900 if all(e.is_int or isinstance(e, exp.Cast) for e in (l, r)) and ( 4901 expression.args.get("safe") or not self.SAFE_INT_DIVISION 4902 ): 4903 return self.sql(exp.IntDiv(this=l, expression=expression.right)) 4904 return self._truncated_div_sql(l, expression.right) 4905 4906 return self.binary(expression, "/")
4925 def nestedjsonselect_sql(self, expression: exp.NestedJSONSelect) -> str: 4926 if not self.SUPPORTS_NESTED_JSON_SELECT and self.dialect != "": 4927 self.unsupported("Selecting nested JSON objects with .^ is not supported") 4928 return f"{self.sql(expression, 'this')}.^{self.sql(expression, 'expression')}"
4936 def escape_sql(self, expression: exp.Escape) -> str: 4937 this = expression.this 4938 if ( 4939 isinstance(this, (exp.Like, exp.ILike)) 4940 and isinstance(this.expression, (exp.All, exp.Any)) 4941 and not self.SUPPORTS_LIKE_QUANTIFIERS 4942 ): 4943 return self._like_sql(this, escape=expression) 4944 return self.binary(expression, "ESCAPE")
4955 def is_sql(self, expression: exp.Is) -> str: 4956 negate = expression.args.get("negate") 4957 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 4958 positive = bool(expression.expression.this) != bool(negate) 4959 return self.sql(expression.this if positive else exp.not_(expression.this)) 4960 return self.binary(expression, "IS NOT" if negate else "IS")
5032 def mod_sql(self, expression: exp.Mod) -> str: 5033 self.nullif_zero_divisor(expression) 5034 this = self.sql(expression, "this") 5035 expr = self.sql(expression, "expression") 5036 sql = f"{this} {self.maybe_comment(self.MOD_OPERATOR, comments=expression.comments)} {expr}" 5037 5038 parent = expression.parent 5039 if isinstance(parent, self.MOD_PAREN_PARENT_TYPES) and parent.expression is expression: 5040 return f"({sql})" 5041 5042 return sql
5072 def log_sql(self, expression: exp.Log) -> str: 5073 this = expression.this 5074 expr = expression.expression 5075 5076 if self.dialect.LOG_BASE_FIRST is False: 5077 this, expr = expr, this 5078 elif self.dialect.LOG_BASE_FIRST is None and expr: 5079 if this.name in ("2", "10"): 5080 return self.func(f"LOG{this.name}", expr) 5081 5082 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 5083 5084 return self.func("LOG", this, expr)
5093 def binary(self, expression: exp.Binary, op: str) -> str: 5094 sqls: list[str] = [] 5095 stack: list[None | str | exp.Expr] = [expression] 5096 binary_type = type(expression) 5097 is_is = binary_type is exp.Is and op in ("IS", "IS NOT") 5098 negate = expression.args.get("negate") 5099 5100 while stack: 5101 node = stack.pop() 5102 5103 if type(node) is binary_type and ( 5104 node is expression 5105 or (is_is and not isinstance(node.expression, exp.Boolean)) 5106 or node.args.get("negate") == negate 5107 ): 5108 op_func = node.args.get("operator") 5109 if op_func: 5110 op = self.sql(op_func) 5111 if op not in self.BARE_OPERATORS: 5112 op = f"OPERATOR({op})" 5113 elif is_is: 5114 op = "IS NOT" if node.args.get("negate") else "IS" 5115 5116 stack.append(node.args.get("expression")) 5117 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 5118 stack.append(node.args.get("this")) 5119 else: 5120 sqls.append(self.sql(node)) 5121 5122 return "".join(sqls)
def
ceil_floor( self, expression: sqlglot.expressions.math.Ceil | sqlglot.expressions.math.Floor) -> str:
5131 def function_fallback_sql(self, expression: exp.Func) -> str: 5132 args = [] 5133 5134 for key in expression.arg_types: 5135 arg_value = expression.args.get(key) 5136 5137 if isinstance(arg_value, list): 5138 for value in arg_value: 5139 args.append(value) 5140 elif arg_value is not None: 5141 args.append(arg_value) 5142 5143 return self.func(self.function_name(expression), *args)
def
func( self, name: str, *args: Any, prefix: str = '(', suffix: str = ')', normalize: bool = True) -> str:
def
format_args(self, *args: Any, sep: str = ', ') -> str:
5160 def format_args(self, *args: t.Any, sep: str = ", ") -> str: 5161 arg_sqls = tuple( 5162 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 5163 ) 5164 if self.pretty and self.too_wide(arg_sqls): 5165 return self.indent( 5166 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 5167 ) 5168 return sep.join(arg_sqls)
def
format_time( self, expression: sqlglot.expressions.core.Expr, inverse_time_mapping: dict[str, str] | None = None, inverse_time_trie: dict | None = None) -> str | None:
5173 def format_time( 5174 self, 5175 expression: exp.Expr, 5176 inverse_time_mapping: dict[str, str] | None = None, 5177 inverse_time_trie: dict | None = None, 5178 ) -> str | None: 5179 return format_time( 5180 self.sql(expression, "format"), 5181 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 5182 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 5183 )
def
expressions( self, expression: sqlglot.expressions.core.Expr | None = None, key: str | None = None, sqls: Optional[Collection[str | sqlglot.expressions.core.Expr]] = None, flat: bool = False, indent: bool = True, skip_first: bool = False, skip_last: bool = False, sep: str = ', ', prefix: str = '', dynamic: bool = False, new_line: bool = False) -> str:
5185 def expressions( 5186 self, 5187 expression: exp.Expr | None = None, 5188 key: str | None = None, 5189 sqls: t.Collection[str | exp.Expr] | None = None, 5190 flat: bool = False, 5191 indent: bool = True, 5192 skip_first: bool = False, 5193 skip_last: bool = False, 5194 sep: str = ", ", 5195 prefix: str = "", 5196 dynamic: bool = False, 5197 new_line: bool = False, 5198 ) -> str: 5199 expressions = expression.args.get(key or "expressions") if expression else sqls 5200 5201 if not expressions: 5202 return "" 5203 5204 if flat: 5205 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 5206 5207 num_sqls = len(expressions) 5208 result_sqls = [] 5209 5210 for i, e in enumerate(expressions): 5211 sql = self.sql(e, comment=False) 5212 if not sql: 5213 continue 5214 5215 comments = self.maybe_comment("", e) if isinstance(e, exp.Expr) else "" 5216 5217 if self.pretty: 5218 if self.leading_comma: 5219 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 5220 else: 5221 result_sqls.append( 5222 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 5223 ) 5224 else: 5225 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 5226 5227 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 5228 if new_line: 5229 result_sqls.insert(0, "") 5230 result_sqls.append("") 5231 result_sql = "\n".join(s.rstrip() for s in result_sqls) 5232 else: 5233 result_sql = "".join(result_sqls) 5234 5235 return ( 5236 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 5237 if indent 5238 else result_sql 5239 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.core.Expr, flat: bool = False) -> str:
5241 def op_expressions(self, op: str, expression: exp.Expr, flat: bool = False) -> str: 5242 flat = flat or isinstance(expression.parent, exp.Properties) 5243 expressions_sql = self.expressions(expression, flat=flat) 5244 if flat: 5245 return f"{op} {expressions_sql}" 5246 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
5248 def naked_property(self, expression: exp.Property) -> str: 5249 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 5250 if not property_name: 5251 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 5252 return f"{property_name} {self.sql(expression, 'this')}"
5260 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 5261 this = self.sql(expression, "this") 5262 expressions = self.no_identify(self.expressions, expression) 5263 expressions = ( 5264 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 5265 ) 5266 return f"{this}{expressions}" if expressions.strip() != "" else this
5285 def when_sql(self, expression: exp.When) -> str: 5286 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 5287 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 5288 condition = self.sql(expression, "condition") 5289 condition = f" AND {condition}" if condition else "" 5290 5291 then_expression = expression.args.get("then") 5292 if isinstance(then_expression, exp.Insert): 5293 this = ( 5294 "ALL BY NAME" 5295 if self.MERGE_ALL_BY_NAME and isinstance(then_expression.this, exp.Star) 5296 else self.sql(then_expression, "this") 5297 ) 5298 this = f"INSERT {this}" if this else "INSERT" 5299 then = self.sql(then_expression, "expression") 5300 then = f"{this} VALUES {then}" if then else this 5301 elif isinstance(then_expression, exp.Update): 5302 if isinstance(then_expression.args.get("expressions"), exp.Star): 5303 then = ( 5304 "UPDATE ALL BY NAME" 5305 if self.MERGE_ALL_BY_NAME 5306 else f"UPDATE {self.sql(then_expression, 'expressions')}" 5307 ) 5308 elif ( 5309 self.MERGE_ALL_BY_NAME 5310 and len(then_expression.expressions) == 1 5311 and isinstance(then_expression.expressions[0], exp.Star) 5312 ): 5313 then = "UPDATE ALL BY NAME" 5314 else: 5315 expressions_sql = self.expressions(then_expression) 5316 then = f"UPDATE SET{self.sep()}{expressions_sql}" if expressions_sql else "UPDATE" 5317 else: 5318 then = self.sql(then_expression) 5319 5320 if isinstance(then_expression, (exp.Insert, exp.Update)): 5321 where = self.sql(then_expression, "where") 5322 if where and not self.SUPPORTS_MERGE_WHERE: 5323 kind = "INSERT" if isinstance(then_expression, exp.Insert) else "UPDATE" 5324 self.unsupported(f"WHERE clause in MERGE {kind} is not supported") 5325 where = "" 5326 then = f"{then}{where}" 5327 return f"WHEN {matched}{source}{condition} THEN {then}"
5332 def merge_sql(self, expression: exp.Merge) -> str: 5333 schema_evolution = "" 5334 if expression.args.get("schema_evolution"): 5335 min_version = self.MERGE_SCHEMA_EVOLUTION_MIN_VERSION 5336 if min_version and self.dialect.version >= min_version: 5337 schema_evolution = " WITH SCHEMA EVOLUTION" 5338 else: 5339 self.unsupported("MERGE WITH SCHEMA EVOLUTION is not supported") 5340 5341 table = expression.this 5342 table_alias = "" 5343 5344 hints = table.args.get("hints") 5345 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 5346 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 5347 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 5348 5349 this = self.sql(table) 5350 using = f"USING {self.sql(expression, 'using')}" 5351 whens = self.sql(expression, "whens") 5352 5353 on = self.sql(expression, "on") 5354 on = f"ON {on}" if on else "" 5355 5356 if not on: 5357 on = self.expressions(expression, key="using_cond") 5358 on = f"USING ({on})" if on else "" 5359 5360 returning = self.sql(expression, "returning") 5361 if returning: 5362 whens = f"{whens}{returning}" 5363 5364 sep = self.sep() 5365 5366 return self.prepend_ctes( 5367 expression, 5368 f"MERGE{schema_evolution} INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 5369 )
@unsupported_args('format')
def
tochar_sql(self, expression: sqlglot.expressions.string.ToChar) -> str:
@unsupported_args('default')
def
tonumber_sql(self, expression: sqlglot.expressions.string.ToNumber) -> str:
5375 @unsupported_args("default") 5376 def tonumber_sql(self, expression: exp.ToNumber) -> str: 5377 if not self.SUPPORTS_TO_NUMBER: 5378 self.unsupported("Unsupported TO_NUMBER function") 5379 return self._tonumber_cast_sql(expression) 5380 5381 fmt = expression.args.get("format") 5382 if not fmt: 5383 self.unsupported("Conversion format is required for TO_NUMBER") 5384 return self._tonumber_cast_sql(expression) 5385 5386 return self.func("TO_NUMBER", expression.this, fmt)
5393 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 5394 this = self.sql(expression, "this") 5395 kind = self.sql(expression, "kind") 5396 settings_sql = self.expressions(expression, key="settings", sep=" ") 5397 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 5398 return f"{this}({kind}{args})"
def
aggregatekeyproperty_sql( self, expression: sqlglot.expressions.properties.AggregateKeyProperty) -> str:
def
duplicatekeyproperty_sql( self, expression: sqlglot.expressions.properties.DuplicateKeyProperty) -> str:
def
uniquekeyproperty_sql( self, expression: sqlglot.expressions.properties.UniqueKeyProperty, prefix: str = 'UNIQUE KEY') -> str:
def
distributedbyproperty_sql( self, expression: sqlglot.expressions.properties.DistributedByProperty) -> str:
5422 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 5423 expressions = self.expressions(expression, flat=True) 5424 expressions = f" {self.wrap(expressions)}" if expressions else "" 5425 buckets = self.sql(expression, "buckets") 5426 kind = self.sql(expression, "kind") 5427 buckets = f" BUCKETS {buckets}" if buckets else "" 5428 order = self.sql(expression, "order") 5429 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
def
clusteredbyproperty_sql( self, expression: sqlglot.expressions.properties.ClusteredByProperty) -> str:
5434 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 5435 expressions = self.expressions(expression, key="expressions", flat=True) 5436 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 5437 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 5438 buckets = self.sql(expression, "buckets") 5439 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
5441 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 5442 this = self.sql(expression, "this") 5443 having = self.sql(expression, "having") 5444 5445 if having: 5446 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 5447 5448 return self.func("ANY_VALUE", this)
5450 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 5451 transform = self.func("TRANSFORM", *expression.expressions) 5452 row_format_before = self.sql(expression, "row_format_before") 5453 row_format_before = f" {row_format_before}" if row_format_before else "" 5454 record_writer = self.sql(expression, "record_writer") 5455 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 5456 using = f" USING {self.sql(expression, 'command_script')}" 5457 schema = self.sql(expression, "schema") 5458 schema = f" AS {schema}" if schema else "" 5459 row_format_after = self.sql(expression, "row_format_after") 5460 row_format_after = f" {row_format_after}" if row_format_after else "" 5461 record_reader = self.sql(expression, "record_reader") 5462 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 5463 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
def
indexconstraintoption_sql( self, expression: sqlglot.expressions.constraints.IndexConstraintOption) -> str:
5465 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 5466 key_block_size = self.sql(expression, "key_block_size") 5467 if key_block_size: 5468 return f"KEY_BLOCK_SIZE = {key_block_size}" 5469 5470 using = self.sql(expression, "using") 5471 if using: 5472 return f"USING {using}" 5473 5474 parser = self.sql(expression, "parser") 5475 if parser: 5476 return f"WITH PARSER {parser}" 5477 5478 comment = self.sql(expression, "comment") 5479 if comment: 5480 return f"COMMENT {comment}" 5481 5482 visible = expression.args.get("visible") 5483 if visible is not None: 5484 return "VISIBLE" if visible else "INVISIBLE" 5485 5486 engine_attr = self.sql(expression, "engine_attr") 5487 if engine_attr: 5488 return f"ENGINE_ATTRIBUTE = {engine_attr}" 5489 5490 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 5491 if secondary_engine_attr: 5492 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 5493 5494 self.unsupported("Unsupported index constraint option.") 5495 return ""
def
checkcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.CheckColumnConstraint) -> str:
def
indexcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.IndexColumnConstraint) -> str:
5501 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 5502 kind = self.sql(expression, "kind") 5503 kind = f"{kind} INDEX" if kind else "INDEX" 5504 this = self.sql(expression, "this") 5505 this = f" {this}" if this else "" 5506 index_type = self.sql(expression, "index_type") 5507 index_type = f" USING {index_type}" if index_type else "" 5508 expressions = self.expressions(expression, flat=True) 5509 expressions = f" ({expressions})" if expressions else "" 5510 options = self.expressions(expression, key="options", sep=" ") 5511 options = f" {options}" if options else "" 5512 return f"{kind}{this}{index_type}{expressions}{options}"
5514 def nvl2_sql(self, expression: exp.Nvl2) -> str: 5515 if self.NVL2_SUPPORTED: 5516 return self.function_fallback_sql(expression) 5517 5518 case = exp.Case().when( 5519 expression.this.is_(exp.null()).not_(copy=False), 5520 expression.args["true"], 5521 copy=False, 5522 ) 5523 else_cond = expression.args.get("false") 5524 if else_cond: 5525 case.else_(else_cond, copy=False) 5526 5527 return self.sql(case)
5535 def comprehension_sql(self, expression: exp.Comprehension) -> str: 5536 this = self.sql(expression, "this") 5537 expr = self.sql(expression, "expression") 5538 position = self.sql(expression, "position") 5539 position = f", {position}" if position else "" 5540 iterator = self.sql(expression, "iterator") 5541 condition = self.sql(expression, "condition") 5542 condition = f" IF {condition}" if condition else "" 5543 return f"{this} FOR {expr}{position} IN {iterator}{condition}"
def
generateembedding_sql(self, expression: sqlglot.expressions.functions.GenerateEmbedding) -> str:
5593 def aiforecast_sql(self, expression: exp.AIForecast) -> str: 5594 this_sql = self.sql(expression, "this") 5595 if isinstance(expression.this, exp.Table): 5596 this_sql = f"TABLE {this_sql}" 5597 5598 return self.func( 5599 "FORECAST", 5600 this_sql, 5601 expression.args.get("data_col"), 5602 expression.args.get("timestamp_col"), 5603 expression.args.get("model"), 5604 expression.args.get("id_cols"), 5605 expression.args.get("horizon"), 5606 expression.args.get("forecast_end_timestamp"), 5607 expression.args.get("confidence_level"), 5608 expression.args.get("output_historical_time_series"), 5609 expression.args.get("context_window"), 5610 )
5612 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 5613 this_sql = self.sql(expression, "this") 5614 if isinstance(expression.this, exp.Table): 5615 this_sql = f"TABLE {this_sql}" 5616 5617 return self.func( 5618 "FEATURES_AT_TIME", 5619 this_sql, 5620 expression.args.get("time"), 5621 expression.args.get("num_rows"), 5622 expression.args.get("ignore_feature_nulls"), 5623 )
5625 def vectorsearch_sql(self, expression: exp.VectorSearch) -> str: 5626 this_sql = self.sql(expression, "this") 5627 if isinstance(expression.this, exp.Table): 5628 this_sql = f"TABLE {this_sql}" 5629 5630 query_table = self.sql(expression, "query_table") 5631 if isinstance(expression.args["query_table"], exp.Table): 5632 query_table = f"TABLE {query_table}" 5633 5634 return self.func( 5635 "VECTOR_SEARCH", 5636 this_sql, 5637 expression.args.get("column_to_search"), 5638 query_table, 5639 expression.args.get("query_column_to_search"), 5640 expression.args.get("top_k"), 5641 expression.args.get("distance_type"), 5642 expression.args.get("options"), 5643 )
@unsupported_args('partition_start', 'partition_end', 'force', 'mode')
def
refresh_sql(self, expression: sqlglot.expressions.core.Refresh) -> str:
5650 @unsupported_args("partition_start", "partition_end", "force", "mode") 5651 def refresh_sql(self, expression: exp.Refresh) -> str: 5652 this = self.sql(expression, "this") 5653 kind = "" if isinstance(expression.this, exp.Literal) else f"{expression.text('kind')} " 5654 return f"REFRESH {kind}{this}"
5656 def toarray_sql(self, expression: exp.ToArray) -> str: 5657 arg = expression.this 5658 if not arg.type: 5659 import sqlglot.optimizer.annotate_types 5660 5661 arg = sqlglot.optimizer.annotate_types.annotate_types(arg, dialect=self.dialect) 5662 5663 if arg.is_type(exp.DType.ARRAY): 5664 return self.sql(arg) 5665 5666 cond_for_null = arg.is_(exp.null()) 5667 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
5669 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 5670 this = expression.this 5671 time_format = self.format_time(expression) 5672 5673 if time_format: 5674 return self.sql( 5675 exp.cast( 5676 exp.StrToTime(this=this, format=expression.args["format"]), 5677 exp.DType.TIME, 5678 ) 5679 ) 5680 5681 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DType.TIME): 5682 return self.sql(this) 5683 5684 return self.sql(exp.cast(this, exp.DType.TIME))
5686 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 5687 this = expression.this 5688 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DType.TIMESTAMP): 5689 return self.sql(this) 5690 5691 return self.sql(exp.cast(this, exp.DType.TIMESTAMP, dialect=self.dialect))
5693 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 5694 this = expression.this 5695 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DType.DATETIME): 5696 return self.sql(this) 5697 5698 return self.sql(exp.cast(this, exp.DType.DATETIME, dialect=self.dialect))
5700 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 5701 this = expression.this 5702 time_format = self.format_time(expression) 5703 safe = expression.args.get("safe") 5704 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 5705 return self.sql( 5706 exp.cast( 5707 exp.StrToTime(this=this, format=expression.args["format"], safe=safe), 5708 exp.DType.DATE, 5709 ) 5710 ) 5711 5712 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DType.DATE): 5713 return self.sql(this) 5714 5715 if safe: 5716 return self.sql(exp.TryCast(this=this, to=exp.DataType(this=exp.DType.DATE))) 5717 5718 return self.sql(exp.cast(this, exp.DType.DATE))
5730 def lastday_sql(self, expression: exp.LastDay) -> str: 5731 if self.LAST_DAY_SUPPORTS_DATE_PART: 5732 return self.function_fallback_sql(expression) 5733 5734 unit = expression.args.get("unit") 5735 if unit and unit.name.upper() != "MONTH": 5736 self.unsupported("Date parts are not supported in LAST_DAY.") 5737 5738 return self.func("LAST_DAY", expression.this)
def
arrayinsert_sql( self, expression: sqlglot.expressions.array.ArrayInsert, index_offset: int = 0) -> str:
5750 def arrayinsert_sql(self, expression: exp.ArrayInsert, index_offset: int = 0) -> str: 5751 this = expression.this 5752 position = expression.args["position"] 5753 offset = index_offset - (expression.args.get("offset") or 0) 5754 5755 if offset: 5756 if position.is_int: 5757 value = position.to_py() 5758 if value >= 0: 5759 position = exp.Literal.number(value + offset) 5760 elif offset < 0 and value == -1: 5761 # 1-based -1 appends, which a 0-based position can only express as the size 5762 position = exp.ArraySize(this=this.copy()) 5763 else: 5764 # Negative positions count from the end, so they shift in the opposite 5765 # direction, e.g. 0-based -1 (before the last element) is 1-based -2 5766 position = exp.Literal.number(value - offset) 5767 else: 5768 self.unsupported("ARRAY_INSERT position can only be converted if it's a literal") 5769 5770 return self.func("ARRAY_INSERT", this, position, expression.expression)
5772 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 5773 if self.CAN_IMPLEMENT_ARRAY_ANY: 5774 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 5775 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 5776 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 5777 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 5778 5779 import sqlglot.dialects.dialect 5780 5781 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 5782 if self.dialect.__class__ != sqlglot.dialects.dialect.Dialect: 5783 self.unsupported("ARRAY_ANY is unsupported") 5784 5785 return self.function_fallback_sql(expression)
5787 def struct_sql(self, expression: exp.Struct) -> str: 5788 expression.set( 5789 "expressions", 5790 [ 5791 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 5792 if isinstance(e, exp.PropertyEQ) 5793 else e 5794 for e in expression.expressions 5795 ], 5796 ) 5797 5798 return self.function_fallback_sql(expression)
5806 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 5807 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 5808 tables = f" {self.expressions(expression)}" 5809 5810 exists = " IF EXISTS" if expression.args.get("exists") else "" 5811 5812 on_cluster = self.sql(expression, "cluster") 5813 on_cluster = f" {on_cluster}" if on_cluster else "" 5814 5815 identity = self.sql(expression, "identity") 5816 identity = f" {identity} IDENTITY" if identity else "" 5817 5818 option = self.sql(expression, "option") 5819 option = f" {option}" if option else "" 5820 5821 partition = self.sql(expression, "partition") 5822 partition = f" {partition}" if partition else "" 5823 5824 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
5828 def convert_sql(self, expression: exp.Convert) -> str: 5829 to = expression.this 5830 value = expression.expression 5831 style = expression.args.get("style") 5832 safe = expression.args.get("safe") 5833 strict = expression.args.get("strict") 5834 5835 if not to or not value: 5836 return "" 5837 5838 # Retrieve length of datatype and override to default if not specified 5839 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5840 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 5841 5842 transformed: exp.Expr | None = None 5843 cast = exp.Cast if strict else exp.TryCast 5844 5845 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 5846 if isinstance(style, exp.Literal) and style.is_int: 5847 import sqlglot.dialects.tsql 5848 5849 style_value = style.name 5850 converted_style = sqlglot.dialects.tsql.TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 5851 if not converted_style: 5852 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 5853 5854 fmt = exp.Literal.string(converted_style) 5855 5856 if to.this == exp.DType.DATE: 5857 transformed = exp.StrToDate(this=value, format=fmt) 5858 elif to.this in (exp.DType.DATETIME, exp.DType.DATETIME2): 5859 transformed = exp.StrToTime(this=value, format=fmt) 5860 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 5861 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 5862 elif to.this == exp.DType.TEXT: 5863 transformed = exp.TimeToStr(this=value, format=fmt) 5864 5865 if not transformed: 5866 transformed = cast(this=value, to=to, safe=safe) 5867 5868 return self.sql(transformed)
5945 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 5946 option = self.sql(expression, "this") 5947 5948 if expression.expressions: 5949 upper = option.upper() 5950 5951 # Snowflake FILE_FORMAT options are separated by whitespace 5952 sep = " " if upper == "FILE_FORMAT" else ", " 5953 5954 # Databricks copy/format options do not set their list of values with EQ 5955 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 5956 values = self.expressions(expression, flat=True, sep=sep) 5957 return f"{option}{op}({values})" 5958 5959 value = self.sql(expression, "expression") 5960 5961 if not value: 5962 return option 5963 5964 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 5965 5966 return f"{option}{op}{value}"
5968 def credentials_sql(self, expression: exp.Credentials) -> str: 5969 cred_expr = expression.args.get("credentials") 5970 if isinstance(cred_expr, exp.Literal): 5971 # Redshift case: CREDENTIALS <string> 5972 credentials = self.sql(expression, "credentials") 5973 credentials = f"CREDENTIALS {credentials}" if credentials else "" 5974 else: 5975 # Snowflake case: CREDENTIALS = (...) 5976 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 5977 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 5978 5979 storage = self.sql(expression, "storage") 5980 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 5981 5982 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 5983 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 5984 5985 iam_role = self.sql(expression, "iam_role") 5986 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 5987 5988 region = self.sql(expression, "region") 5989 region = f" REGION {region}" if region else "" 5990 5991 return f"{credentials}{storage}{encryption}{iam_role}{region}"
5993 def copy_sql(self, expression: exp.Copy) -> str: 5994 this = self.sql(expression, "this") 5995 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 5996 5997 credentials = self.sql(expression, "credentials") 5998 credentials = self.seg(credentials) if credentials else "" 5999 files = self.expressions(expression, key="files", flat=True) 6000 kind = self.seg("FROM" if expression.args.get("kind") else "TO") if files else "" 6001 6002 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 6003 params = self.expressions( 6004 expression, 6005 key="params", 6006 sep=sep, 6007 new_line=True, 6008 skip_last=True, 6009 skip_first=True, 6010 indent=self.COPY_PARAMS_ARE_WRAPPED, 6011 ) 6012 6013 if params: 6014 if self.COPY_PARAMS_ARE_WRAPPED: 6015 params = f" WITH ({params})" 6016 elif not self.pretty and (files or credentials): 6017 params = f" {params}" 6018 6019 return f"COPY{this}{kind} {files}{credentials}{params}"
def
datadeletionproperty_sql( self, expression: sqlglot.expressions.properties.DataDeletionProperty) -> str:
6024 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 6025 on_sql = "ON" if expression.args.get("on") else "OFF" 6026 filter_col: str | None = self.sql(expression, "filter_column") 6027 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 6028 retention_period: str | None = self.sql(expression, "retention_period") 6029 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 6030 6031 if filter_col or retention_period: 6032 on_sql = self.func("ON", filter_col, retention_period) 6033 6034 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.MaskingPolicyColumnConstraint) -> str:
6036 def maskingpolicycolumnconstraint_sql( 6037 self, expression: exp.MaskingPolicyColumnConstraint 6038 ) -> str: 6039 this = self.sql(expression, "this") 6040 expressions = self.expressions(expression, flat=True) 6041 expressions = f" USING ({expressions})" if expressions else "" 6042 return f"MASKING POLICY {this}{expressions}"
6053 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 6054 this = self.sql(expression, "this") 6055 expr = expression.expression 6056 6057 if isinstance(expr, exp.Func): 6058 # T-SQL's CLR functions are case sensitive 6059 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 6060 else: 6061 expr = self.sql(expression, "expression") 6062 6063 return self.scope_resolution(expr, this)
6071 def rand_sql(self, expression: exp.Rand) -> str: 6072 lower = self.sql(expression, "lower") 6073 upper = self.sql(expression, "upper") 6074 6075 if lower and upper: 6076 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 6077 return self.func("RAND", expression.this)
6079 def changes_sql(self, expression: exp.Changes) -> str: 6080 information = self.sql(expression, "information") 6081 information = f"INFORMATION => {information}" 6082 at_before = self.sql(expression, "at_before") 6083 at_before = f"{self.seg('')}{at_before}" if at_before else "" 6084 end = self.sql(expression, "end") 6085 end = f"{self.seg('')}{end}" if end else "" 6086 6087 return f"CHANGES ({information}){at_before}{end}"
6089 def pad_sql(self, expression: exp.Pad) -> str: 6090 prefix = "L" if expression.args.get("is_left") else "R" 6091 6092 fill_pattern = self.sql(expression, "fill_pattern") or None 6093 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 6094 fill_pattern = "' '" 6095 6096 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql( self, expression: sqlglot.expressions.array.ExplodingGenerateSeries) -> str:
6102 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 6103 generate_series = exp.GenerateSeries(**expression.args) 6104 6105 parent = expression.parent 6106 if isinstance(parent, (exp.Alias, exp.TableAlias)): 6107 parent = parent.parent 6108 6109 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 6110 return self.sql(exp.Unnest(expressions=[generate_series])) 6111 6112 if isinstance(parent, exp.Select): 6113 self.unsupported("GenerateSeries projection unnesting is not supported.") 6114 6115 return self.sql(generate_series)
6117 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 6118 if self.SUPPORTS_CONVERT_TIMEZONE: 6119 return self.function_fallback_sql(expression) 6120 6121 source_tz = expression.args.get("source_tz") 6122 target_tz = expression.args.get("target_tz") 6123 timestamp = expression.args.get("timestamp") 6124 6125 if source_tz and timestamp: 6126 timestamp = exp.AtTimeZone( 6127 this=exp.cast(timestamp, exp.DType.TIMESTAMPNTZ), zone=source_tz 6128 ) 6129 6130 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 6131 6132 return self.sql(expr)
6134 def json_sql(self, expression: exp.JSON) -> str: 6135 this = self.sql(expression, "this") 6136 this = f" {this}" if this else "" 6137 6138 _with = expression.args.get("with_") 6139 6140 if _with is None: 6141 with_sql = "" 6142 elif not _with: 6143 with_sql = " WITHOUT" 6144 else: 6145 with_sql = " WITH" 6146 6147 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 6148 6149 return f"JSON{this}{with_sql}{unique_sql}"
6151 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 6152 path = self.sql(expression, "path") 6153 returning = self.sql(expression, "returning") 6154 returning = f" RETURNING {returning}" if returning else "" 6155 6156 on_condition = self.sql(expression, "on_condition") 6157 on_condition = f" {on_condition}" if on_condition else "" 6158 6159 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
6165 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 6166 else_ = "ELSE " if expression.args.get("else_") else "" 6167 condition = self.sql(expression, "expression") 6168 condition = f"WHEN {condition} THEN " if condition else else_ 6169 insert = self.sql(expression, "this")[len("INSERT") :].strip() 6170 return f"{condition}{insert}"
6172 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 6173 kind = self.sql(expression, "kind") 6174 source = self.sql(expression, "source") 6175 6176 if kind: 6177 expressions = self.seg(self.expressions(expression, sep=" ")) 6178 sql = f"INSERT {kind}{expressions}{self.seg(source)}" 6179 else: 6180 # If kind isn't present, we have Hive's FROM-first form: 6181 # FROM x INSERT ... SELECT ... [INSERT ... SELECT ...] 6182 inserts = self.sep().join(self.sql(e) for e in expression.expressions) 6183 sql = f"FROM {source}{self.seg(inserts)}" 6184 6185 return self.prepend_ctes(expression, sql)
6187 def oncondition_sql(self, expression: exp.OnCondition) -> str: 6188 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 6189 empty = expression.args.get("empty") 6190 empty = ( 6191 f"DEFAULT {empty} ON EMPTY" 6192 if isinstance(empty, exp.Expr) 6193 else self.sql(expression, "empty") 6194 ) 6195 6196 error = expression.args.get("error") 6197 error = ( 6198 f"DEFAULT {error} ON ERROR" 6199 if isinstance(error, exp.Expr) 6200 else self.sql(expression, "error") 6201 ) 6202 6203 if error and empty: 6204 error = ( 6205 f"{empty} {error}" 6206 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 6207 else f"{error} {empty}" 6208 ) 6209 empty = "" 6210 6211 null = self.sql(expression, "null") 6212 6213 return f"{empty}{error}{null}"
6219 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 6220 this = self.sql(expression, "this") 6221 path = self.sql(expression, "path") 6222 6223 passing = self.expressions(expression, "passing") 6224 passing = f" PASSING {passing}" if passing else "" 6225 6226 on_condition = self.sql(expression, "on_condition") 6227 on_condition = f" {on_condition}" if on_condition else "" 6228 6229 path = f"{path}{passing}{on_condition}" 6230 6231 return self.func("JSON_EXISTS", this, path)
6281 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 6282 array_agg = self.function_fallback_sql(expression) 6283 column_expr = expression.this 6284 if isinstance(column_expr, exp.Order): 6285 column_expr = column_expr.this 6286 6287 return self._add_arrayagg_null_filter(array_agg, expression, column_expr)
6289 def timeslice_sql(self, expression: exp.TimeSlice) -> str: 6290 # Only the SQLGlot dialect serializes the internal origin for round-tripping. 6291 origin = expression.args.get("origin") if self.dialect == "" else None 6292 kind = expression.args.get("kind") 6293 if origin is not None and kind is None: 6294 kind = exp.Literal.string("START") 6295 6296 return self.func( 6297 "TIME_SLICE", expression.this, expression.expression, expression.unit, kind, origin 6298 )
6300 def slice_sql(self, expression: exp.Slice) -> str: 6301 if "[" in self.dialect.tokenizer_class._IDENTIFIERS: 6302 self.unsupported("Slices are not supported") 6303 6304 step = self.sql(expression, "step") 6305 # An omitted end is written as `-` before a step, since `::` is the cast operator 6306 end = self.sql(expression.expression) or ("-" if step else "") 6307 begin = self.sql(expression.this) 6308 6309 sql = f"{end}:{step}" if step else end 6310 return f"{begin}:{sql}" if sql else f"{begin}:"
6383 def overlay_sql(self, expression: exp.Overlay) -> str: 6384 this = self.sql(expression, "this") 6385 expr = self.sql(expression, "expression") 6386 from_sql = self.sql(expression, "from_") 6387 for_sql = self.sql(expression, "for_") 6388 for_sql = f" FOR {for_sql}" if for_sql else "" 6389 6390 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.string.ToDouble) -> str:
6397 def string_sql(self, expression: exp.String) -> str: 6398 this = expression.this 6399 zone = expression.args.get("zone") 6400 6401 if zone: 6402 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 6403 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 6404 # set for source_tz to transpile the time conversion before the STRING cast 6405 this = exp.ConvertTimezone( 6406 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 6407 ) 6408 6409 return self.sql(exp.cast(this, exp.DType.VARCHAR))
def
overflowtruncatebehavior_sql( self, expression: sqlglot.expressions.query.OverflowTruncateBehavior) -> str:
6419 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 6420 filler = self.sql(expression, "this") 6421 filler = f" {filler}" if filler else "" 6422 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 6423 return f"TRUNCATE{filler} {with_count}"
6425 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 6426 if self.SUPPORTS_UNIX_SECONDS: 6427 return self.function_fallback_sql(expression) 6428 6429 start_ts = exp.cast(exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DType.TIMESTAMPTZ) 6430 6431 return self.sql( 6432 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 6433 )
6435 def arraysort_sql(self, expression: exp.ArraySort) -> str: 6436 asc = expression.args.get("asc") 6437 nulls_first = expression.args.get("nulls_first") 6438 if (asc and asc != exp.true()) or (nulls_first and nulls_first != exp.false()): 6439 self.unsupported("ARRAY_SORT only sorts ascending with NULLs last") 6440 return self.func("ARRAY_SORT", expression.this, expression.expression)
def
variance_sql( self, expression: sqlglot.expressions.aggregate.Variance, window: sqlglot.expressions.query.Window | None = None) -> str:
6442 def variance_sql(self, expression: exp.Variance, window: exp.Window | None = None) -> str: 6443 this = expression.this 6444 name = self.VARIANCE_NAME or self.function_name(expression) 6445 if not expression.args.get("single_value_returns_zero"): 6446 return self.func(name, this) 6447 6448 node: exp.Expr = expression 6449 while node.parent and not isinstance(node.parent, (exp.Window, exp.AggFunc, exp.Select)): 6450 node = node.parent 6451 if window is None and isinstance(node.parent, exp.Window) and node.arg_key == "this": 6452 self.unsupported("VARIANCE returning 0 for a single value is not supported in a window") 6453 return self.func(name, this) 6454 6455 expression.set("single_value_returns_zero", None) 6456 count: exp.Expr 6457 variance: exp.Expr = expression 6458 if window: 6459 count = window.copy() 6460 count.set("this", exp.Count(this=count.this.this)) 6461 variance = window 6462 else: 6463 count = exp.Count(this=this.copy()) 6464 6465 return self.sql( 6466 exp.case(count, copy=False) 6467 .when(0, exp.null(), copy=False) 6468 .when(1, 0, copy=False) 6469 .else_(variance, copy=False) 6470 )
6472 def arraysize_sql(self, expression: exp.ArraySize) -> str: 6473 dim = expression.expression 6474 6475 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 6476 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 6477 if not (dim.is_int and dim.name == "1"): 6478 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 6479 dim = None 6480 6481 # If dimension is required but not specified, default initialize it 6482 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 6483 dim = exp.Literal.number(1) 6484 6485 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
6487 def attach_sql(self, expression: exp.Attach) -> str: 6488 this = self.sql(expression, "this") 6489 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 6490 expressions = self.expressions(expression) 6491 expressions = f" ({expressions})" if expressions else "" 6492 6493 return f"ATTACH{exists_sql} {this}{expressions}"
6495 def detach_sql(self, expression: exp.Detach) -> str: 6496 kind = self.sql(expression, "kind") 6497 kind = f" {kind}" if kind else "" 6498 # the DATABASE keyword is required if IF EXISTS is set for DuckDB 6499 # ref: https://duckdb.org/docs/stable/sql/statements/attach.html#detach-syntax 6500 exists = " IF EXISTS" if expression.args.get("exists") else "" 6501 if exists: 6502 kind = kind or " DATABASE" 6503 6504 this = self.sql(expression, "this") 6505 this = f" {this}" if this else "" 6506 cluster = self.sql(expression, "cluster") 6507 cluster = f" {cluster}" if cluster else "" 6508 permanent = " PERMANENTLY" if expression.args.get("permanent") else "" 6509 sync = " SYNC" if expression.args.get("sync") else "" 6510 return f"DETACH{kind}{exists}{this}{cluster}{permanent}{sync}"
def
watermarkcolumnconstraint_sql( self, expression: sqlglot.expressions.constraints.WatermarkColumnConstraint) -> str:
6523 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 6524 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 6525 encode = f"{encode} {self.sql(expression, 'this')}" 6526 6527 properties = expression.args.get("properties") 6528 if properties: 6529 encode = f"{encode} {self.properties(properties)}" 6530 6531 return encode
6533 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 6534 this = self.sql(expression, "this") 6535 include = f"INCLUDE {this}" 6536 6537 column_def = self.sql(expression, "column_def") 6538 if column_def: 6539 include = f"{include} {column_def}" 6540 6541 alias = self.sql(expression, "alias") 6542 if alias: 6543 include = f"{include} AS {alias}" 6544 6545 return include
def
partitionbyrangeproperty_sql( self, expression: sqlglot.expressions.properties.PartitionByRangeProperty) -> str:
6558 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 6559 partitions = self.expressions(expression, "partition_expressions") 6560 create = self.expressions(expression, "create_expressions") 6561 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.properties.PartitionByRangePropertyDynamic) -> str:
6563 def partitionbyrangepropertydynamic_sql( 6564 self, expression: exp.PartitionByRangePropertyDynamic 6565 ) -> str: 6566 start = self.sql(expression, "start") 6567 end = self.sql(expression, "end") 6568 6569 every = expression.args["every"] 6570 if isinstance(every, exp.Interval) and every.this.is_string: 6571 every.this.replace(exp.Literal.number(every.name)) 6572 6573 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
6586 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 6587 kind = self.sql(expression, "kind") 6588 option = self.sql(expression, "option") 6589 option = f" {option}" if option else "" 6590 this = self.sql(expression, "this") 6591 this = f" {this}" if this else "" 6592 columns = self.expressions(expression) 6593 columns = f" {columns}" if columns else "" 6594 return f"{kind}{option} STATISTICS{this}{columns}"
6596 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 6597 this = self.sql(expression, "this") 6598 columns = self.expressions(expression) 6599 inner_expression = self.sql(expression, "expression") 6600 inner_expression = f" {inner_expression}" if inner_expression else "" 6601 update_options = self.sql(expression, "update_options") 6602 update_options = f" {update_options} UPDATE" if update_options else "" 6603 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql( self, expression: sqlglot.expressions.query.AnalyzeListChainedRows) -> str:
6614 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 6615 kind = self.sql(expression, "kind") 6616 this = self.sql(expression, "this") 6617 this = f" {this}" if this else "" 6618 inner_expression = self.sql(expression, "expression") 6619 return f"VALIDATE {kind}{this}{inner_expression}"
6621 def analyze_sql(self, expression: exp.Analyze) -> str: 6622 options = self.expressions(expression, key="options", sep=" ") 6623 options = f" {options}" if options else "" 6624 kind = self.sql(expression, "kind") 6625 kind = f" {kind}" if kind else "" 6626 tables = self.expressions(expression, key="tables", flat=True) 6627 tables = f" {tables}" if tables else "" 6628 mode = self.sql(expression, "mode") 6629 mode = f" {mode}" if mode else "" 6630 properties = self.sql(expression, "properties") 6631 properties = f" {properties}" if properties else "" 6632 partition = self.sql(expression, "partition") 6633 partition = f" {partition}" if partition else "" 6634 inner_expression = self.sql(expression, "expression") 6635 inner_expression = f" {inner_expression}" if inner_expression else "" 6636 return f"ANALYZE{options}{kind}{tables}{partition}{mode}{inner_expression}{properties}"
6638 def xmltable_sql(self, expression: exp.XMLTable) -> str: 6639 this = self.sql(expression, "this") 6640 namespaces = self.expressions(expression, key="namespaces") 6641 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 6642 passing = self.expressions(expression, key="passing") 6643 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 6644 columns = self.expressions(expression, key="columns") 6645 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 6646 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 6647 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
6653 def export_sql(self, expression: exp.Export) -> str: 6654 this = self.sql(expression, "this") 6655 connection = self.sql(expression, "connection") 6656 connection = f"WITH CONNECTION {connection} " if connection else "" 6657 options = self.sql(expression, "options") 6658 return f"EXPORT DATA {connection}{options} AS {this}"
6664 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 6665 variables = self.expressions(expression, "this") 6666 default = self.sql(expression, "default") 6667 default = f" {self.DECLARE_DEFAULT_ASSIGNMENT} {default}" if default else "" 6668 6669 kind = self.sql(expression, "kind") 6670 if isinstance(expression.args.get("kind"), exp.Schema): 6671 kind = f"TABLE {kind}" 6672 6673 kind = f" {kind}" if kind else "" 6674 6675 return f"{variables}{kind}{default}"
def
recursivewithsearch_sql(self, expression: sqlglot.expressions.query.RecursiveWithSearch) -> str:
6677 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 6678 kind = self.sql(expression, "kind") 6679 this = self.sql(expression, "this") 6680 set = self.sql(expression, "expression") 6681 to = self.sql(expression, "to") 6682 to = f" TO {to}" if to else "" 6683 default = self.sql(expression, "default") 6684 default = f" DEFAULT {default}" if default else "" 6685 using = self.sql(expression, "using") 6686 using = f" USING {using}" if using else "" 6687 6688 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 6689 6690 return f"{kind_sql} {this} SET {set}{to}{default}{using}"
def
combinedparameterizedagg_sql( self, expression: sqlglot.expressions.core.CombinedParameterizedAgg) -> str:
def
get_put_sql( self, expression: sqlglot.expressions.query.Put | sqlglot.expressions.query.Get) -> str:
6718 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 6719 # Snowflake GET/PUT statements: 6720 # PUT <file> <internalStage> <properties> 6721 # GET <internalStage> <file> <properties> 6722 props = expression.args.get("properties") 6723 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 6724 this = self.sql(expression, "this") 6725 target = self.sql(expression, "target") 6726 6727 if isinstance(expression, exp.Put): 6728 return f"PUT {this} {target}{props_sql}" 6729 else: 6730 return f"GET {target} {this}{props_sql}"
def
translatecharacters_sql(self, expression: sqlglot.expressions.query.TranslateCharacters) -> str:
6732 def translatecharacters_sql(self, expression: exp.TranslateCharacters) -> str: 6733 this = self.sql(expression, "this") 6734 expr = self.sql(expression, "expression") 6735 with_error = " WITH ERROR" if expression.args.get("with_error") else "" 6736 return f"TRANSLATE({this} USING {expr}{with_error})"
6738 def decodecase_sql(self, expression: exp.DecodeCase) -> str: 6739 if self.SUPPORTS_DECODE_CASE: 6740 return self.func("DECODE", *expression.expressions) 6741 6742 decode_expr, *expressions = expression.expressions 6743 6744 ifs = [] 6745 for search, result in zip(expressions[::2], expressions[1::2]): 6746 if isinstance(search, exp.Literal): 6747 ifs.append(exp.If(this=decode_expr.eq(search), true=result)) 6748 elif isinstance(search, exp.Null): 6749 ifs.append(exp.If(this=decode_expr.is_(exp.Null()), true=result)) 6750 else: 6751 if isinstance(search, exp.Binary): 6752 search = exp.paren(search) 6753 6754 cond = exp.or_( 6755 decode_expr.eq(search), 6756 exp.and_(decode_expr.is_(exp.Null()), search.is_(exp.Null()), copy=False), 6757 copy=False, 6758 ) 6759 ifs.append(exp.If(this=cond, true=result)) 6760 6761 case = exp.Case(ifs=ifs, default=expressions[-1] if len(expressions) % 2 == 1 else None) 6762 return self.sql(case)
6764 def semanticview_sql(self, expression: exp.SemanticView) -> str: 6765 this = self.sql(expression, "this") 6766 this = self.seg(this, sep="") 6767 dimensions = self.expressions( 6768 expression, "dimensions", dynamic=True, skip_first=True, skip_last=True 6769 ) 6770 dimensions = self.seg(f"DIMENSIONS {dimensions}") if dimensions else "" 6771 metrics = self.expressions( 6772 expression, "metrics", dynamic=True, skip_first=True, skip_last=True 6773 ) 6774 metrics = self.seg(f"METRICS {metrics}") if metrics else "" 6775 facts = self.expressions(expression, "facts", dynamic=True, skip_first=True, skip_last=True) 6776 facts = self.seg(f"FACTS {facts}") if facts else "" 6777 where = self.sql(expression, "where") 6778 where = self.seg(f"WHERE {where}") if where else "" 6779 body = self.indent(this + metrics + dimensions + facts + where, skip_first=True) 6780 return f"SEMANTIC_VIEW({body}{self.seg(')', sep='')}"
6782 def getextract_sql(self, expression: exp.GetExtract) -> str: 6783 this = expression.this 6784 expr = expression.expression 6785 6786 if not this.type or not expression.type: 6787 import sqlglot.optimizer.annotate_types 6788 6789 this = sqlglot.optimizer.annotate_types.annotate_types(this, dialect=self.dialect) 6790 6791 if this.is_type(*(exp.DType.ARRAY, exp.DType.MAP)): 6792 return self.sql(exp.Bracket(this=this, expressions=[expr])) 6793 6794 return self.sql(exp.JSONExtract(this=this, expression=self.dialect.to_json_path(expr)))
def
refreshtriggerproperty_sql( self, expression: sqlglot.expressions.properties.RefreshTriggerProperty) -> str:
6811 def refreshtriggerproperty_sql(self, expression: exp.RefreshTriggerProperty) -> str: 6812 method = self.sql(expression, "method") 6813 kind = expression.args.get("kind") 6814 if not kind: 6815 return f"REFRESH {method}" 6816 6817 every = self.sql(expression, "every") 6818 unit = self.sql(expression, "unit") 6819 every = f" EVERY {every} {unit}" if every else "" 6820 starts = self.sql(expression, "starts") 6821 starts = f" STARTS {starts}" if starts else "" 6822 6823 return f"REFRESH {method} ON {kind}{every}{starts}"
6832 def uuid_sql(self, expression: exp.Uuid) -> str: 6833 is_string = expression.args.get("is_string", False) 6834 uuid_func_sql = self.func("UUID") 6835 6836 if is_string and not self.dialect.UUID_IS_STRING_TYPE: 6837 return self.sql(exp.cast(uuid_func_sql, exp.DType.VARCHAR, dialect=self.dialect)) 6838 6839 return uuid_func_sql
6841 def initcap_sql(self, expression: exp.Initcap) -> str: 6842 delimiters = expression.expression 6843 6844 if delimiters: 6845 # do not generate delimiters arg if we are round-tripping from default delimiters 6846 if ( 6847 delimiters.is_string 6848 and delimiters.this == self.dialect.INITCAP_DEFAULT_DELIMITER_CHARS 6849 ): 6850 delimiters = None 6851 elif not self.dialect.INITCAP_SUPPORTS_CUSTOM_DELIMITERS: 6852 self.unsupported("INITCAP does not support custom delimiters") 6853 delimiters = None 6854 6855 return self.func("INITCAP", expression.this, delimiters)
6865 def weekstart_name(self, expression: exp.WeekStart) -> str: 6866 import sqlglot.dialects.dialect 6867 6868 # WEEK(<day>) is BigQuery-only syntax, so it degrades to the plain WEEK unit 6869 this = expression.this.name.upper() 6870 6871 dow_from_week_start_day = sqlglot.dialects.dialect.WEEK_START_DAY_TO_DOW.get(this) 6872 dow_from_week_offset = sqlglot.dialects.dialect.week_offset_to_dow(self.dialect.WEEK_OFFSET) 6873 6874 if dow_from_week_start_day != dow_from_week_offset: 6875 self.unsupported( 6876 f"WEEK({this}) is not supported; falling back to the default week start day" 6877 ) 6878 6879 return "WEEK"
6881 def weekstart_sql(self, expression: exp.WeekStart) -> str: 6882 name = self.weekstart_name(expression) 6883 6884 # DateTrunc stores string literal units, whereas TimeUnit expressions store keywords 6885 if isinstance(expression.parent, exp.DateTrunc): 6886 return self.sql(exp.Literal.string(name)) 6887 6888 return name
6890 def datetrunc_sql(self, expression: exp.DateTrunc) -> str: 6891 self._warn_unsupported_arg(expression, "century_from_zero") 6892 unit = expression.unit 6893 if unit.is_string and unit.name.upper() in ("WEEK_OF_MONTH", "WEEK_OF_YEAR"): 6894 self.unsupported(f"Unexpected interval unit: {unit.name}") 6895 6896 return self.function_fallback_sql(expression)
6898 def chr_sql(self, expression: exp.Chr, name: str = "CHR") -> str: 6899 args = expression.expressions 6900 if len(args) > 1 and not self.SUPPORTS_MULTI_ARG_CHR: 6901 # CHAR(72, 105) -> CHR(72) || CHR(105) 6902 chars: list[exp.Expr] = [exp.Chr(expressions=[arg.copy()]) for arg in args] 6903 return self.sql(reduce(lambda x, y: exp.DPipe(this=x, expression=y), chars)) 6904 6905 this = self.expressions(expression) 6906 charset = self.sql(expression, "charset") 6907 using = f" USING {charset}" if charset else "" 6908 return self.func(name, this + using)
def
functionspecification_sql(self, expression: sqlglot.expressions.query.FunctionSpecification) -> str:
6964 def executeimmediate_sql(self, expression: exp.ExecuteImmediate) -> str: 6965 if not self.SUPPORTS_EXECUTE_IMMEDIATE: 6966 self.unsupported("EXECUTE IMMEDIATE is not supported") 6967 return "" 6968 using = self.expressions(expression, flat=True) 6969 using = f" USING {using}" if using else "" 6970 return f"EXECUTE IMMEDIATE {self.sql(expression, 'this')}{using}"
def
altermodifysqlsecurity_sql(self, expression: sqlglot.expressions.ddl.AlterModifySqlSecurity) -> str: