sqlglot.generator
1from __future__ import annotations 2 3import logging 4import re 5import typing as t 6from collections import defaultdict 7from functools import reduce, wraps 8 9from sqlglot import exp 10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages 11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get 12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS 13from sqlglot.time import format_time 14from sqlglot.tokens import TokenType 15 16if t.TYPE_CHECKING: 17 from sqlglot._typing import E 18 from sqlglot.dialects.dialect import DialectType 19 20 G = t.TypeVar("G", bound="Generator") 21 GeneratorMethod = t.Callable[[G, E], str] 22 23logger = logging.getLogger("sqlglot") 24 25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)") 26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}." 27 28 29def unsupported_args( 30 *args: t.Union[str, t.Tuple[str, str]], 31) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 32 """ 33 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 34 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 35 """ 36 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 37 for arg in args: 38 if isinstance(arg, str): 39 diagnostic_by_arg[arg] = None 40 else: 41 diagnostic_by_arg[arg[0]] = arg[1] 42 43 def decorator(func: GeneratorMethod) -> GeneratorMethod: 44 @wraps(func) 45 def _func(generator: G, expression: E) -> str: 46 expression_name = expression.__class__.__name__ 47 dialect_name = generator.dialect.__class__.__name__ 48 49 for arg_name, diagnostic in diagnostic_by_arg.items(): 50 if expression.args.get(arg_name): 51 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 52 arg_name, expression_name, dialect_name 53 ) 54 generator.unsupported(diagnostic) 55 56 return func(generator, expression) 57 58 return _func 59 60 return decorator 61 62 63class _Generator(type): 64 def __new__(cls, clsname, bases, attrs): 65 klass = super().__new__(cls, clsname, bases, attrs) 66 67 # Remove transforms that correspond to unsupported JSONPathPart expressions 68 for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS: 69 klass.TRANSFORMS.pop(part, None) 70 71 return klass 72 73 74class Generator(metaclass=_Generator): 75 """ 76 Generator converts a given syntax tree to the corresponding SQL string. 77 78 Args: 79 pretty: Whether to format the produced SQL string. 80 Default: False. 81 identify: Determines when an identifier should be quoted. Possible values are: 82 False (default): Never quote, except in cases where it's mandatory by the dialect. 83 True or 'always': Always quote. 84 'safe': Only quote identifiers that are case insensitive. 85 normalize: Whether to normalize identifiers to lowercase. 86 Default: False. 87 pad: The pad size in a formatted string. For example, this affects the indentation of 88 a projection in a query, relative to its nesting level. 89 Default: 2. 90 indent: The indentation size in a formatted string. For example, this affects the 91 indentation of subqueries and filters under a `WHERE` clause. 92 Default: 2. 93 normalize_functions: How to normalize function names. Possible values are: 94 "upper" or True (default): Convert names to uppercase. 95 "lower": Convert names to lowercase. 96 False: Disables function name normalization. 97 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 98 Default ErrorLevel.WARN. 99 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 100 This is only relevant if unsupported_level is ErrorLevel.RAISE. 101 Default: 3 102 leading_comma: Whether the comma is leading or trailing in select expressions. 103 This is only relevant when generating in pretty mode. 104 Default: False 105 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 106 The default is on the smaller end because the length only represents a segment and not the true 107 line length. 108 Default: 80 109 comments: Whether to preserve comments in the output SQL code. 110 Default: True 111 """ 112 113 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 114 **JSON_PATH_PART_TRANSFORMS, 115 exp.AllowedValuesProperty: lambda self, 116 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 117 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 118 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 119 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 120 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 121 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 122 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 123 exp.CaseSpecificColumnConstraint: lambda _, 124 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 125 exp.Ceil: lambda self, e: self.ceil_floor(e), 126 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 127 exp.CharacterSetProperty: lambda self, 128 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 129 exp.ClusteredColumnConstraint: lambda self, 130 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 131 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 132 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 133 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 134 exp.ConvertToCharset: lambda self, e: self.func( 135 "CONVERT", e.this, e.args["dest"], e.args.get("source") 136 ), 137 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 138 exp.CredentialsProperty: lambda self, 139 e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})", 140 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 141 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 142 exp.DynamicProperty: lambda *_: "DYNAMIC", 143 exp.EmptyProperty: lambda *_: "EMPTY", 144 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 145 exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})", 146 exp.EphemeralColumnConstraint: lambda self, 147 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 148 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 149 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 150 exp.Except: lambda self, e: self.set_operations(e), 151 exp.ExternalProperty: lambda *_: "EXTERNAL", 152 exp.Floor: lambda self, e: self.ceil_floor(e), 153 exp.Get: lambda self, e: self.get_put_sql(e), 154 exp.GlobalProperty: lambda *_: "GLOBAL", 155 exp.HeapProperty: lambda *_: "HEAP", 156 exp.IcebergProperty: lambda *_: "ICEBERG", 157 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 158 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 159 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 160 exp.Intersect: lambda self, e: self.set_operations(e), 161 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 162 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 163 exp.LanguageProperty: lambda self, e: self.naked_property(e), 164 exp.LocationProperty: lambda self, e: self.naked_property(e), 165 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 166 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 167 exp.NonClusteredColumnConstraint: lambda self, 168 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 169 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 170 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 171 exp.OnCommitProperty: lambda _, 172 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 173 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 174 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 175 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 176 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 177 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 178 exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression), 179 exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression), 180 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 181 exp.ProjectionPolicyColumnConstraint: lambda self, 182 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 183 exp.Put: lambda self, e: self.get_put_sql(e), 184 exp.RemoteWithConnectionModelProperty: lambda self, 185 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 186 exp.ReturnsProperty: lambda self, e: ( 187 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 188 ), 189 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 190 exp.SecureProperty: lambda *_: "SECURE", 191 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 192 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 193 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 194 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 195 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 196 exp.SqlReadWriteProperty: lambda _, e: e.name, 197 exp.SqlSecurityProperty: lambda _, 198 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 199 exp.StabilityProperty: lambda _, e: e.name, 200 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 201 exp.StreamingTableProperty: lambda *_: "STREAMING", 202 exp.StrictProperty: lambda *_: "STRICT", 203 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 204 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 205 exp.TemporaryProperty: lambda *_: "TEMPORARY", 206 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 207 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 208 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 209 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 210 exp.TransientProperty: lambda *_: "TRANSIENT", 211 exp.Union: lambda self, e: self.set_operations(e), 212 exp.UnloggedProperty: lambda *_: "UNLOGGED", 213 exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 214 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 215 exp.Uuid: lambda *_: "UUID()", 216 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 217 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 218 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 219 exp.VolatileProperty: lambda *_: "VOLATILE", 220 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 221 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 222 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 223 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 224 exp.ForceProperty: lambda *_: "FORCE", 225 } 226 227 # Whether null ordering is supported in order by 228 # True: Full Support, None: No support, False: No support for certain cases 229 # such as window specifications, aggregate functions etc 230 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 231 232 # Whether ignore nulls is inside the agg or outside. 233 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 234 IGNORE_NULLS_IN_FUNC = False 235 236 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 237 LOCKING_READS_SUPPORTED = False 238 239 # Whether the EXCEPT and INTERSECT operations can return duplicates 240 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 241 242 # Wrap derived values in parens, usually standard but spark doesn't support it 243 WRAP_DERIVED_VALUES = True 244 245 # Whether create function uses an AS before the RETURN 246 CREATE_FUNCTION_RETURN_AS = True 247 248 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 249 MATCHED_BY_SOURCE = True 250 251 # Whether the INTERVAL expression works only with values like '1 day' 252 SINGLE_STRING_INTERVAL = False 253 254 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 255 INTERVAL_ALLOWS_PLURAL_FORM = True 256 257 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 258 LIMIT_FETCH = "ALL" 259 260 # Whether limit and fetch allows expresions or just limits 261 LIMIT_ONLY_LITERALS = False 262 263 # Whether a table is allowed to be renamed with a db 264 RENAME_TABLE_WITH_DB = True 265 266 # The separator for grouping sets and rollups 267 GROUPINGS_SEP = "," 268 269 # The string used for creating an index on a table 270 INDEX_ON = "ON" 271 272 # Whether join hints should be generated 273 JOIN_HINTS = True 274 275 # Whether table hints should be generated 276 TABLE_HINTS = True 277 278 # Whether query hints should be generated 279 QUERY_HINTS = True 280 281 # What kind of separator to use for query hints 282 QUERY_HINT_SEP = ", " 283 284 # Whether comparing against booleans (e.g. x IS TRUE) is supported 285 IS_BOOL_ALLOWED = True 286 287 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 288 DUPLICATE_KEY_UPDATE_WITH_SET = True 289 290 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 291 LIMIT_IS_TOP = False 292 293 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 294 RETURNING_END = True 295 296 # Whether to generate an unquoted value for EXTRACT's date part argument 297 EXTRACT_ALLOWS_QUOTES = True 298 299 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 300 TZ_TO_WITH_TIME_ZONE = False 301 302 # Whether the NVL2 function is supported 303 NVL2_SUPPORTED = True 304 305 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 306 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 307 308 # Whether VALUES statements can be used as derived tables. 309 # MySQL 5 and Redshift do not allow this, so when False, it will convert 310 # SELECT * VALUES into SELECT UNION 311 VALUES_AS_TABLE = True 312 313 # Whether the word COLUMN is included when adding a column with ALTER TABLE 314 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 315 316 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 317 UNNEST_WITH_ORDINALITY = True 318 319 # Whether FILTER (WHERE cond) can be used for conditional aggregation 320 AGGREGATE_FILTER_SUPPORTED = True 321 322 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 323 SEMI_ANTI_JOIN_WITH_SIDE = True 324 325 # Whether to include the type of a computed column in the CREATE DDL 326 COMPUTED_COLUMN_WITH_TYPE = True 327 328 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 329 SUPPORTS_TABLE_COPY = True 330 331 # Whether parentheses are required around the table sample's expression 332 TABLESAMPLE_REQUIRES_PARENS = True 333 334 # Whether a table sample clause's size needs to be followed by the ROWS keyword 335 TABLESAMPLE_SIZE_IS_ROWS = True 336 337 # The keyword(s) to use when generating a sample clause 338 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 339 340 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 341 TABLESAMPLE_WITH_METHOD = True 342 343 # The keyword to use when specifying the seed of a sample clause 344 TABLESAMPLE_SEED_KEYWORD = "SEED" 345 346 # Whether COLLATE is a function instead of a binary operator 347 COLLATE_IS_FUNC = False 348 349 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 350 DATA_TYPE_SPECIFIERS_ALLOWED = False 351 352 # Whether conditions require booleans WHERE x = 0 vs WHERE x 353 ENSURE_BOOLS = False 354 355 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 356 CTE_RECURSIVE_KEYWORD_REQUIRED = True 357 358 # Whether CONCAT requires >1 arguments 359 SUPPORTS_SINGLE_ARG_CONCAT = True 360 361 # Whether LAST_DAY function supports a date part argument 362 LAST_DAY_SUPPORTS_DATE_PART = True 363 364 # Whether named columns are allowed in table aliases 365 SUPPORTS_TABLE_ALIAS_COLUMNS = True 366 367 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 368 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 369 370 # What delimiter to use for separating JSON key/value pairs 371 JSON_KEY_VALUE_PAIR_SEP = ":" 372 373 # INSERT OVERWRITE TABLE x override 374 INSERT_OVERWRITE = " OVERWRITE TABLE" 375 376 # Whether the SELECT .. INTO syntax is used instead of CTAS 377 SUPPORTS_SELECT_INTO = False 378 379 # Whether UNLOGGED tables can be created 380 SUPPORTS_UNLOGGED_TABLES = False 381 382 # Whether the CREATE TABLE LIKE statement is supported 383 SUPPORTS_CREATE_TABLE_LIKE = True 384 385 # Whether the LikeProperty needs to be specified inside of the schema clause 386 LIKE_PROPERTY_INSIDE_SCHEMA = False 387 388 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 389 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 390 MULTI_ARG_DISTINCT = True 391 392 # Whether the JSON extraction operators expect a value of type JSON 393 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 394 395 # Whether bracketed keys like ["foo"] are supported in JSON paths 396 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 397 398 # Whether to escape keys using single quotes in JSON paths 399 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 400 401 # The JSONPathPart expressions supported by this dialect 402 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 403 404 # Whether any(f(x) for x in array) can be implemented by this dialect 405 CAN_IMPLEMENT_ARRAY_ANY = False 406 407 # Whether the function TO_NUMBER is supported 408 SUPPORTS_TO_NUMBER = True 409 410 # Whether EXCLUDE in window specification is supported 411 SUPPORTS_WINDOW_EXCLUDE = False 412 413 # Whether or not set op modifiers apply to the outer set op or select. 414 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 415 # True means limit 1 happens after the set op, False means it it happens on y. 416 SET_OP_MODIFIERS = True 417 418 # Whether parameters from COPY statement are wrapped in parentheses 419 COPY_PARAMS_ARE_WRAPPED = True 420 421 # Whether values of params are set with "=" token or empty space 422 COPY_PARAMS_EQ_REQUIRED = False 423 424 # Whether COPY statement has INTO keyword 425 COPY_HAS_INTO_KEYWORD = True 426 427 # Whether the conditional TRY(expression) function is supported 428 TRY_SUPPORTED = True 429 430 # Whether the UESCAPE syntax in unicode strings is supported 431 SUPPORTS_UESCAPE = True 432 433 # The keyword to use when generating a star projection with excluded columns 434 STAR_EXCEPT = "EXCEPT" 435 436 # The HEX function name 437 HEX_FUNC = "HEX" 438 439 # The keywords to use when prefixing & separating WITH based properties 440 WITH_PROPERTIES_PREFIX = "WITH" 441 442 # Whether to quote the generated expression of exp.JsonPath 443 QUOTE_JSON_PATH = True 444 445 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 446 PAD_FILL_PATTERN_IS_REQUIRED = False 447 448 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 449 SUPPORTS_EXPLODING_PROJECTIONS = True 450 451 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 452 ARRAY_CONCAT_IS_VAR_LEN = True 453 454 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 455 SUPPORTS_CONVERT_TIMEZONE = False 456 457 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 458 SUPPORTS_MEDIAN = True 459 460 # Whether UNIX_SECONDS(timestamp) is supported 461 SUPPORTS_UNIX_SECONDS = False 462 463 # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>) 464 ALTER_SET_WRAPPED = False 465 466 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 467 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 468 469 # The function name of the exp.ArraySize expression 470 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 471 472 # The syntax to use when altering the type of a column 473 ALTER_SET_TYPE = "SET DATA TYPE" 474 475 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 476 # None -> Doesn't support it at all 477 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 478 # True (Postgres) -> Explicitly requires it 479 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 480 481 TYPE_MAPPING = { 482 exp.DataType.Type.DATETIME2: "TIMESTAMP", 483 exp.DataType.Type.NCHAR: "CHAR", 484 exp.DataType.Type.NVARCHAR: "VARCHAR", 485 exp.DataType.Type.MEDIUMTEXT: "TEXT", 486 exp.DataType.Type.LONGTEXT: "TEXT", 487 exp.DataType.Type.TINYTEXT: "TEXT", 488 exp.DataType.Type.BLOB: "VARBINARY", 489 exp.DataType.Type.MEDIUMBLOB: "BLOB", 490 exp.DataType.Type.LONGBLOB: "BLOB", 491 exp.DataType.Type.TINYBLOB: "BLOB", 492 exp.DataType.Type.INET: "INET", 493 exp.DataType.Type.ROWVERSION: "VARBINARY", 494 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 495 } 496 497 TIME_PART_SINGULARS = { 498 "MICROSECONDS": "MICROSECOND", 499 "SECONDS": "SECOND", 500 "MINUTES": "MINUTE", 501 "HOURS": "HOUR", 502 "DAYS": "DAY", 503 "WEEKS": "WEEK", 504 "MONTHS": "MONTH", 505 "QUARTERS": "QUARTER", 506 "YEARS": "YEAR", 507 } 508 509 AFTER_HAVING_MODIFIER_TRANSFORMS = { 510 "cluster": lambda self, e: self.sql(e, "cluster"), 511 "distribute": lambda self, e: self.sql(e, "distribute"), 512 "sort": lambda self, e: self.sql(e, "sort"), 513 "windows": lambda self, e: ( 514 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 515 if e.args.get("windows") 516 else "" 517 ), 518 "qualify": lambda self, e: self.sql(e, "qualify"), 519 } 520 521 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 522 523 STRUCT_DELIMITER = ("<", ">") 524 525 PARAMETER_TOKEN = "@" 526 NAMED_PLACEHOLDER_TOKEN = ":" 527 528 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 529 530 PROPERTIES_LOCATION = { 531 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 532 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 533 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 537 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 539 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 542 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 543 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 544 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 546 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 547 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 548 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 549 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 551 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 555 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 558 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 559 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 560 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 561 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 562 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 563 exp.HeapProperty: exp.Properties.Location.POST_WITH, 564 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 565 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 566 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 569 exp.JournalProperty: exp.Properties.Location.POST_NAME, 570 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 575 exp.LogProperty: exp.Properties.Location.POST_NAME, 576 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 577 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 578 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 579 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 580 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 581 exp.Order: exp.Properties.Location.POST_SCHEMA, 582 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 583 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 584 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 585 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 586 exp.Property: exp.Properties.Location.POST_WITH, 587 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 588 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 593 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 594 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 595 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 596 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 597 exp.Set: exp.Properties.Location.POST_SCHEMA, 598 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 599 exp.SetProperty: exp.Properties.Location.POST_CREATE, 600 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 601 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 602 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 603 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 604 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 605 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 606 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 607 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 608 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 609 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 610 exp.Tags: exp.Properties.Location.POST_WITH, 611 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 612 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 613 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 614 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 615 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 616 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 617 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 618 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 619 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 620 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 621 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 622 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 623 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 624 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 625 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 626 } 627 628 # Keywords that can't be used as unquoted identifier names 629 RESERVED_KEYWORDS: t.Set[str] = set() 630 631 # Expressions whose comments are separated from them for better formatting 632 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 633 exp.Command, 634 exp.Create, 635 exp.Describe, 636 exp.Delete, 637 exp.Drop, 638 exp.From, 639 exp.Insert, 640 exp.Join, 641 exp.MultitableInserts, 642 exp.Select, 643 exp.SetOperation, 644 exp.Update, 645 exp.Where, 646 exp.With, 647 ) 648 649 # Expressions that should not have their comments generated in maybe_comment 650 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 651 exp.Binary, 652 exp.SetOperation, 653 ) 654 655 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 656 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 657 exp.Column, 658 exp.Literal, 659 exp.Neg, 660 exp.Paren, 661 ) 662 663 PARAMETERIZABLE_TEXT_TYPES = { 664 exp.DataType.Type.NVARCHAR, 665 exp.DataType.Type.VARCHAR, 666 exp.DataType.Type.CHAR, 667 exp.DataType.Type.NCHAR, 668 } 669 670 # Expressions that need to have all CTEs under them bubbled up to them 671 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 672 673 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.Tuple[t.Type[exp.Expression], ...] = () 674 675 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 676 677 __slots__ = ( 678 "pretty", 679 "identify", 680 "normalize", 681 "pad", 682 "_indent", 683 "normalize_functions", 684 "unsupported_level", 685 "max_unsupported", 686 "leading_comma", 687 "max_text_width", 688 "comments", 689 "dialect", 690 "unsupported_messages", 691 "_escaped_quote_end", 692 "_escaped_identifier_end", 693 "_next_name", 694 "_identifier_start", 695 "_identifier_end", 696 "_quote_json_path_key_using_brackets", 697 ) 698 699 def __init__( 700 self, 701 pretty: t.Optional[bool] = None, 702 identify: str | bool = False, 703 normalize: bool = False, 704 pad: int = 2, 705 indent: int = 2, 706 normalize_functions: t.Optional[str | bool] = None, 707 unsupported_level: ErrorLevel = ErrorLevel.WARN, 708 max_unsupported: int = 3, 709 leading_comma: bool = False, 710 max_text_width: int = 80, 711 comments: bool = True, 712 dialect: DialectType = None, 713 ): 714 import sqlglot 715 from sqlglot.dialects import Dialect 716 717 self.pretty = pretty if pretty is not None else sqlglot.pretty 718 self.identify = identify 719 self.normalize = normalize 720 self.pad = pad 721 self._indent = indent 722 self.unsupported_level = unsupported_level 723 self.max_unsupported = max_unsupported 724 self.leading_comma = leading_comma 725 self.max_text_width = max_text_width 726 self.comments = comments 727 self.dialect = Dialect.get_or_raise(dialect) 728 729 # This is both a Dialect property and a Generator argument, so we prioritize the latter 730 self.normalize_functions = ( 731 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 732 ) 733 734 self.unsupported_messages: t.List[str] = [] 735 self._escaped_quote_end: str = ( 736 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 737 ) 738 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 739 740 self._next_name = name_sequence("_t") 741 742 self._identifier_start = self.dialect.IDENTIFIER_START 743 self._identifier_end = self.dialect.IDENTIFIER_END 744 745 self._quote_json_path_key_using_brackets = True 746 747 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 748 """ 749 Generates the SQL string corresponding to the given syntax tree. 750 751 Args: 752 expression: The syntax tree. 753 copy: Whether to copy the expression. The generator performs mutations so 754 it is safer to copy. 755 756 Returns: 757 The SQL string corresponding to `expression`. 758 """ 759 if copy: 760 expression = expression.copy() 761 762 expression = self.preprocess(expression) 763 764 self.unsupported_messages = [] 765 sql = self.sql(expression).strip() 766 767 if self.pretty: 768 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 769 770 if self.unsupported_level == ErrorLevel.IGNORE: 771 return sql 772 773 if self.unsupported_level == ErrorLevel.WARN: 774 for msg in self.unsupported_messages: 775 logger.warning(msg) 776 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 777 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 778 779 return sql 780 781 def preprocess(self, expression: exp.Expression) -> exp.Expression: 782 """Apply generic preprocessing transformations to a given expression.""" 783 expression = self._move_ctes_to_top_level(expression) 784 785 if self.ENSURE_BOOLS: 786 from sqlglot.transforms import ensure_bools 787 788 expression = ensure_bools(expression) 789 790 return expression 791 792 def _move_ctes_to_top_level(self, expression: E) -> E: 793 if ( 794 not expression.parent 795 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 796 and any(node.parent is not expression for node in expression.find_all(exp.With)) 797 ): 798 from sqlglot.transforms import move_ctes_to_top_level 799 800 expression = move_ctes_to_top_level(expression) 801 return expression 802 803 def unsupported(self, message: str) -> None: 804 if self.unsupported_level == ErrorLevel.IMMEDIATE: 805 raise UnsupportedError(message) 806 self.unsupported_messages.append(message) 807 808 def sep(self, sep: str = " ") -> str: 809 return f"{sep.strip()}\n" if self.pretty else sep 810 811 def seg(self, sql: str, sep: str = " ") -> str: 812 return f"{self.sep(sep)}{sql}" 813 814 def sanitize_comment(self, comment: str) -> str: 815 comment = " " + comment if comment[0].strip() else comment 816 comment = comment + " " if comment[-1].strip() else comment 817 818 if not self.dialect.tokenizer_class.NESTED_COMMENTS: 819 # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */ 820 comment = comment.replace("*/", "* /") 821 822 return comment 823 824 def maybe_comment( 825 self, 826 sql: str, 827 expression: t.Optional[exp.Expression] = None, 828 comments: t.Optional[t.List[str]] = None, 829 separated: bool = False, 830 ) -> str: 831 comments = ( 832 ((expression and expression.comments) if comments is None else comments) # type: ignore 833 if self.comments 834 else None 835 ) 836 837 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 838 return sql 839 840 comments_sql = " ".join( 841 f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment 842 ) 843 844 if not comments_sql: 845 return sql 846 847 comments_sql = self._replace_line_breaks(comments_sql) 848 849 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 850 return ( 851 f"{self.sep()}{comments_sql}{sql}" 852 if not sql or sql[0].isspace() 853 else f"{comments_sql}{self.sep()}{sql}" 854 ) 855 856 return f"{sql} {comments_sql}" 857 858 def wrap(self, expression: exp.Expression | str) -> str: 859 this_sql = ( 860 self.sql(expression) 861 if isinstance(expression, exp.UNWRAPPED_QUERIES) 862 else self.sql(expression, "this") 863 ) 864 if not this_sql: 865 return "()" 866 867 this_sql = self.indent(this_sql, level=1, pad=0) 868 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 869 870 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 871 original = self.identify 872 self.identify = False 873 result = func(*args, **kwargs) 874 self.identify = original 875 return result 876 877 def normalize_func(self, name: str) -> str: 878 if self.normalize_functions == "upper" or self.normalize_functions is True: 879 return name.upper() 880 if self.normalize_functions == "lower": 881 return name.lower() 882 return name 883 884 def indent( 885 self, 886 sql: str, 887 level: int = 0, 888 pad: t.Optional[int] = None, 889 skip_first: bool = False, 890 skip_last: bool = False, 891 ) -> str: 892 if not self.pretty or not sql: 893 return sql 894 895 pad = self.pad if pad is None else pad 896 lines = sql.split("\n") 897 898 return "\n".join( 899 ( 900 line 901 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 902 else f"{' ' * (level * self._indent + pad)}{line}" 903 ) 904 for i, line in enumerate(lines) 905 ) 906 907 def sql( 908 self, 909 expression: t.Optional[str | exp.Expression], 910 key: t.Optional[str] = None, 911 comment: bool = True, 912 ) -> str: 913 if not expression: 914 return "" 915 916 if isinstance(expression, str): 917 return expression 918 919 if key: 920 value = expression.args.get(key) 921 if value: 922 return self.sql(value) 923 return "" 924 925 transform = self.TRANSFORMS.get(expression.__class__) 926 927 if callable(transform): 928 sql = transform(self, expression) 929 elif isinstance(expression, exp.Expression): 930 exp_handler_name = f"{expression.key}_sql" 931 932 if hasattr(self, exp_handler_name): 933 sql = getattr(self, exp_handler_name)(expression) 934 elif isinstance(expression, exp.Func): 935 sql = self.function_fallback_sql(expression) 936 elif isinstance(expression, exp.Property): 937 sql = self.property_sql(expression) 938 else: 939 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 940 else: 941 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 942 943 return self.maybe_comment(sql, expression) if self.comments and comment else sql 944 945 def uncache_sql(self, expression: exp.Uncache) -> str: 946 table = self.sql(expression, "this") 947 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 948 return f"UNCACHE TABLE{exists_sql} {table}" 949 950 def cache_sql(self, expression: exp.Cache) -> str: 951 lazy = " LAZY" if expression.args.get("lazy") else "" 952 table = self.sql(expression, "this") 953 options = expression.args.get("options") 954 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 955 sql = self.sql(expression, "expression") 956 sql = f" AS{self.sep()}{sql}" if sql else "" 957 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 958 return self.prepend_ctes(expression, sql) 959 960 def characterset_sql(self, expression: exp.CharacterSet) -> str: 961 if isinstance(expression.parent, exp.Cast): 962 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 963 default = "DEFAULT " if expression.args.get("default") else "" 964 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 965 966 def column_parts(self, expression: exp.Column) -> str: 967 return ".".join( 968 self.sql(part) 969 for part in ( 970 expression.args.get("catalog"), 971 expression.args.get("db"), 972 expression.args.get("table"), 973 expression.args.get("this"), 974 ) 975 if part 976 ) 977 978 def column_sql(self, expression: exp.Column) -> str: 979 join_mark = " (+)" if expression.args.get("join_mark") else "" 980 981 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 982 join_mark = "" 983 self.unsupported("Outer join syntax using the (+) operator is not supported.") 984 985 return f"{self.column_parts(expression)}{join_mark}" 986 987 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 988 this = self.sql(expression, "this") 989 this = f" {this}" if this else "" 990 position = self.sql(expression, "position") 991 return f"{position}{this}" 992 993 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 994 column = self.sql(expression, "this") 995 kind = self.sql(expression, "kind") 996 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 997 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 998 kind = f"{sep}{kind}" if kind else "" 999 constraints = f" {constraints}" if constraints else "" 1000 position = self.sql(expression, "position") 1001 position = f" {position}" if position else "" 1002 1003 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1004 kind = "" 1005 1006 return f"{exists}{column}{kind}{constraints}{position}" 1007 1008 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 1009 this = self.sql(expression, "this") 1010 kind_sql = self.sql(expression, "kind").strip() 1011 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 1012 1013 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1014 this = self.sql(expression, "this") 1015 if expression.args.get("not_null"): 1016 persisted = " PERSISTED NOT NULL" 1017 elif expression.args.get("persisted"): 1018 persisted = " PERSISTED" 1019 else: 1020 persisted = "" 1021 return f"AS {this}{persisted}" 1022 1023 def autoincrementcolumnconstraint_sql(self, _) -> str: 1024 return self.token_sql(TokenType.AUTO_INCREMENT) 1025 1026 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1027 if isinstance(expression.this, list): 1028 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1029 else: 1030 this = self.sql(expression, "this") 1031 1032 return f"COMPRESS {this}" 1033 1034 def generatedasidentitycolumnconstraint_sql( 1035 self, expression: exp.GeneratedAsIdentityColumnConstraint 1036 ) -> str: 1037 this = "" 1038 if expression.this is not None: 1039 on_null = " ON NULL" if expression.args.get("on_null") else "" 1040 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1041 1042 start = expression.args.get("start") 1043 start = f"START WITH {start}" if start else "" 1044 increment = expression.args.get("increment") 1045 increment = f" INCREMENT BY {increment}" if increment else "" 1046 minvalue = expression.args.get("minvalue") 1047 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1048 maxvalue = expression.args.get("maxvalue") 1049 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1050 cycle = expression.args.get("cycle") 1051 cycle_sql = "" 1052 1053 if cycle is not None: 1054 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1055 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1056 1057 sequence_opts = "" 1058 if start or increment or cycle_sql: 1059 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1060 sequence_opts = f" ({sequence_opts.strip()})" 1061 1062 expr = self.sql(expression, "expression") 1063 expr = f"({expr})" if expr else "IDENTITY" 1064 1065 return f"GENERATED{this} AS {expr}{sequence_opts}" 1066 1067 def generatedasrowcolumnconstraint_sql( 1068 self, expression: exp.GeneratedAsRowColumnConstraint 1069 ) -> str: 1070 start = "START" if expression.args.get("start") else "END" 1071 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1072 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1073 1074 def periodforsystemtimeconstraint_sql( 1075 self, expression: exp.PeriodForSystemTimeConstraint 1076 ) -> str: 1077 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1078 1079 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1080 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1081 1082 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1083 return f"AS {self.sql(expression, 'this')}" 1084 1085 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1086 desc = expression.args.get("desc") 1087 if desc is not None: 1088 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1089 options = self.expressions(expression, key="options", flat=True, sep=" ") 1090 options = f" {options}" if options else "" 1091 return f"PRIMARY KEY{options}" 1092 1093 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1094 this = self.sql(expression, "this") 1095 this = f" {this}" if this else "" 1096 index_type = expression.args.get("index_type") 1097 index_type = f" USING {index_type}" if index_type else "" 1098 on_conflict = self.sql(expression, "on_conflict") 1099 on_conflict = f" {on_conflict}" if on_conflict else "" 1100 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1101 options = self.expressions(expression, key="options", flat=True, sep=" ") 1102 options = f" {options}" if options else "" 1103 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}" 1104 1105 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1106 return self.sql(expression, "this") 1107 1108 def create_sql(self, expression: exp.Create) -> str: 1109 kind = self.sql(expression, "kind") 1110 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1111 properties = expression.args.get("properties") 1112 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1113 1114 this = self.createable_sql(expression, properties_locs) 1115 1116 properties_sql = "" 1117 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1118 exp.Properties.Location.POST_WITH 1119 ): 1120 properties_sql = self.sql( 1121 exp.Properties( 1122 expressions=[ 1123 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1124 *properties_locs[exp.Properties.Location.POST_WITH], 1125 ] 1126 ) 1127 ) 1128 1129 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1130 properties_sql = self.sep() + properties_sql 1131 elif not self.pretty: 1132 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1133 properties_sql = f" {properties_sql}" 1134 1135 begin = " BEGIN" if expression.args.get("begin") else "" 1136 end = " END" if expression.args.get("end") else "" 1137 1138 expression_sql = self.sql(expression, "expression") 1139 if expression_sql: 1140 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1141 1142 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1143 postalias_props_sql = "" 1144 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1145 postalias_props_sql = self.properties( 1146 exp.Properties( 1147 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1148 ), 1149 wrapped=False, 1150 ) 1151 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1152 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1153 1154 postindex_props_sql = "" 1155 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1156 postindex_props_sql = self.properties( 1157 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1158 wrapped=False, 1159 prefix=" ", 1160 ) 1161 1162 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1163 indexes = f" {indexes}" if indexes else "" 1164 index_sql = indexes + postindex_props_sql 1165 1166 replace = " OR REPLACE" if expression.args.get("replace") else "" 1167 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1168 unique = " UNIQUE" if expression.args.get("unique") else "" 1169 1170 clustered = expression.args.get("clustered") 1171 if clustered is None: 1172 clustered_sql = "" 1173 elif clustered: 1174 clustered_sql = " CLUSTERED COLUMNSTORE" 1175 else: 1176 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1177 1178 postcreate_props_sql = "" 1179 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1180 postcreate_props_sql = self.properties( 1181 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1182 sep=" ", 1183 prefix=" ", 1184 wrapped=False, 1185 ) 1186 1187 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1188 1189 postexpression_props_sql = "" 1190 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1191 postexpression_props_sql = self.properties( 1192 exp.Properties( 1193 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1194 ), 1195 sep=" ", 1196 prefix=" ", 1197 wrapped=False, 1198 ) 1199 1200 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1201 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1202 no_schema_binding = ( 1203 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1204 ) 1205 1206 clone = self.sql(expression, "clone") 1207 clone = f" {clone}" if clone else "" 1208 1209 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1210 properties_expression = f"{expression_sql}{properties_sql}" 1211 else: 1212 properties_expression = f"{properties_sql}{expression_sql}" 1213 1214 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1215 return self.prepend_ctes(expression, expression_sql) 1216 1217 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1218 start = self.sql(expression, "start") 1219 start = f"START WITH {start}" if start else "" 1220 increment = self.sql(expression, "increment") 1221 increment = f" INCREMENT BY {increment}" if increment else "" 1222 minvalue = self.sql(expression, "minvalue") 1223 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1224 maxvalue = self.sql(expression, "maxvalue") 1225 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1226 owned = self.sql(expression, "owned") 1227 owned = f" OWNED BY {owned}" if owned else "" 1228 1229 cache = expression.args.get("cache") 1230 if cache is None: 1231 cache_str = "" 1232 elif cache is True: 1233 cache_str = " CACHE" 1234 else: 1235 cache_str = f" CACHE {cache}" 1236 1237 options = self.expressions(expression, key="options", flat=True, sep=" ") 1238 options = f" {options}" if options else "" 1239 1240 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1241 1242 def clone_sql(self, expression: exp.Clone) -> str: 1243 this = self.sql(expression, "this") 1244 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1245 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1246 return f"{shallow}{keyword} {this}" 1247 1248 def describe_sql(self, expression: exp.Describe) -> str: 1249 style = expression.args.get("style") 1250 style = f" {style}" if style else "" 1251 partition = self.sql(expression, "partition") 1252 partition = f" {partition}" if partition else "" 1253 format = self.sql(expression, "format") 1254 format = f" {format}" if format else "" 1255 1256 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1257 1258 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1259 tag = self.sql(expression, "tag") 1260 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1261 1262 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1263 with_ = self.sql(expression, "with") 1264 if with_: 1265 sql = f"{with_}{self.sep()}{sql}" 1266 return sql 1267 1268 def with_sql(self, expression: exp.With) -> str: 1269 sql = self.expressions(expression, flat=True) 1270 recursive = ( 1271 "RECURSIVE " 1272 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1273 else "" 1274 ) 1275 search = self.sql(expression, "search") 1276 search = f" {search}" if search else "" 1277 1278 return f"WITH {recursive}{sql}{search}" 1279 1280 def cte_sql(self, expression: exp.CTE) -> str: 1281 alias = expression.args.get("alias") 1282 if alias: 1283 alias.add_comments(expression.pop_comments()) 1284 1285 alias_sql = self.sql(expression, "alias") 1286 1287 materialized = expression.args.get("materialized") 1288 if materialized is False: 1289 materialized = "NOT MATERIALIZED " 1290 elif materialized: 1291 materialized = "MATERIALIZED " 1292 1293 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1294 1295 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1296 alias = self.sql(expression, "this") 1297 columns = self.expressions(expression, key="columns", flat=True) 1298 columns = f"({columns})" if columns else "" 1299 1300 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1301 columns = "" 1302 self.unsupported("Named columns are not supported in table alias.") 1303 1304 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1305 alias = self._next_name() 1306 1307 return f"{alias}{columns}" 1308 1309 def bitstring_sql(self, expression: exp.BitString) -> str: 1310 this = self.sql(expression, "this") 1311 if self.dialect.BIT_START: 1312 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1313 return f"{int(this, 2)}" 1314 1315 def hexstring_sql( 1316 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1317 ) -> str: 1318 this = self.sql(expression, "this") 1319 is_integer_type = expression.args.get("is_integer") 1320 1321 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1322 not self.dialect.HEX_START and not binary_function_repr 1323 ): 1324 # Integer representation will be returned if: 1325 # - The read dialect treats the hex value as integer literal but not the write 1326 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1327 return f"{int(this, 16)}" 1328 1329 if not is_integer_type: 1330 # Read dialect treats the hex value as BINARY/BLOB 1331 if binary_function_repr: 1332 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1333 return self.func(binary_function_repr, exp.Literal.string(this)) 1334 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1335 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1336 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1337 1338 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1339 1340 def bytestring_sql(self, expression: exp.ByteString) -> str: 1341 this = self.sql(expression, "this") 1342 if self.dialect.BYTE_START: 1343 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1344 return this 1345 1346 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1347 this = self.sql(expression, "this") 1348 escape = expression.args.get("escape") 1349 1350 if self.dialect.UNICODE_START: 1351 escape_substitute = r"\\\1" 1352 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1353 else: 1354 escape_substitute = r"\\u\1" 1355 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1356 1357 if escape: 1358 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1359 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1360 else: 1361 escape_pattern = ESCAPED_UNICODE_RE 1362 escape_sql = "" 1363 1364 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1365 this = escape_pattern.sub(escape_substitute, this) 1366 1367 return f"{left_quote}{this}{right_quote}{escape_sql}" 1368 1369 def rawstring_sql(self, expression: exp.RawString) -> str: 1370 string = expression.this 1371 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1372 string = string.replace("\\", "\\\\") 1373 1374 string = self.escape_str(string, escape_backslash=False) 1375 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1376 1377 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1378 this = self.sql(expression, "this") 1379 specifier = self.sql(expression, "expression") 1380 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1381 return f"{this}{specifier}" 1382 1383 def datatype_sql(self, expression: exp.DataType) -> str: 1384 nested = "" 1385 values = "" 1386 interior = self.expressions(expression, flat=True) 1387 1388 type_value = expression.this 1389 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1390 type_sql = self.sql(expression, "kind") 1391 else: 1392 type_sql = ( 1393 self.TYPE_MAPPING.get(type_value, type_value.value) 1394 if isinstance(type_value, exp.DataType.Type) 1395 else type_value 1396 ) 1397 1398 if interior: 1399 if expression.args.get("nested"): 1400 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1401 if expression.args.get("values") is not None: 1402 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1403 values = self.expressions(expression, key="values", flat=True) 1404 values = f"{delimiters[0]}{values}{delimiters[1]}" 1405 elif type_value == exp.DataType.Type.INTERVAL: 1406 nested = f" {interior}" 1407 else: 1408 nested = f"({interior})" 1409 1410 type_sql = f"{type_sql}{nested}{values}" 1411 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1412 exp.DataType.Type.TIMETZ, 1413 exp.DataType.Type.TIMESTAMPTZ, 1414 ): 1415 type_sql = f"{type_sql} WITH TIME ZONE" 1416 1417 return type_sql 1418 1419 def directory_sql(self, expression: exp.Directory) -> str: 1420 local = "LOCAL " if expression.args.get("local") else "" 1421 row_format = self.sql(expression, "row_format") 1422 row_format = f" {row_format}" if row_format else "" 1423 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1424 1425 def delete_sql(self, expression: exp.Delete) -> str: 1426 this = self.sql(expression, "this") 1427 this = f" FROM {this}" if this else "" 1428 using = self.sql(expression, "using") 1429 using = f" USING {using}" if using else "" 1430 cluster = self.sql(expression, "cluster") 1431 cluster = f" {cluster}" if cluster else "" 1432 where = self.sql(expression, "where") 1433 returning = self.sql(expression, "returning") 1434 limit = self.sql(expression, "limit") 1435 tables = self.expressions(expression, key="tables") 1436 tables = f" {tables}" if tables else "" 1437 if self.RETURNING_END: 1438 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1439 else: 1440 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1441 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1442 1443 def drop_sql(self, expression: exp.Drop) -> str: 1444 this = self.sql(expression, "this") 1445 expressions = self.expressions(expression, flat=True) 1446 expressions = f" ({expressions})" if expressions else "" 1447 kind = expression.args["kind"] 1448 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1449 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1450 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1451 on_cluster = self.sql(expression, "cluster") 1452 on_cluster = f" {on_cluster}" if on_cluster else "" 1453 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1454 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1455 cascade = " CASCADE" if expression.args.get("cascade") else "" 1456 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1457 purge = " PURGE" if expression.args.get("purge") else "" 1458 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1459 1460 def set_operation(self, expression: exp.SetOperation) -> str: 1461 op_type = type(expression) 1462 op_name = op_type.key.upper() 1463 1464 distinct = expression.args.get("distinct") 1465 if ( 1466 distinct is False 1467 and op_type in (exp.Except, exp.Intersect) 1468 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1469 ): 1470 self.unsupported(f"{op_name} ALL is not supported") 1471 1472 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1473 1474 if distinct is None: 1475 distinct = default_distinct 1476 if distinct is None: 1477 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1478 1479 if distinct is default_distinct: 1480 distinct_or_all = "" 1481 else: 1482 distinct_or_all = " DISTINCT" if distinct else " ALL" 1483 1484 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 1485 side_kind = f"{side_kind} " if side_kind else "" 1486 1487 by_name = " BY NAME" if expression.args.get("by_name") else "" 1488 on = self.expressions(expression, key="on", flat=True) 1489 on = f" ON ({on})" if on else "" 1490 1491 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}" 1492 1493 def set_operations(self, expression: exp.SetOperation) -> str: 1494 if not self.SET_OP_MODIFIERS: 1495 limit = expression.args.get("limit") 1496 order = expression.args.get("order") 1497 1498 if limit or order: 1499 select = self._move_ctes_to_top_level( 1500 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1501 ) 1502 1503 if limit: 1504 select = select.limit(limit.pop(), copy=False) 1505 if order: 1506 select = select.order_by(order.pop(), copy=False) 1507 return self.sql(select) 1508 1509 sqls: t.List[str] = [] 1510 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1511 1512 while stack: 1513 node = stack.pop() 1514 1515 if isinstance(node, exp.SetOperation): 1516 stack.append(node.expression) 1517 stack.append( 1518 self.maybe_comment( 1519 self.set_operation(node), comments=node.comments, separated=True 1520 ) 1521 ) 1522 stack.append(node.this) 1523 else: 1524 sqls.append(self.sql(node)) 1525 1526 this = self.sep().join(sqls) 1527 this = self.query_modifiers(expression, this) 1528 return self.prepend_ctes(expression, this) 1529 1530 def fetch_sql(self, expression: exp.Fetch) -> str: 1531 direction = expression.args.get("direction") 1532 direction = f" {direction}" if direction else "" 1533 count = self.sql(expression, "count") 1534 count = f" {count}" if count else "" 1535 limit_options = self.sql(expression, "limit_options") 1536 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1537 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1538 1539 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1540 percent = " PERCENT" if expression.args.get("percent") else "" 1541 rows = " ROWS" if expression.args.get("rows") else "" 1542 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1543 if not with_ties and rows: 1544 with_ties = " ONLY" 1545 return f"{percent}{rows}{with_ties}" 1546 1547 def filter_sql(self, expression: exp.Filter) -> str: 1548 if self.AGGREGATE_FILTER_SUPPORTED: 1549 this = self.sql(expression, "this") 1550 where = self.sql(expression, "expression").strip() 1551 return f"{this} FILTER({where})" 1552 1553 agg = expression.this 1554 agg_arg = agg.this 1555 cond = expression.expression.this 1556 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1557 return self.sql(agg) 1558 1559 def hint_sql(self, expression: exp.Hint) -> str: 1560 if not self.QUERY_HINTS: 1561 self.unsupported("Hints are not supported") 1562 return "" 1563 1564 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1565 1566 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1567 using = self.sql(expression, "using") 1568 using = f" USING {using}" if using else "" 1569 columns = self.expressions(expression, key="columns", flat=True) 1570 columns = f"({columns})" if columns else "" 1571 partition_by = self.expressions(expression, key="partition_by", flat=True) 1572 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1573 where = self.sql(expression, "where") 1574 include = self.expressions(expression, key="include", flat=True) 1575 if include: 1576 include = f" INCLUDE ({include})" 1577 with_storage = self.expressions(expression, key="with_storage", flat=True) 1578 with_storage = f" WITH ({with_storage})" if with_storage else "" 1579 tablespace = self.sql(expression, "tablespace") 1580 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1581 on = self.sql(expression, "on") 1582 on = f" ON {on}" if on else "" 1583 1584 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1585 1586 def index_sql(self, expression: exp.Index) -> str: 1587 unique = "UNIQUE " if expression.args.get("unique") else "" 1588 primary = "PRIMARY " if expression.args.get("primary") else "" 1589 amp = "AMP " if expression.args.get("amp") else "" 1590 name = self.sql(expression, "this") 1591 name = f"{name} " if name else "" 1592 table = self.sql(expression, "table") 1593 table = f"{self.INDEX_ON} {table}" if table else "" 1594 1595 index = "INDEX " if not table else "" 1596 1597 params = self.sql(expression, "params") 1598 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1599 1600 def identifier_sql(self, expression: exp.Identifier) -> str: 1601 text = expression.name 1602 lower = text.lower() 1603 text = lower if self.normalize and not expression.quoted else text 1604 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1605 if ( 1606 expression.quoted 1607 or self.dialect.can_identify(text, self.identify) 1608 or lower in self.RESERVED_KEYWORDS 1609 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1610 ): 1611 text = f"{self._identifier_start}{text}{self._identifier_end}" 1612 return text 1613 1614 def hex_sql(self, expression: exp.Hex) -> str: 1615 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1616 if self.dialect.HEX_LOWERCASE: 1617 text = self.func("LOWER", text) 1618 1619 return text 1620 1621 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1622 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1623 if not self.dialect.HEX_LOWERCASE: 1624 text = self.func("LOWER", text) 1625 return text 1626 1627 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1628 input_format = self.sql(expression, "input_format") 1629 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1630 output_format = self.sql(expression, "output_format") 1631 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1632 return self.sep().join((input_format, output_format)) 1633 1634 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1635 string = self.sql(exp.Literal.string(expression.name)) 1636 return f"{prefix}{string}" 1637 1638 def partition_sql(self, expression: exp.Partition) -> str: 1639 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1640 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1641 1642 def properties_sql(self, expression: exp.Properties) -> str: 1643 root_properties = [] 1644 with_properties = [] 1645 1646 for p in expression.expressions: 1647 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1648 if p_loc == exp.Properties.Location.POST_WITH: 1649 with_properties.append(p) 1650 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1651 root_properties.append(p) 1652 1653 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1654 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1655 1656 if root_props and with_props and not self.pretty: 1657 with_props = " " + with_props 1658 1659 return root_props + with_props 1660 1661 def root_properties(self, properties: exp.Properties) -> str: 1662 if properties.expressions: 1663 return self.expressions(properties, indent=False, sep=" ") 1664 return "" 1665 1666 def properties( 1667 self, 1668 properties: exp.Properties, 1669 prefix: str = "", 1670 sep: str = ", ", 1671 suffix: str = "", 1672 wrapped: bool = True, 1673 ) -> str: 1674 if properties.expressions: 1675 expressions = self.expressions(properties, sep=sep, indent=False) 1676 if expressions: 1677 expressions = self.wrap(expressions) if wrapped else expressions 1678 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1679 return "" 1680 1681 def with_properties(self, properties: exp.Properties) -> str: 1682 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1683 1684 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1685 properties_locs = defaultdict(list) 1686 for p in properties.expressions: 1687 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1688 if p_loc != exp.Properties.Location.UNSUPPORTED: 1689 properties_locs[p_loc].append(p) 1690 else: 1691 self.unsupported(f"Unsupported property {p.key}") 1692 1693 return properties_locs 1694 1695 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1696 if isinstance(expression.this, exp.Dot): 1697 return self.sql(expression, "this") 1698 return f"'{expression.name}'" if string_key else expression.name 1699 1700 def property_sql(self, expression: exp.Property) -> str: 1701 property_cls = expression.__class__ 1702 if property_cls == exp.Property: 1703 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1704 1705 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1706 if not property_name: 1707 self.unsupported(f"Unsupported property {expression.key}") 1708 1709 return f"{property_name}={self.sql(expression, 'this')}" 1710 1711 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1712 if self.SUPPORTS_CREATE_TABLE_LIKE: 1713 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1714 options = f" {options}" if options else "" 1715 1716 like = f"LIKE {self.sql(expression, 'this')}{options}" 1717 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1718 like = f"({like})" 1719 1720 return like 1721 1722 if expression.expressions: 1723 self.unsupported("Transpilation of LIKE property options is unsupported") 1724 1725 select = exp.select("*").from_(expression.this).limit(0) 1726 return f"AS {self.sql(select)}" 1727 1728 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1729 no = "NO " if expression.args.get("no") else "" 1730 protection = " PROTECTION" if expression.args.get("protection") else "" 1731 return f"{no}FALLBACK{protection}" 1732 1733 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1734 no = "NO " if expression.args.get("no") else "" 1735 local = expression.args.get("local") 1736 local = f"{local} " if local else "" 1737 dual = "DUAL " if expression.args.get("dual") else "" 1738 before = "BEFORE " if expression.args.get("before") else "" 1739 after = "AFTER " if expression.args.get("after") else "" 1740 return f"{no}{local}{dual}{before}{after}JOURNAL" 1741 1742 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1743 freespace = self.sql(expression, "this") 1744 percent = " PERCENT" if expression.args.get("percent") else "" 1745 return f"FREESPACE={freespace}{percent}" 1746 1747 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1748 if expression.args.get("default"): 1749 property = "DEFAULT" 1750 elif expression.args.get("on"): 1751 property = "ON" 1752 else: 1753 property = "OFF" 1754 return f"CHECKSUM={property}" 1755 1756 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1757 if expression.args.get("no"): 1758 return "NO MERGEBLOCKRATIO" 1759 if expression.args.get("default"): 1760 return "DEFAULT MERGEBLOCKRATIO" 1761 1762 percent = " PERCENT" if expression.args.get("percent") else "" 1763 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1764 1765 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1766 default = expression.args.get("default") 1767 minimum = expression.args.get("minimum") 1768 maximum = expression.args.get("maximum") 1769 if default or minimum or maximum: 1770 if default: 1771 prop = "DEFAULT" 1772 elif minimum: 1773 prop = "MINIMUM" 1774 else: 1775 prop = "MAXIMUM" 1776 return f"{prop} DATABLOCKSIZE" 1777 units = expression.args.get("units") 1778 units = f" {units}" if units else "" 1779 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1780 1781 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1782 autotemp = expression.args.get("autotemp") 1783 always = expression.args.get("always") 1784 default = expression.args.get("default") 1785 manual = expression.args.get("manual") 1786 never = expression.args.get("never") 1787 1788 if autotemp is not None: 1789 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1790 elif always: 1791 prop = "ALWAYS" 1792 elif default: 1793 prop = "DEFAULT" 1794 elif manual: 1795 prop = "MANUAL" 1796 elif never: 1797 prop = "NEVER" 1798 return f"BLOCKCOMPRESSION={prop}" 1799 1800 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1801 no = expression.args.get("no") 1802 no = " NO" if no else "" 1803 concurrent = expression.args.get("concurrent") 1804 concurrent = " CONCURRENT" if concurrent else "" 1805 target = self.sql(expression, "target") 1806 target = f" {target}" if target else "" 1807 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1808 1809 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1810 if isinstance(expression.this, list): 1811 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1812 if expression.this: 1813 modulus = self.sql(expression, "this") 1814 remainder = self.sql(expression, "expression") 1815 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1816 1817 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1818 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1819 return f"FROM ({from_expressions}) TO ({to_expressions})" 1820 1821 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1822 this = self.sql(expression, "this") 1823 1824 for_values_or_default = expression.expression 1825 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1826 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1827 else: 1828 for_values_or_default = " DEFAULT" 1829 1830 return f"PARTITION OF {this}{for_values_or_default}" 1831 1832 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1833 kind = expression.args.get("kind") 1834 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1835 for_or_in = expression.args.get("for_or_in") 1836 for_or_in = f" {for_or_in}" if for_or_in else "" 1837 lock_type = expression.args.get("lock_type") 1838 override = " OVERRIDE" if expression.args.get("override") else "" 1839 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1840 1841 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1842 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1843 statistics = expression.args.get("statistics") 1844 statistics_sql = "" 1845 if statistics is not None: 1846 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1847 return f"{data_sql}{statistics_sql}" 1848 1849 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1850 this = self.sql(expression, "this") 1851 this = f"HISTORY_TABLE={this}" if this else "" 1852 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1853 data_consistency = ( 1854 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1855 ) 1856 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1857 retention_period = ( 1858 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1859 ) 1860 1861 if this: 1862 on_sql = self.func("ON", this, data_consistency, retention_period) 1863 else: 1864 on_sql = "ON" if expression.args.get("on") else "OFF" 1865 1866 sql = f"SYSTEM_VERSIONING={on_sql}" 1867 1868 return f"WITH({sql})" if expression.args.get("with") else sql 1869 1870 def insert_sql(self, expression: exp.Insert) -> str: 1871 hint = self.sql(expression, "hint") 1872 overwrite = expression.args.get("overwrite") 1873 1874 if isinstance(expression.this, exp.Directory): 1875 this = " OVERWRITE" if overwrite else " INTO" 1876 else: 1877 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1878 1879 stored = self.sql(expression, "stored") 1880 stored = f" {stored}" if stored else "" 1881 alternative = expression.args.get("alternative") 1882 alternative = f" OR {alternative}" if alternative else "" 1883 ignore = " IGNORE" if expression.args.get("ignore") else "" 1884 is_function = expression.args.get("is_function") 1885 if is_function: 1886 this = f"{this} FUNCTION" 1887 this = f"{this} {self.sql(expression, 'this')}" 1888 1889 exists = " IF EXISTS" if expression.args.get("exists") else "" 1890 where = self.sql(expression, "where") 1891 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1892 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1893 on_conflict = self.sql(expression, "conflict") 1894 on_conflict = f" {on_conflict}" if on_conflict else "" 1895 by_name = " BY NAME" if expression.args.get("by_name") else "" 1896 returning = self.sql(expression, "returning") 1897 1898 if self.RETURNING_END: 1899 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1900 else: 1901 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1902 1903 partition_by = self.sql(expression, "partition") 1904 partition_by = f" {partition_by}" if partition_by else "" 1905 settings = self.sql(expression, "settings") 1906 settings = f" {settings}" if settings else "" 1907 1908 source = self.sql(expression, "source") 1909 source = f"TABLE {source}" if source else "" 1910 1911 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1912 return self.prepend_ctes(expression, sql) 1913 1914 def introducer_sql(self, expression: exp.Introducer) -> str: 1915 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1916 1917 def kill_sql(self, expression: exp.Kill) -> str: 1918 kind = self.sql(expression, "kind") 1919 kind = f" {kind}" if kind else "" 1920 this = self.sql(expression, "this") 1921 this = f" {this}" if this else "" 1922 return f"KILL{kind}{this}" 1923 1924 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1925 return expression.name 1926 1927 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1928 return expression.name 1929 1930 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1931 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1932 1933 constraint = self.sql(expression, "constraint") 1934 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1935 1936 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1937 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1938 action = self.sql(expression, "action") 1939 1940 expressions = self.expressions(expression, flat=True) 1941 if expressions: 1942 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1943 expressions = f" {set_keyword}{expressions}" 1944 1945 where = self.sql(expression, "where") 1946 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1947 1948 def returning_sql(self, expression: exp.Returning) -> str: 1949 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1950 1951 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1952 fields = self.sql(expression, "fields") 1953 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1954 escaped = self.sql(expression, "escaped") 1955 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1956 items = self.sql(expression, "collection_items") 1957 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1958 keys = self.sql(expression, "map_keys") 1959 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1960 lines = self.sql(expression, "lines") 1961 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1962 null = self.sql(expression, "null") 1963 null = f" NULL DEFINED AS {null}" if null else "" 1964 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1965 1966 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1967 return f"WITH ({self.expressions(expression, flat=True)})" 1968 1969 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1970 this = f"{self.sql(expression, 'this')} INDEX" 1971 target = self.sql(expression, "target") 1972 target = f" FOR {target}" if target else "" 1973 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1974 1975 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1976 this = self.sql(expression, "this") 1977 kind = self.sql(expression, "kind") 1978 expr = self.sql(expression, "expression") 1979 return f"{this} ({kind} => {expr})" 1980 1981 def table_parts(self, expression: exp.Table) -> str: 1982 return ".".join( 1983 self.sql(part) 1984 for part in ( 1985 expression.args.get("catalog"), 1986 expression.args.get("db"), 1987 expression.args.get("this"), 1988 ) 1989 if part is not None 1990 ) 1991 1992 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1993 table = self.table_parts(expression) 1994 only = "ONLY " if expression.args.get("only") else "" 1995 partition = self.sql(expression, "partition") 1996 partition = f" {partition}" if partition else "" 1997 version = self.sql(expression, "version") 1998 version = f" {version}" if version else "" 1999 alias = self.sql(expression, "alias") 2000 alias = f"{sep}{alias}" if alias else "" 2001 2002 sample = self.sql(expression, "sample") 2003 if self.dialect.ALIAS_POST_TABLESAMPLE: 2004 sample_pre_alias = sample 2005 sample_post_alias = "" 2006 else: 2007 sample_pre_alias = "" 2008 sample_post_alias = sample 2009 2010 hints = self.expressions(expression, key="hints", sep=" ") 2011 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2012 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2013 joins = self.indent( 2014 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2015 ) 2016 laterals = self.expressions(expression, key="laterals", sep="") 2017 2018 file_format = self.sql(expression, "format") 2019 if file_format: 2020 pattern = self.sql(expression, "pattern") 2021 pattern = f", PATTERN => {pattern}" if pattern else "" 2022 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2023 2024 ordinality = expression.args.get("ordinality") or "" 2025 if ordinality: 2026 ordinality = f" WITH ORDINALITY{alias}" 2027 alias = "" 2028 2029 when = self.sql(expression, "when") 2030 if when: 2031 table = f"{table} {when}" 2032 2033 changes = self.sql(expression, "changes") 2034 changes = f" {changes}" if changes else "" 2035 2036 rows_from = self.expressions(expression, key="rows_from") 2037 if rows_from: 2038 table = f"ROWS FROM {self.wrap(rows_from)}" 2039 2040 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2041 2042 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2043 table = self.func("TABLE", expression.this) 2044 alias = self.sql(expression, "alias") 2045 alias = f" AS {alias}" if alias else "" 2046 sample = self.sql(expression, "sample") 2047 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2048 joins = self.indent( 2049 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2050 ) 2051 return f"{table}{alias}{pivots}{sample}{joins}" 2052 2053 def tablesample_sql( 2054 self, 2055 expression: exp.TableSample, 2056 tablesample_keyword: t.Optional[str] = None, 2057 ) -> str: 2058 method = self.sql(expression, "method") 2059 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2060 numerator = self.sql(expression, "bucket_numerator") 2061 denominator = self.sql(expression, "bucket_denominator") 2062 field = self.sql(expression, "bucket_field") 2063 field = f" ON {field}" if field else "" 2064 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2065 seed = self.sql(expression, "seed") 2066 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2067 2068 size = self.sql(expression, "size") 2069 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2070 size = f"{size} ROWS" 2071 2072 percent = self.sql(expression, "percent") 2073 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2074 percent = f"{percent} PERCENT" 2075 2076 expr = f"{bucket}{percent}{size}" 2077 if self.TABLESAMPLE_REQUIRES_PARENS: 2078 expr = f"({expr})" 2079 2080 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2081 2082 def pivot_sql(self, expression: exp.Pivot) -> str: 2083 expressions = self.expressions(expression, flat=True) 2084 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2085 2086 group = self.sql(expression, "group") 2087 2088 if expression.this: 2089 this = self.sql(expression, "this") 2090 if not expressions: 2091 return f"UNPIVOT {this}" 2092 2093 on = f"{self.seg('ON')} {expressions}" 2094 into = self.sql(expression, "into") 2095 into = f"{self.seg('INTO')} {into}" if into else "" 2096 using = self.expressions(expression, key="using", flat=True) 2097 using = f"{self.seg('USING')} {using}" if using else "" 2098 return f"{direction} {this}{on}{into}{using}{group}" 2099 2100 alias = self.sql(expression, "alias") 2101 alias = f" AS {alias}" if alias else "" 2102 2103 fields = self.expressions( 2104 expression, 2105 "fields", 2106 sep=" ", 2107 dynamic=True, 2108 new_line=True, 2109 skip_first=True, 2110 skip_last=True, 2111 ) 2112 2113 include_nulls = expression.args.get("include_nulls") 2114 if include_nulls is not None: 2115 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2116 else: 2117 nulls = "" 2118 2119 default_on_null = self.sql(expression, "default_on_null") 2120 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2121 return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}" 2122 2123 def version_sql(self, expression: exp.Version) -> str: 2124 this = f"FOR {expression.name}" 2125 kind = expression.text("kind") 2126 expr = self.sql(expression, "expression") 2127 return f"{this} {kind} {expr}" 2128 2129 def tuple_sql(self, expression: exp.Tuple) -> str: 2130 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2131 2132 def update_sql(self, expression: exp.Update) -> str: 2133 this = self.sql(expression, "this") 2134 set_sql = self.expressions(expression, flat=True) 2135 from_sql = self.sql(expression, "from") 2136 where_sql = self.sql(expression, "where") 2137 returning = self.sql(expression, "returning") 2138 order = self.sql(expression, "order") 2139 limit = self.sql(expression, "limit") 2140 if self.RETURNING_END: 2141 expression_sql = f"{from_sql}{where_sql}{returning}" 2142 else: 2143 expression_sql = f"{returning}{from_sql}{where_sql}" 2144 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2145 return self.prepend_ctes(expression, sql) 2146 2147 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2148 values_as_table = values_as_table and self.VALUES_AS_TABLE 2149 2150 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2151 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2152 args = self.expressions(expression) 2153 alias = self.sql(expression, "alias") 2154 values = f"VALUES{self.seg('')}{args}" 2155 values = ( 2156 f"({values})" 2157 if self.WRAP_DERIVED_VALUES 2158 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2159 else values 2160 ) 2161 return f"{values} AS {alias}" if alias else values 2162 2163 # Converts `VALUES...` expression into a series of select unions. 2164 alias_node = expression.args.get("alias") 2165 column_names = alias_node and alias_node.columns 2166 2167 selects: t.List[exp.Query] = [] 2168 2169 for i, tup in enumerate(expression.expressions): 2170 row = tup.expressions 2171 2172 if i == 0 and column_names: 2173 row = [ 2174 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2175 ] 2176 2177 selects.append(exp.Select(expressions=row)) 2178 2179 if self.pretty: 2180 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2181 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2182 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2183 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2184 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2185 2186 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2187 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2188 return f"({unions}){alias}" 2189 2190 def var_sql(self, expression: exp.Var) -> str: 2191 return self.sql(expression, "this") 2192 2193 @unsupported_args("expressions") 2194 def into_sql(self, expression: exp.Into) -> str: 2195 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2196 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2197 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2198 2199 def from_sql(self, expression: exp.From) -> str: 2200 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2201 2202 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2203 grouping_sets = self.expressions(expression, indent=False) 2204 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2205 2206 def rollup_sql(self, expression: exp.Rollup) -> str: 2207 expressions = self.expressions(expression, indent=False) 2208 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2209 2210 def cube_sql(self, expression: exp.Cube) -> str: 2211 expressions = self.expressions(expression, indent=False) 2212 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2213 2214 def group_sql(self, expression: exp.Group) -> str: 2215 group_by_all = expression.args.get("all") 2216 if group_by_all is True: 2217 modifier = " ALL" 2218 elif group_by_all is False: 2219 modifier = " DISTINCT" 2220 else: 2221 modifier = "" 2222 2223 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2224 2225 grouping_sets = self.expressions(expression, key="grouping_sets") 2226 cube = self.expressions(expression, key="cube") 2227 rollup = self.expressions(expression, key="rollup") 2228 2229 groupings = csv( 2230 self.seg(grouping_sets) if grouping_sets else "", 2231 self.seg(cube) if cube else "", 2232 self.seg(rollup) if rollup else "", 2233 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2234 sep=self.GROUPINGS_SEP, 2235 ) 2236 2237 if ( 2238 expression.expressions 2239 and groupings 2240 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2241 ): 2242 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2243 2244 return f"{group_by}{groupings}" 2245 2246 def having_sql(self, expression: exp.Having) -> str: 2247 this = self.indent(self.sql(expression, "this")) 2248 return f"{self.seg('HAVING')}{self.sep()}{this}" 2249 2250 def connect_sql(self, expression: exp.Connect) -> str: 2251 start = self.sql(expression, "start") 2252 start = self.seg(f"START WITH {start}") if start else "" 2253 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2254 connect = self.sql(expression, "connect") 2255 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2256 return start + connect 2257 2258 def prior_sql(self, expression: exp.Prior) -> str: 2259 return f"PRIOR {self.sql(expression, 'this')}" 2260 2261 def join_sql(self, expression: exp.Join) -> str: 2262 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2263 side = None 2264 else: 2265 side = expression.side 2266 2267 op_sql = " ".join( 2268 op 2269 for op in ( 2270 expression.method, 2271 "GLOBAL" if expression.args.get("global") else None, 2272 side, 2273 expression.kind, 2274 expression.hint if self.JOIN_HINTS else None, 2275 ) 2276 if op 2277 ) 2278 match_cond = self.sql(expression, "match_condition") 2279 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2280 on_sql = self.sql(expression, "on") 2281 using = expression.args.get("using") 2282 2283 if not on_sql and using: 2284 on_sql = csv(*(self.sql(column) for column in using)) 2285 2286 this = expression.this 2287 this_sql = self.sql(this) 2288 2289 exprs = self.expressions(expression) 2290 if exprs: 2291 this_sql = f"{this_sql},{self.seg(exprs)}" 2292 2293 if on_sql: 2294 on_sql = self.indent(on_sql, skip_first=True) 2295 space = self.seg(" " * self.pad) if self.pretty else " " 2296 if using: 2297 on_sql = f"{space}USING ({on_sql})" 2298 else: 2299 on_sql = f"{space}ON {on_sql}" 2300 elif not op_sql: 2301 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2302 return f" {this_sql}" 2303 2304 return f", {this_sql}" 2305 2306 if op_sql != "STRAIGHT_JOIN": 2307 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2308 2309 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2310 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}" 2311 2312 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2313 args = self.expressions(expression, flat=True) 2314 args = f"({args})" if len(args.split(",")) > 1 else args 2315 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2316 2317 def lateral_op(self, expression: exp.Lateral) -> str: 2318 cross_apply = expression.args.get("cross_apply") 2319 2320 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2321 if cross_apply is True: 2322 op = "INNER JOIN " 2323 elif cross_apply is False: 2324 op = "LEFT JOIN " 2325 else: 2326 op = "" 2327 2328 return f"{op}LATERAL" 2329 2330 def lateral_sql(self, expression: exp.Lateral) -> str: 2331 this = self.sql(expression, "this") 2332 2333 if expression.args.get("view"): 2334 alias = expression.args["alias"] 2335 columns = self.expressions(alias, key="columns", flat=True) 2336 table = f" {alias.name}" if alias.name else "" 2337 columns = f" AS {columns}" if columns else "" 2338 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2339 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2340 2341 alias = self.sql(expression, "alias") 2342 alias = f" AS {alias}" if alias else "" 2343 2344 ordinality = expression.args.get("ordinality") or "" 2345 if ordinality: 2346 ordinality = f" WITH ORDINALITY{alias}" 2347 alias = "" 2348 2349 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}" 2350 2351 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2352 this = self.sql(expression, "this") 2353 2354 args = [ 2355 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2356 for e in (expression.args.get(k) for k in ("offset", "expression")) 2357 if e 2358 ] 2359 2360 args_sql = ", ".join(self.sql(e) for e in args) 2361 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2362 expressions = self.expressions(expression, flat=True) 2363 limit_options = self.sql(expression, "limit_options") 2364 expressions = f" BY {expressions}" if expressions else "" 2365 2366 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2367 2368 def offset_sql(self, expression: exp.Offset) -> str: 2369 this = self.sql(expression, "this") 2370 value = expression.expression 2371 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2372 expressions = self.expressions(expression, flat=True) 2373 expressions = f" BY {expressions}" if expressions else "" 2374 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2375 2376 def setitem_sql(self, expression: exp.SetItem) -> str: 2377 kind = self.sql(expression, "kind") 2378 kind = f"{kind} " if kind else "" 2379 this = self.sql(expression, "this") 2380 expressions = self.expressions(expression) 2381 collate = self.sql(expression, "collate") 2382 collate = f" COLLATE {collate}" if collate else "" 2383 global_ = "GLOBAL " if expression.args.get("global") else "" 2384 return f"{global_}{kind}{this}{expressions}{collate}" 2385 2386 def set_sql(self, expression: exp.Set) -> str: 2387 expressions = f" {self.expressions(expression, flat=True)}" 2388 tag = " TAG" if expression.args.get("tag") else "" 2389 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2390 2391 def pragma_sql(self, expression: exp.Pragma) -> str: 2392 return f"PRAGMA {self.sql(expression, 'this')}" 2393 2394 def lock_sql(self, expression: exp.Lock) -> str: 2395 if not self.LOCKING_READS_SUPPORTED: 2396 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2397 return "" 2398 2399 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2400 expressions = self.expressions(expression, flat=True) 2401 expressions = f" OF {expressions}" if expressions else "" 2402 wait = expression.args.get("wait") 2403 2404 if wait is not None: 2405 if isinstance(wait, exp.Literal): 2406 wait = f" WAIT {self.sql(wait)}" 2407 else: 2408 wait = " NOWAIT" if wait else " SKIP LOCKED" 2409 2410 return f"{lock_type}{expressions}{wait or ''}" 2411 2412 def literal_sql(self, expression: exp.Literal) -> str: 2413 text = expression.this or "" 2414 if expression.is_string: 2415 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2416 return text 2417 2418 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2419 if self.dialect.ESCAPED_SEQUENCES: 2420 to_escaped = self.dialect.ESCAPED_SEQUENCES 2421 text = "".join( 2422 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2423 ) 2424 2425 return self._replace_line_breaks(text).replace( 2426 self.dialect.QUOTE_END, self._escaped_quote_end 2427 ) 2428 2429 def loaddata_sql(self, expression: exp.LoadData) -> str: 2430 local = " LOCAL" if expression.args.get("local") else "" 2431 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2432 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2433 this = f" INTO TABLE {self.sql(expression, 'this')}" 2434 partition = self.sql(expression, "partition") 2435 partition = f" {partition}" if partition else "" 2436 input_format = self.sql(expression, "input_format") 2437 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2438 serde = self.sql(expression, "serde") 2439 serde = f" SERDE {serde}" if serde else "" 2440 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2441 2442 def null_sql(self, *_) -> str: 2443 return "NULL" 2444 2445 def boolean_sql(self, expression: exp.Boolean) -> str: 2446 return "TRUE" if expression.this else "FALSE" 2447 2448 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2449 this = self.sql(expression, "this") 2450 this = f"{this} " if this else this 2451 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2452 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2453 2454 def withfill_sql(self, expression: exp.WithFill) -> str: 2455 from_sql = self.sql(expression, "from") 2456 from_sql = f" FROM {from_sql}" if from_sql else "" 2457 to_sql = self.sql(expression, "to") 2458 to_sql = f" TO {to_sql}" if to_sql else "" 2459 step_sql = self.sql(expression, "step") 2460 step_sql = f" STEP {step_sql}" if step_sql else "" 2461 interpolated_values = [ 2462 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2463 if isinstance(e, exp.Alias) 2464 else self.sql(e, "this") 2465 for e in expression.args.get("interpolate") or [] 2466 ] 2467 interpolate = ( 2468 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2469 ) 2470 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2471 2472 def cluster_sql(self, expression: exp.Cluster) -> str: 2473 return self.op_expressions("CLUSTER BY", expression) 2474 2475 def distribute_sql(self, expression: exp.Distribute) -> str: 2476 return self.op_expressions("DISTRIBUTE BY", expression) 2477 2478 def sort_sql(self, expression: exp.Sort) -> str: 2479 return self.op_expressions("SORT BY", expression) 2480 2481 def ordered_sql(self, expression: exp.Ordered) -> str: 2482 desc = expression.args.get("desc") 2483 asc = not desc 2484 2485 nulls_first = expression.args.get("nulls_first") 2486 nulls_last = not nulls_first 2487 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2488 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2489 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2490 2491 this = self.sql(expression, "this") 2492 2493 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2494 nulls_sort_change = "" 2495 if nulls_first and ( 2496 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2497 ): 2498 nulls_sort_change = " NULLS FIRST" 2499 elif ( 2500 nulls_last 2501 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2502 and not nulls_are_last 2503 ): 2504 nulls_sort_change = " NULLS LAST" 2505 2506 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2507 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2508 window = expression.find_ancestor(exp.Window, exp.Select) 2509 if isinstance(window, exp.Window) and window.args.get("spec"): 2510 self.unsupported( 2511 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2512 ) 2513 nulls_sort_change = "" 2514 elif self.NULL_ORDERING_SUPPORTED is False and ( 2515 (asc and nulls_sort_change == " NULLS LAST") 2516 or (desc and nulls_sort_change == " NULLS FIRST") 2517 ): 2518 # BigQuery does not allow these ordering/nulls combinations when used under 2519 # an aggregation func or under a window containing one 2520 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2521 2522 if isinstance(ancestor, exp.Window): 2523 ancestor = ancestor.this 2524 if isinstance(ancestor, exp.AggFunc): 2525 self.unsupported( 2526 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2527 ) 2528 nulls_sort_change = "" 2529 elif self.NULL_ORDERING_SUPPORTED is None: 2530 if expression.this.is_int: 2531 self.unsupported( 2532 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2533 ) 2534 elif not isinstance(expression.this, exp.Rand): 2535 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2536 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2537 nulls_sort_change = "" 2538 2539 with_fill = self.sql(expression, "with_fill") 2540 with_fill = f" {with_fill}" if with_fill else "" 2541 2542 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2543 2544 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2545 window_frame = self.sql(expression, "window_frame") 2546 window_frame = f"{window_frame} " if window_frame else "" 2547 2548 this = self.sql(expression, "this") 2549 2550 return f"{window_frame}{this}" 2551 2552 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2553 partition = self.partition_by_sql(expression) 2554 order = self.sql(expression, "order") 2555 measures = self.expressions(expression, key="measures") 2556 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2557 rows = self.sql(expression, "rows") 2558 rows = self.seg(rows) if rows else "" 2559 after = self.sql(expression, "after") 2560 after = self.seg(after) if after else "" 2561 pattern = self.sql(expression, "pattern") 2562 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2563 definition_sqls = [ 2564 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2565 for definition in expression.args.get("define", []) 2566 ] 2567 definitions = self.expressions(sqls=definition_sqls) 2568 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2569 body = "".join( 2570 ( 2571 partition, 2572 order, 2573 measures, 2574 rows, 2575 after, 2576 pattern, 2577 define, 2578 ) 2579 ) 2580 alias = self.sql(expression, "alias") 2581 alias = f" {alias}" if alias else "" 2582 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2583 2584 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2585 limit = expression.args.get("limit") 2586 2587 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2588 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2589 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2590 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2591 2592 return csv( 2593 *sqls, 2594 *[self.sql(join) for join in expression.args.get("joins") or []], 2595 self.sql(expression, "match"), 2596 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2597 self.sql(expression, "prewhere"), 2598 self.sql(expression, "where"), 2599 self.sql(expression, "connect"), 2600 self.sql(expression, "group"), 2601 self.sql(expression, "having"), 2602 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2603 self.sql(expression, "order"), 2604 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2605 *self.after_limit_modifiers(expression), 2606 self.options_modifier(expression), 2607 self.for_modifiers(expression), 2608 sep="", 2609 ) 2610 2611 def options_modifier(self, expression: exp.Expression) -> str: 2612 options = self.expressions(expression, key="options") 2613 return f" {options}" if options else "" 2614 2615 def for_modifiers(self, expression: exp.Expression) -> str: 2616 for_modifiers = self.expressions(expression, key="for") 2617 return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else "" 2618 2619 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2620 self.unsupported("Unsupported query option.") 2621 return "" 2622 2623 def offset_limit_modifiers( 2624 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2625 ) -> t.List[str]: 2626 return [ 2627 self.sql(expression, "offset") if fetch else self.sql(limit), 2628 self.sql(limit) if fetch else self.sql(expression, "offset"), 2629 ] 2630 2631 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2632 locks = self.expressions(expression, key="locks", sep=" ") 2633 locks = f" {locks}" if locks else "" 2634 return [locks, self.sql(expression, "sample")] 2635 2636 def select_sql(self, expression: exp.Select) -> str: 2637 into = expression.args.get("into") 2638 if not self.SUPPORTS_SELECT_INTO and into: 2639 into.pop() 2640 2641 hint = self.sql(expression, "hint") 2642 distinct = self.sql(expression, "distinct") 2643 distinct = f" {distinct}" if distinct else "" 2644 kind = self.sql(expression, "kind") 2645 2646 limit = expression.args.get("limit") 2647 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2648 top = self.limit_sql(limit, top=True) 2649 limit.pop() 2650 else: 2651 top = "" 2652 2653 expressions = self.expressions(expression) 2654 2655 if kind: 2656 if kind in self.SELECT_KINDS: 2657 kind = f" AS {kind}" 2658 else: 2659 if kind == "STRUCT": 2660 expressions = self.expressions( 2661 sqls=[ 2662 self.sql( 2663 exp.Struct( 2664 expressions=[ 2665 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2666 if isinstance(e, exp.Alias) 2667 else e 2668 for e in expression.expressions 2669 ] 2670 ) 2671 ) 2672 ] 2673 ) 2674 kind = "" 2675 2676 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2677 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2678 2679 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2680 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2681 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2682 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2683 sql = self.query_modifiers( 2684 expression, 2685 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2686 self.sql(expression, "into", comment=False), 2687 self.sql(expression, "from", comment=False), 2688 ) 2689 2690 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2691 if expression.args.get("with"): 2692 sql = self.maybe_comment(sql, expression) 2693 expression.pop_comments() 2694 2695 sql = self.prepend_ctes(expression, sql) 2696 2697 if not self.SUPPORTS_SELECT_INTO and into: 2698 if into.args.get("temporary"): 2699 table_kind = " TEMPORARY" 2700 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2701 table_kind = " UNLOGGED" 2702 else: 2703 table_kind = "" 2704 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2705 2706 return sql 2707 2708 def schema_sql(self, expression: exp.Schema) -> str: 2709 this = self.sql(expression, "this") 2710 sql = self.schema_columns_sql(expression) 2711 return f"{this} {sql}" if this and sql else this or sql 2712 2713 def schema_columns_sql(self, expression: exp.Schema) -> str: 2714 if expression.expressions: 2715 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2716 return "" 2717 2718 def star_sql(self, expression: exp.Star) -> str: 2719 except_ = self.expressions(expression, key="except", flat=True) 2720 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2721 replace = self.expressions(expression, key="replace", flat=True) 2722 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2723 rename = self.expressions(expression, key="rename", flat=True) 2724 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2725 return f"*{except_}{replace}{rename}" 2726 2727 def parameter_sql(self, expression: exp.Parameter) -> str: 2728 this = self.sql(expression, "this") 2729 return f"{self.PARAMETER_TOKEN}{this}" 2730 2731 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2732 this = self.sql(expression, "this") 2733 kind = expression.text("kind") 2734 if kind: 2735 kind = f"{kind}." 2736 return f"@@{kind}{this}" 2737 2738 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2739 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2740 2741 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2742 alias = self.sql(expression, "alias") 2743 alias = f"{sep}{alias}" if alias else "" 2744 sample = self.sql(expression, "sample") 2745 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2746 alias = f"{sample}{alias}" 2747 2748 # Set to None so it's not generated again by self.query_modifiers() 2749 expression.set("sample", None) 2750 2751 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2752 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2753 return self.prepend_ctes(expression, sql) 2754 2755 def qualify_sql(self, expression: exp.Qualify) -> str: 2756 this = self.indent(self.sql(expression, "this")) 2757 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2758 2759 def unnest_sql(self, expression: exp.Unnest) -> str: 2760 args = self.expressions(expression, flat=True) 2761 2762 alias = expression.args.get("alias") 2763 offset = expression.args.get("offset") 2764 2765 if self.UNNEST_WITH_ORDINALITY: 2766 if alias and isinstance(offset, exp.Expression): 2767 alias.append("columns", offset) 2768 2769 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2770 columns = alias.columns 2771 alias = self.sql(columns[0]) if columns else "" 2772 else: 2773 alias = self.sql(alias) 2774 2775 alias = f" AS {alias}" if alias else alias 2776 if self.UNNEST_WITH_ORDINALITY: 2777 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2778 else: 2779 if isinstance(offset, exp.Expression): 2780 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2781 elif offset: 2782 suffix = f"{alias} WITH OFFSET" 2783 else: 2784 suffix = alias 2785 2786 return f"UNNEST({args}){suffix}" 2787 2788 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2789 return "" 2790 2791 def where_sql(self, expression: exp.Where) -> str: 2792 this = self.indent(self.sql(expression, "this")) 2793 return f"{self.seg('WHERE')}{self.sep()}{this}" 2794 2795 def window_sql(self, expression: exp.Window) -> str: 2796 this = self.sql(expression, "this") 2797 partition = self.partition_by_sql(expression) 2798 order = expression.args.get("order") 2799 order = self.order_sql(order, flat=True) if order else "" 2800 spec = self.sql(expression, "spec") 2801 alias = self.sql(expression, "alias") 2802 over = self.sql(expression, "over") or "OVER" 2803 2804 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2805 2806 first = expression.args.get("first") 2807 if first is None: 2808 first = "" 2809 else: 2810 first = "FIRST" if first else "LAST" 2811 2812 if not partition and not order and not spec and alias: 2813 return f"{this} {alias}" 2814 2815 args = self.format_args( 2816 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 2817 ) 2818 return f"{this} ({args})" 2819 2820 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2821 partition = self.expressions(expression, key="partition_by", flat=True) 2822 return f"PARTITION BY {partition}" if partition else "" 2823 2824 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2825 kind = self.sql(expression, "kind") 2826 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2827 end = ( 2828 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2829 or "CURRENT ROW" 2830 ) 2831 2832 window_spec = f"{kind} BETWEEN {start} AND {end}" 2833 2834 exclude = self.sql(expression, "exclude") 2835 if exclude: 2836 if self.SUPPORTS_WINDOW_EXCLUDE: 2837 window_spec += f" EXCLUDE {exclude}" 2838 else: 2839 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 2840 2841 return window_spec 2842 2843 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2844 this = self.sql(expression, "this") 2845 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2846 return f"{this} WITHIN GROUP ({expression_sql})" 2847 2848 def between_sql(self, expression: exp.Between) -> str: 2849 this = self.sql(expression, "this") 2850 low = self.sql(expression, "low") 2851 high = self.sql(expression, "high") 2852 return f"{this} BETWEEN {low} AND {high}" 2853 2854 def bracket_offset_expressions( 2855 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2856 ) -> t.List[exp.Expression]: 2857 return apply_index_offset( 2858 expression.this, 2859 expression.expressions, 2860 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2861 dialect=self.dialect, 2862 ) 2863 2864 def bracket_sql(self, expression: exp.Bracket) -> str: 2865 expressions = self.bracket_offset_expressions(expression) 2866 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2867 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2868 2869 def all_sql(self, expression: exp.All) -> str: 2870 return f"ALL {self.wrap(expression)}" 2871 2872 def any_sql(self, expression: exp.Any) -> str: 2873 this = self.sql(expression, "this") 2874 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2875 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2876 this = self.wrap(this) 2877 return f"ANY{this}" 2878 return f"ANY {this}" 2879 2880 def exists_sql(self, expression: exp.Exists) -> str: 2881 return f"EXISTS{self.wrap(expression)}" 2882 2883 def case_sql(self, expression: exp.Case) -> str: 2884 this = self.sql(expression, "this") 2885 statements = [f"CASE {this}" if this else "CASE"] 2886 2887 for e in expression.args["ifs"]: 2888 statements.append(f"WHEN {self.sql(e, 'this')}") 2889 statements.append(f"THEN {self.sql(e, 'true')}") 2890 2891 default = self.sql(expression, "default") 2892 2893 if default: 2894 statements.append(f"ELSE {default}") 2895 2896 statements.append("END") 2897 2898 if self.pretty and self.too_wide(statements): 2899 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2900 2901 return " ".join(statements) 2902 2903 def constraint_sql(self, expression: exp.Constraint) -> str: 2904 this = self.sql(expression, "this") 2905 expressions = self.expressions(expression, flat=True) 2906 return f"CONSTRAINT {this} {expressions}" 2907 2908 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2909 order = expression.args.get("order") 2910 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2911 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2912 2913 def extract_sql(self, expression: exp.Extract) -> str: 2914 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2915 expression_sql = self.sql(expression, "expression") 2916 return f"EXTRACT({this} FROM {expression_sql})" 2917 2918 def trim_sql(self, expression: exp.Trim) -> str: 2919 trim_type = self.sql(expression, "position") 2920 2921 if trim_type == "LEADING": 2922 func_name = "LTRIM" 2923 elif trim_type == "TRAILING": 2924 func_name = "RTRIM" 2925 else: 2926 func_name = "TRIM" 2927 2928 return self.func(func_name, expression.this, expression.expression) 2929 2930 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2931 args = expression.expressions 2932 if isinstance(expression, exp.ConcatWs): 2933 args = args[1:] # Skip the delimiter 2934 2935 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2936 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2937 2938 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2939 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2940 2941 return args 2942 2943 def concat_sql(self, expression: exp.Concat) -> str: 2944 expressions = self.convert_concat_args(expression) 2945 2946 # Some dialects don't allow a single-argument CONCAT call 2947 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2948 return self.sql(expressions[0]) 2949 2950 return self.func("CONCAT", *expressions) 2951 2952 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2953 return self.func( 2954 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2955 ) 2956 2957 def check_sql(self, expression: exp.Check) -> str: 2958 this = self.sql(expression, key="this") 2959 return f"CHECK ({this})" 2960 2961 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2962 expressions = self.expressions(expression, flat=True) 2963 expressions = f" ({expressions})" if expressions else "" 2964 reference = self.sql(expression, "reference") 2965 reference = f" {reference}" if reference else "" 2966 delete = self.sql(expression, "delete") 2967 delete = f" ON DELETE {delete}" if delete else "" 2968 update = self.sql(expression, "update") 2969 update = f" ON UPDATE {update}" if update else "" 2970 options = self.expressions(expression, key="options", flat=True, sep=" ") 2971 options = f" {options}" if options else "" 2972 return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}" 2973 2974 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2975 expressions = self.expressions(expression, flat=True) 2976 options = self.expressions(expression, key="options", flat=True, sep=" ") 2977 options = f" {options}" if options else "" 2978 return f"PRIMARY KEY ({expressions}){options}" 2979 2980 def if_sql(self, expression: exp.If) -> str: 2981 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2982 2983 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2984 modifier = expression.args.get("modifier") 2985 modifier = f" {modifier}" if modifier else "" 2986 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2987 2988 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2989 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2990 2991 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2992 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2993 2994 if expression.args.get("escape"): 2995 path = self.escape_str(path) 2996 2997 if self.QUOTE_JSON_PATH: 2998 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2999 3000 return path 3001 3002 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 3003 if isinstance(expression, exp.JSONPathPart): 3004 transform = self.TRANSFORMS.get(expression.__class__) 3005 if not callable(transform): 3006 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 3007 return "" 3008 3009 return transform(self, expression) 3010 3011 if isinstance(expression, int): 3012 return str(expression) 3013 3014 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 3015 escaped = expression.replace("'", "\\'") 3016 escaped = f"\\'{expression}\\'" 3017 else: 3018 escaped = expression.replace('"', '\\"') 3019 escaped = f'"{escaped}"' 3020 3021 return escaped 3022 3023 def formatjson_sql(self, expression: exp.FormatJson) -> str: 3024 return f"{self.sql(expression, 'this')} FORMAT JSON" 3025 3026 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 3027 null_handling = expression.args.get("null_handling") 3028 null_handling = f" {null_handling}" if null_handling else "" 3029 3030 unique_keys = expression.args.get("unique_keys") 3031 if unique_keys is not None: 3032 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 3033 else: 3034 unique_keys = "" 3035 3036 return_type = self.sql(expression, "return_type") 3037 return_type = f" RETURNING {return_type}" if return_type else "" 3038 encoding = self.sql(expression, "encoding") 3039 encoding = f" ENCODING {encoding}" if encoding else "" 3040 3041 return self.func( 3042 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 3043 *expression.expressions, 3044 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 3045 ) 3046 3047 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 3048 return self.jsonobject_sql(expression) 3049 3050 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 3051 null_handling = expression.args.get("null_handling") 3052 null_handling = f" {null_handling}" if null_handling else "" 3053 return_type = self.sql(expression, "return_type") 3054 return_type = f" RETURNING {return_type}" if return_type else "" 3055 strict = " STRICT" if expression.args.get("strict") else "" 3056 return self.func( 3057 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 3058 ) 3059 3060 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 3061 this = self.sql(expression, "this") 3062 order = self.sql(expression, "order") 3063 null_handling = expression.args.get("null_handling") 3064 null_handling = f" {null_handling}" if null_handling else "" 3065 return_type = self.sql(expression, "return_type") 3066 return_type = f" RETURNING {return_type}" if return_type else "" 3067 strict = " STRICT" if expression.args.get("strict") else "" 3068 return self.func( 3069 "JSON_ARRAYAGG", 3070 this, 3071 suffix=f"{order}{null_handling}{return_type}{strict})", 3072 ) 3073 3074 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3075 path = self.sql(expression, "path") 3076 path = f" PATH {path}" if path else "" 3077 nested_schema = self.sql(expression, "nested_schema") 3078 3079 if nested_schema: 3080 return f"NESTED{path} {nested_schema}" 3081 3082 this = self.sql(expression, "this") 3083 kind = self.sql(expression, "kind") 3084 kind = f" {kind}" if kind else "" 3085 return f"{this}{kind}{path}" 3086 3087 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3088 return self.func("COLUMNS", *expression.expressions) 3089 3090 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3091 this = self.sql(expression, "this") 3092 path = self.sql(expression, "path") 3093 path = f", {path}" if path else "" 3094 error_handling = expression.args.get("error_handling") 3095 error_handling = f" {error_handling}" if error_handling else "" 3096 empty_handling = expression.args.get("empty_handling") 3097 empty_handling = f" {empty_handling}" if empty_handling else "" 3098 schema = self.sql(expression, "schema") 3099 return self.func( 3100 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3101 ) 3102 3103 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3104 this = self.sql(expression, "this") 3105 kind = self.sql(expression, "kind") 3106 path = self.sql(expression, "path") 3107 path = f" {path}" if path else "" 3108 as_json = " AS JSON" if expression.args.get("as_json") else "" 3109 return f"{this} {kind}{path}{as_json}" 3110 3111 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3112 this = self.sql(expression, "this") 3113 path = self.sql(expression, "path") 3114 path = f", {path}" if path else "" 3115 expressions = self.expressions(expression) 3116 with_ = ( 3117 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3118 if expressions 3119 else "" 3120 ) 3121 return f"OPENJSON({this}{path}){with_}" 3122 3123 def in_sql(self, expression: exp.In) -> str: 3124 query = expression.args.get("query") 3125 unnest = expression.args.get("unnest") 3126 field = expression.args.get("field") 3127 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3128 3129 if query: 3130 in_sql = self.sql(query) 3131 elif unnest: 3132 in_sql = self.in_unnest_op(unnest) 3133 elif field: 3134 in_sql = self.sql(field) 3135 else: 3136 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3137 3138 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3139 3140 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3141 return f"(SELECT {self.sql(unnest)})" 3142 3143 def interval_sql(self, expression: exp.Interval) -> str: 3144 unit = self.sql(expression, "unit") 3145 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3146 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3147 unit = f" {unit}" if unit else "" 3148 3149 if self.SINGLE_STRING_INTERVAL: 3150 this = expression.this.name if expression.this else "" 3151 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3152 3153 this = self.sql(expression, "this") 3154 if this: 3155 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3156 this = f" {this}" if unwrapped else f" ({this})" 3157 3158 return f"INTERVAL{this}{unit}" 3159 3160 def return_sql(self, expression: exp.Return) -> str: 3161 return f"RETURN {self.sql(expression, 'this')}" 3162 3163 def reference_sql(self, expression: exp.Reference) -> str: 3164 this = self.sql(expression, "this") 3165 expressions = self.expressions(expression, flat=True) 3166 expressions = f"({expressions})" if expressions else "" 3167 options = self.expressions(expression, key="options", flat=True, sep=" ") 3168 options = f" {options}" if options else "" 3169 return f"REFERENCES {this}{expressions}{options}" 3170 3171 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3172 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3173 parent = expression.parent 3174 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3175 return self.func( 3176 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3177 ) 3178 3179 def paren_sql(self, expression: exp.Paren) -> str: 3180 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3181 return f"({sql}{self.seg(')', sep='')}" 3182 3183 def neg_sql(self, expression: exp.Neg) -> str: 3184 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3185 this_sql = self.sql(expression, "this") 3186 sep = " " if this_sql[0] == "-" else "" 3187 return f"-{sep}{this_sql}" 3188 3189 def not_sql(self, expression: exp.Not) -> str: 3190 return f"NOT {self.sql(expression, 'this')}" 3191 3192 def alias_sql(self, expression: exp.Alias) -> str: 3193 alias = self.sql(expression, "alias") 3194 alias = f" AS {alias}" if alias else "" 3195 return f"{self.sql(expression, 'this')}{alias}" 3196 3197 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3198 alias = expression.args["alias"] 3199 3200 parent = expression.parent 3201 pivot = parent and parent.parent 3202 3203 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3204 identifier_alias = isinstance(alias, exp.Identifier) 3205 literal_alias = isinstance(alias, exp.Literal) 3206 3207 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3208 alias.replace(exp.Literal.string(alias.output_name)) 3209 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3210 alias.replace(exp.to_identifier(alias.output_name)) 3211 3212 return self.alias_sql(expression) 3213 3214 def aliases_sql(self, expression: exp.Aliases) -> str: 3215 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3216 3217 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3218 this = self.sql(expression, "this") 3219 index = self.sql(expression, "expression") 3220 return f"{this} AT {index}" 3221 3222 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3223 this = self.sql(expression, "this") 3224 zone = self.sql(expression, "zone") 3225 return f"{this} AT TIME ZONE {zone}" 3226 3227 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3228 this = self.sql(expression, "this") 3229 zone = self.sql(expression, "zone") 3230 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3231 3232 def add_sql(self, expression: exp.Add) -> str: 3233 return self.binary(expression, "+") 3234 3235 def and_sql( 3236 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3237 ) -> str: 3238 return self.connector_sql(expression, "AND", stack) 3239 3240 def or_sql( 3241 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3242 ) -> str: 3243 return self.connector_sql(expression, "OR", stack) 3244 3245 def xor_sql( 3246 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3247 ) -> str: 3248 return self.connector_sql(expression, "XOR", stack) 3249 3250 def connector_sql( 3251 self, 3252 expression: exp.Connector, 3253 op: str, 3254 stack: t.Optional[t.List[str | exp.Expression]] = None, 3255 ) -> str: 3256 if stack is not None: 3257 if expression.expressions: 3258 stack.append(self.expressions(expression, sep=f" {op} ")) 3259 else: 3260 stack.append(expression.right) 3261 if expression.comments and self.comments: 3262 for comment in expression.comments: 3263 if comment: 3264 op += f" /*{self.sanitize_comment(comment)}*/" 3265 stack.extend((op, expression.left)) 3266 return op 3267 3268 stack = [expression] 3269 sqls: t.List[str] = [] 3270 ops = set() 3271 3272 while stack: 3273 node = stack.pop() 3274 if isinstance(node, exp.Connector): 3275 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3276 else: 3277 sql = self.sql(node) 3278 if sqls and sqls[-1] in ops: 3279 sqls[-1] += f" {sql}" 3280 else: 3281 sqls.append(sql) 3282 3283 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3284 return sep.join(sqls) 3285 3286 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3287 return self.binary(expression, "&") 3288 3289 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3290 return self.binary(expression, "<<") 3291 3292 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3293 return f"~{self.sql(expression, 'this')}" 3294 3295 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3296 return self.binary(expression, "|") 3297 3298 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3299 return self.binary(expression, ">>") 3300 3301 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3302 return self.binary(expression, "^") 3303 3304 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3305 format_sql = self.sql(expression, "format") 3306 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3307 to_sql = self.sql(expression, "to") 3308 to_sql = f" {to_sql}" if to_sql else "" 3309 action = self.sql(expression, "action") 3310 action = f" {action}" if action else "" 3311 default = self.sql(expression, "default") 3312 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3313 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3314 3315 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3316 zone = self.sql(expression, "this") 3317 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3318 3319 def collate_sql(self, expression: exp.Collate) -> str: 3320 if self.COLLATE_IS_FUNC: 3321 return self.function_fallback_sql(expression) 3322 return self.binary(expression, "COLLATE") 3323 3324 def command_sql(self, expression: exp.Command) -> str: 3325 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3326 3327 def comment_sql(self, expression: exp.Comment) -> str: 3328 this = self.sql(expression, "this") 3329 kind = expression.args["kind"] 3330 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3331 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3332 expression_sql = self.sql(expression, "expression") 3333 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3334 3335 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3336 this = self.sql(expression, "this") 3337 delete = " DELETE" if expression.args.get("delete") else "" 3338 recompress = self.sql(expression, "recompress") 3339 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3340 to_disk = self.sql(expression, "to_disk") 3341 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3342 to_volume = self.sql(expression, "to_volume") 3343 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3344 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3345 3346 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3347 where = self.sql(expression, "where") 3348 group = self.sql(expression, "group") 3349 aggregates = self.expressions(expression, key="aggregates") 3350 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3351 3352 if not (where or group or aggregates) and len(expression.expressions) == 1: 3353 return f"TTL {self.expressions(expression, flat=True)}" 3354 3355 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3356 3357 def transaction_sql(self, expression: exp.Transaction) -> str: 3358 return "BEGIN" 3359 3360 def commit_sql(self, expression: exp.Commit) -> str: 3361 chain = expression.args.get("chain") 3362 if chain is not None: 3363 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3364 3365 return f"COMMIT{chain or ''}" 3366 3367 def rollback_sql(self, expression: exp.Rollback) -> str: 3368 savepoint = expression.args.get("savepoint") 3369 savepoint = f" TO {savepoint}" if savepoint else "" 3370 return f"ROLLBACK{savepoint}" 3371 3372 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3373 this = self.sql(expression, "this") 3374 3375 dtype = self.sql(expression, "dtype") 3376 if dtype: 3377 collate = self.sql(expression, "collate") 3378 collate = f" COLLATE {collate}" if collate else "" 3379 using = self.sql(expression, "using") 3380 using = f" USING {using}" if using else "" 3381 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 3382 return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}" 3383 3384 default = self.sql(expression, "default") 3385 if default: 3386 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3387 3388 comment = self.sql(expression, "comment") 3389 if comment: 3390 return f"ALTER COLUMN {this} COMMENT {comment}" 3391 3392 visible = expression.args.get("visible") 3393 if visible: 3394 return f"ALTER COLUMN {this} SET {visible}" 3395 3396 allow_null = expression.args.get("allow_null") 3397 drop = expression.args.get("drop") 3398 3399 if not drop and not allow_null: 3400 self.unsupported("Unsupported ALTER COLUMN syntax") 3401 3402 if allow_null is not None: 3403 keyword = "DROP" if drop else "SET" 3404 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3405 3406 return f"ALTER COLUMN {this} DROP DEFAULT" 3407 3408 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3409 this = self.sql(expression, "this") 3410 3411 visible = expression.args.get("visible") 3412 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3413 3414 return f"ALTER INDEX {this} {visible_sql}" 3415 3416 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3417 this = self.sql(expression, "this") 3418 if not isinstance(expression.this, exp.Var): 3419 this = f"KEY DISTKEY {this}" 3420 return f"ALTER DISTSTYLE {this}" 3421 3422 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3423 compound = " COMPOUND" if expression.args.get("compound") else "" 3424 this = self.sql(expression, "this") 3425 expressions = self.expressions(expression, flat=True) 3426 expressions = f"({expressions})" if expressions else "" 3427 return f"ALTER{compound} SORTKEY {this or expressions}" 3428 3429 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3430 if not self.RENAME_TABLE_WITH_DB: 3431 # Remove db from tables 3432 expression = expression.transform( 3433 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3434 ).assert_is(exp.AlterRename) 3435 this = self.sql(expression, "this") 3436 return f"RENAME TO {this}" 3437 3438 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3439 exists = " IF EXISTS" if expression.args.get("exists") else "" 3440 old_column = self.sql(expression, "this") 3441 new_column = self.sql(expression, "to") 3442 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3443 3444 def alterset_sql(self, expression: exp.AlterSet) -> str: 3445 exprs = self.expressions(expression, flat=True) 3446 if self.ALTER_SET_WRAPPED: 3447 exprs = f"({exprs})" 3448 3449 return f"SET {exprs}" 3450 3451 def alter_sql(self, expression: exp.Alter) -> str: 3452 actions = expression.args["actions"] 3453 3454 if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance( 3455 actions[0], exp.ColumnDef 3456 ): 3457 actions_sql = self.expressions(expression, key="actions", flat=True) 3458 actions_sql = f"ADD {actions_sql}" 3459 else: 3460 actions_list = [] 3461 for action in actions: 3462 if isinstance(action, (exp.ColumnDef, exp.Schema)): 3463 action_sql = self.add_column_sql(action) 3464 else: 3465 action_sql = self.sql(action) 3466 if isinstance(action, exp.Query): 3467 action_sql = f"AS {action_sql}" 3468 3469 actions_list.append(action_sql) 3470 3471 actions_sql = self.format_args(*actions_list) 3472 3473 exists = " IF EXISTS" if expression.args.get("exists") else "" 3474 on_cluster = self.sql(expression, "cluster") 3475 on_cluster = f" {on_cluster}" if on_cluster else "" 3476 only = " ONLY" if expression.args.get("only") else "" 3477 options = self.expressions(expression, key="options") 3478 options = f", {options}" if options else "" 3479 kind = self.sql(expression, "kind") 3480 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3481 3482 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}" 3483 3484 def add_column_sql(self, expression: exp.Expression) -> str: 3485 sql = self.sql(expression) 3486 if isinstance(expression, exp.Schema): 3487 column_text = " COLUMNS" 3488 elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3489 column_text = " COLUMN" 3490 else: 3491 column_text = "" 3492 3493 return f"ADD{column_text} {sql}" 3494 3495 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3496 expressions = self.expressions(expression) 3497 exists = " IF EXISTS " if expression.args.get("exists") else " " 3498 return f"DROP{exists}{expressions}" 3499 3500 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3501 return f"ADD {self.expressions(expression)}" 3502 3503 def distinct_sql(self, expression: exp.Distinct) -> str: 3504 this = self.expressions(expression, flat=True) 3505 3506 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3507 case = exp.case() 3508 for arg in expression.expressions: 3509 case = case.when(arg.is_(exp.null()), exp.null()) 3510 this = self.sql(case.else_(f"({this})")) 3511 3512 this = f" {this}" if this else "" 3513 3514 on = self.sql(expression, "on") 3515 on = f" ON {on}" if on else "" 3516 return f"DISTINCT{this}{on}" 3517 3518 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3519 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3520 3521 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3522 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3523 3524 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3525 this_sql = self.sql(expression, "this") 3526 expression_sql = self.sql(expression, "expression") 3527 kind = "MAX" if expression.args.get("max") else "MIN" 3528 return f"{this_sql} HAVING {kind} {expression_sql}" 3529 3530 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3531 return self.sql( 3532 exp.Cast( 3533 this=exp.Div(this=expression.this, expression=expression.expression), 3534 to=exp.DataType(this=exp.DataType.Type.INT), 3535 ) 3536 ) 3537 3538 def dpipe_sql(self, expression: exp.DPipe) -> str: 3539 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3540 return self.func( 3541 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3542 ) 3543 return self.binary(expression, "||") 3544 3545 def div_sql(self, expression: exp.Div) -> str: 3546 l, r = expression.left, expression.right 3547 3548 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3549 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3550 3551 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3552 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3553 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3554 3555 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3556 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3557 return self.sql( 3558 exp.cast( 3559 l / r, 3560 to=exp.DataType.Type.BIGINT, 3561 ) 3562 ) 3563 3564 return self.binary(expression, "/") 3565 3566 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3567 n = exp._wrap(expression.this, exp.Binary) 3568 d = exp._wrap(expression.expression, exp.Binary) 3569 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3570 3571 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3572 return self.binary(expression, "OVERLAPS") 3573 3574 def distance_sql(self, expression: exp.Distance) -> str: 3575 return self.binary(expression, "<->") 3576 3577 def dot_sql(self, expression: exp.Dot) -> str: 3578 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3579 3580 def eq_sql(self, expression: exp.EQ) -> str: 3581 return self.binary(expression, "=") 3582 3583 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3584 return self.binary(expression, ":=") 3585 3586 def escape_sql(self, expression: exp.Escape) -> str: 3587 return self.binary(expression, "ESCAPE") 3588 3589 def glob_sql(self, expression: exp.Glob) -> str: 3590 return self.binary(expression, "GLOB") 3591 3592 def gt_sql(self, expression: exp.GT) -> str: 3593 return self.binary(expression, ">") 3594 3595 def gte_sql(self, expression: exp.GTE) -> str: 3596 return self.binary(expression, ">=") 3597 3598 def ilike_sql(self, expression: exp.ILike) -> str: 3599 return self.binary(expression, "ILIKE") 3600 3601 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3602 return self.binary(expression, "ILIKE ANY") 3603 3604 def is_sql(self, expression: exp.Is) -> str: 3605 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3606 return self.sql( 3607 expression.this if expression.expression.this else exp.not_(expression.this) 3608 ) 3609 return self.binary(expression, "IS") 3610 3611 def like_sql(self, expression: exp.Like) -> str: 3612 return self.binary(expression, "LIKE") 3613 3614 def likeany_sql(self, expression: exp.LikeAny) -> str: 3615 return self.binary(expression, "LIKE ANY") 3616 3617 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3618 return self.binary(expression, "SIMILAR TO") 3619 3620 def lt_sql(self, expression: exp.LT) -> str: 3621 return self.binary(expression, "<") 3622 3623 def lte_sql(self, expression: exp.LTE) -> str: 3624 return self.binary(expression, "<=") 3625 3626 def mod_sql(self, expression: exp.Mod) -> str: 3627 return self.binary(expression, "%") 3628 3629 def mul_sql(self, expression: exp.Mul) -> str: 3630 return self.binary(expression, "*") 3631 3632 def neq_sql(self, expression: exp.NEQ) -> str: 3633 return self.binary(expression, "<>") 3634 3635 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3636 return self.binary(expression, "IS NOT DISTINCT FROM") 3637 3638 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3639 return self.binary(expression, "IS DISTINCT FROM") 3640 3641 def slice_sql(self, expression: exp.Slice) -> str: 3642 return self.binary(expression, ":") 3643 3644 def sub_sql(self, expression: exp.Sub) -> str: 3645 return self.binary(expression, "-") 3646 3647 def trycast_sql(self, expression: exp.TryCast) -> str: 3648 return self.cast_sql(expression, safe_prefix="TRY_") 3649 3650 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3651 return self.cast_sql(expression) 3652 3653 def try_sql(self, expression: exp.Try) -> str: 3654 if not self.TRY_SUPPORTED: 3655 self.unsupported("Unsupported TRY function") 3656 return self.sql(expression, "this") 3657 3658 return self.func("TRY", expression.this) 3659 3660 def log_sql(self, expression: exp.Log) -> str: 3661 this = expression.this 3662 expr = expression.expression 3663 3664 if self.dialect.LOG_BASE_FIRST is False: 3665 this, expr = expr, this 3666 elif self.dialect.LOG_BASE_FIRST is None and expr: 3667 if this.name in ("2", "10"): 3668 return self.func(f"LOG{this.name}", expr) 3669 3670 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3671 3672 return self.func("LOG", this, expr) 3673 3674 def use_sql(self, expression: exp.Use) -> str: 3675 kind = self.sql(expression, "kind") 3676 kind = f" {kind}" if kind else "" 3677 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3678 this = f" {this}" if this else "" 3679 return f"USE{kind}{this}" 3680 3681 def binary(self, expression: exp.Binary, op: str) -> str: 3682 sqls: t.List[str] = [] 3683 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3684 binary_type = type(expression) 3685 3686 while stack: 3687 node = stack.pop() 3688 3689 if type(node) is binary_type: 3690 op_func = node.args.get("operator") 3691 if op_func: 3692 op = f"OPERATOR({self.sql(op_func)})" 3693 3694 stack.append(node.right) 3695 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3696 stack.append(node.left) 3697 else: 3698 sqls.append(self.sql(node)) 3699 3700 return "".join(sqls) 3701 3702 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3703 to_clause = self.sql(expression, "to") 3704 if to_clause: 3705 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3706 3707 return self.function_fallback_sql(expression) 3708 3709 def function_fallback_sql(self, expression: exp.Func) -> str: 3710 args = [] 3711 3712 for key in expression.arg_types: 3713 arg_value = expression.args.get(key) 3714 3715 if isinstance(arg_value, list): 3716 for value in arg_value: 3717 args.append(value) 3718 elif arg_value is not None: 3719 args.append(arg_value) 3720 3721 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3722 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3723 else: 3724 name = expression.sql_name() 3725 3726 return self.func(name, *args) 3727 3728 def func( 3729 self, 3730 name: str, 3731 *args: t.Optional[exp.Expression | str], 3732 prefix: str = "(", 3733 suffix: str = ")", 3734 normalize: bool = True, 3735 ) -> str: 3736 name = self.normalize_func(name) if normalize else name 3737 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3738 3739 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3740 arg_sqls = tuple( 3741 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3742 ) 3743 if self.pretty and self.too_wide(arg_sqls): 3744 return self.indent( 3745 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3746 ) 3747 return sep.join(arg_sqls) 3748 3749 def too_wide(self, args: t.Iterable) -> bool: 3750 return sum(len(arg) for arg in args) > self.max_text_width 3751 3752 def format_time( 3753 self, 3754 expression: exp.Expression, 3755 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3756 inverse_time_trie: t.Optional[t.Dict] = None, 3757 ) -> t.Optional[str]: 3758 return format_time( 3759 self.sql(expression, "format"), 3760 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3761 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3762 ) 3763 3764 def expressions( 3765 self, 3766 expression: t.Optional[exp.Expression] = None, 3767 key: t.Optional[str] = None, 3768 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3769 flat: bool = False, 3770 indent: bool = True, 3771 skip_first: bool = False, 3772 skip_last: bool = False, 3773 sep: str = ", ", 3774 prefix: str = "", 3775 dynamic: bool = False, 3776 new_line: bool = False, 3777 ) -> str: 3778 expressions = expression.args.get(key or "expressions") if expression else sqls 3779 3780 if not expressions: 3781 return "" 3782 3783 if flat: 3784 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3785 3786 num_sqls = len(expressions) 3787 result_sqls = [] 3788 3789 for i, e in enumerate(expressions): 3790 sql = self.sql(e, comment=False) 3791 if not sql: 3792 continue 3793 3794 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3795 3796 if self.pretty: 3797 if self.leading_comma: 3798 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3799 else: 3800 result_sqls.append( 3801 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3802 ) 3803 else: 3804 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3805 3806 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3807 if new_line: 3808 result_sqls.insert(0, "") 3809 result_sqls.append("") 3810 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3811 else: 3812 result_sql = "".join(result_sqls) 3813 3814 return ( 3815 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3816 if indent 3817 else result_sql 3818 ) 3819 3820 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3821 flat = flat or isinstance(expression.parent, exp.Properties) 3822 expressions_sql = self.expressions(expression, flat=flat) 3823 if flat: 3824 return f"{op} {expressions_sql}" 3825 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3826 3827 def naked_property(self, expression: exp.Property) -> str: 3828 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3829 if not property_name: 3830 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3831 return f"{property_name} {self.sql(expression, 'this')}" 3832 3833 def tag_sql(self, expression: exp.Tag) -> str: 3834 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3835 3836 def token_sql(self, token_type: TokenType) -> str: 3837 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3838 3839 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3840 this = self.sql(expression, "this") 3841 expressions = self.no_identify(self.expressions, expression) 3842 expressions = ( 3843 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3844 ) 3845 return f"{this}{expressions}" if expressions.strip() != "" else this 3846 3847 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3848 this = self.sql(expression, "this") 3849 expressions = self.expressions(expression, flat=True) 3850 return f"{this}({expressions})" 3851 3852 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3853 return self.binary(expression, "=>") 3854 3855 def when_sql(self, expression: exp.When) -> str: 3856 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3857 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3858 condition = self.sql(expression, "condition") 3859 condition = f" AND {condition}" if condition else "" 3860 3861 then_expression = expression.args.get("then") 3862 if isinstance(then_expression, exp.Insert): 3863 this = self.sql(then_expression, "this") 3864 this = f"INSERT {this}" if this else "INSERT" 3865 then = self.sql(then_expression, "expression") 3866 then = f"{this} VALUES {then}" if then else this 3867 elif isinstance(then_expression, exp.Update): 3868 if isinstance(then_expression.args.get("expressions"), exp.Star): 3869 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3870 else: 3871 then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}" 3872 else: 3873 then = self.sql(then_expression) 3874 return f"WHEN {matched}{source}{condition} THEN {then}" 3875 3876 def whens_sql(self, expression: exp.Whens) -> str: 3877 return self.expressions(expression, sep=" ", indent=False) 3878 3879 def merge_sql(self, expression: exp.Merge) -> str: 3880 table = expression.this 3881 table_alias = "" 3882 3883 hints = table.args.get("hints") 3884 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3885 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3886 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3887 3888 this = self.sql(table) 3889 using = f"USING {self.sql(expression, 'using')}" 3890 on = f"ON {self.sql(expression, 'on')}" 3891 whens = self.sql(expression, "whens") 3892 3893 returning = self.sql(expression, "returning") 3894 if returning: 3895 whens = f"{whens}{returning}" 3896 3897 sep = self.sep() 3898 3899 return self.prepend_ctes( 3900 expression, 3901 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3902 ) 3903 3904 @unsupported_args("format") 3905 def tochar_sql(self, expression: exp.ToChar) -> str: 3906 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3907 3908 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3909 if not self.SUPPORTS_TO_NUMBER: 3910 self.unsupported("Unsupported TO_NUMBER function") 3911 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3912 3913 fmt = expression.args.get("format") 3914 if not fmt: 3915 self.unsupported("Conversion format is required for TO_NUMBER") 3916 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3917 3918 return self.func("TO_NUMBER", expression.this, fmt) 3919 3920 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3921 this = self.sql(expression, "this") 3922 kind = self.sql(expression, "kind") 3923 settings_sql = self.expressions(expression, key="settings", sep=" ") 3924 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3925 return f"{this}({kind}{args})" 3926 3927 def dictrange_sql(self, expression: exp.DictRange) -> str: 3928 this = self.sql(expression, "this") 3929 max = self.sql(expression, "max") 3930 min = self.sql(expression, "min") 3931 return f"{this}(MIN {min} MAX {max})" 3932 3933 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3934 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3935 3936 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3937 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3938 3939 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3940 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3941 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3942 3943 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3944 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3945 expressions = self.expressions(expression, flat=True) 3946 expressions = f" {self.wrap(expressions)}" if expressions else "" 3947 buckets = self.sql(expression, "buckets") 3948 kind = self.sql(expression, "kind") 3949 buckets = f" BUCKETS {buckets}" if buckets else "" 3950 order = self.sql(expression, "order") 3951 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3952 3953 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3954 return "" 3955 3956 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3957 expressions = self.expressions(expression, key="expressions", flat=True) 3958 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3959 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3960 buckets = self.sql(expression, "buckets") 3961 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3962 3963 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3964 this = self.sql(expression, "this") 3965 having = self.sql(expression, "having") 3966 3967 if having: 3968 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3969 3970 return self.func("ANY_VALUE", this) 3971 3972 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3973 transform = self.func("TRANSFORM", *expression.expressions) 3974 row_format_before = self.sql(expression, "row_format_before") 3975 row_format_before = f" {row_format_before}" if row_format_before else "" 3976 record_writer = self.sql(expression, "record_writer") 3977 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3978 using = f" USING {self.sql(expression, 'command_script')}" 3979 schema = self.sql(expression, "schema") 3980 schema = f" AS {schema}" if schema else "" 3981 row_format_after = self.sql(expression, "row_format_after") 3982 row_format_after = f" {row_format_after}" if row_format_after else "" 3983 record_reader = self.sql(expression, "record_reader") 3984 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3985 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3986 3987 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3988 key_block_size = self.sql(expression, "key_block_size") 3989 if key_block_size: 3990 return f"KEY_BLOCK_SIZE = {key_block_size}" 3991 3992 using = self.sql(expression, "using") 3993 if using: 3994 return f"USING {using}" 3995 3996 parser = self.sql(expression, "parser") 3997 if parser: 3998 return f"WITH PARSER {parser}" 3999 4000 comment = self.sql(expression, "comment") 4001 if comment: 4002 return f"COMMENT {comment}" 4003 4004 visible = expression.args.get("visible") 4005 if visible is not None: 4006 return "VISIBLE" if visible else "INVISIBLE" 4007 4008 engine_attr = self.sql(expression, "engine_attr") 4009 if engine_attr: 4010 return f"ENGINE_ATTRIBUTE = {engine_attr}" 4011 4012 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 4013 if secondary_engine_attr: 4014 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 4015 4016 self.unsupported("Unsupported index constraint option.") 4017 return "" 4018 4019 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 4020 enforced = " ENFORCED" if expression.args.get("enforced") else "" 4021 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 4022 4023 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 4024 kind = self.sql(expression, "kind") 4025 kind = f"{kind} INDEX" if kind else "INDEX" 4026 this = self.sql(expression, "this") 4027 this = f" {this}" if this else "" 4028 index_type = self.sql(expression, "index_type") 4029 index_type = f" USING {index_type}" if index_type else "" 4030 expressions = self.expressions(expression, flat=True) 4031 expressions = f" ({expressions})" if expressions else "" 4032 options = self.expressions(expression, key="options", sep=" ") 4033 options = f" {options}" if options else "" 4034 return f"{kind}{this}{index_type}{expressions}{options}" 4035 4036 def nvl2_sql(self, expression: exp.Nvl2) -> str: 4037 if self.NVL2_SUPPORTED: 4038 return self.function_fallback_sql(expression) 4039 4040 case = exp.Case().when( 4041 expression.this.is_(exp.null()).not_(copy=False), 4042 expression.args["true"], 4043 copy=False, 4044 ) 4045 else_cond = expression.args.get("false") 4046 if else_cond: 4047 case.else_(else_cond, copy=False) 4048 4049 return self.sql(case) 4050 4051 def comprehension_sql(self, expression: exp.Comprehension) -> str: 4052 this = self.sql(expression, "this") 4053 expr = self.sql(expression, "expression") 4054 iterator = self.sql(expression, "iterator") 4055 condition = self.sql(expression, "condition") 4056 condition = f" IF {condition}" if condition else "" 4057 return f"{this} FOR {expr} IN {iterator}{condition}" 4058 4059 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 4060 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 4061 4062 def opclass_sql(self, expression: exp.Opclass) -> str: 4063 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 4064 4065 def predict_sql(self, expression: exp.Predict) -> str: 4066 model = self.sql(expression, "this") 4067 model = f"MODEL {model}" 4068 table = self.sql(expression, "expression") 4069 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 4070 parameters = self.sql(expression, "params_struct") 4071 return self.func("PREDICT", model, table, parameters or None) 4072 4073 def forin_sql(self, expression: exp.ForIn) -> str: 4074 this = self.sql(expression, "this") 4075 expression_sql = self.sql(expression, "expression") 4076 return f"FOR {this} DO {expression_sql}" 4077 4078 def refresh_sql(self, expression: exp.Refresh) -> str: 4079 this = self.sql(expression, "this") 4080 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 4081 return f"REFRESH {table}{this}" 4082 4083 def toarray_sql(self, expression: exp.ToArray) -> str: 4084 arg = expression.this 4085 if not arg.type: 4086 from sqlglot.optimizer.annotate_types import annotate_types 4087 4088 arg = annotate_types(arg, dialect=self.dialect) 4089 4090 if arg.is_type(exp.DataType.Type.ARRAY): 4091 return self.sql(arg) 4092 4093 cond_for_null = arg.is_(exp.null()) 4094 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4095 4096 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4097 this = expression.this 4098 time_format = self.format_time(expression) 4099 4100 if time_format: 4101 return self.sql( 4102 exp.cast( 4103 exp.StrToTime(this=this, format=expression.args["format"]), 4104 exp.DataType.Type.TIME, 4105 ) 4106 ) 4107 4108 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4109 return self.sql(this) 4110 4111 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4112 4113 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4114 this = expression.this 4115 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4116 return self.sql(this) 4117 4118 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4119 4120 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4121 this = expression.this 4122 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4123 return self.sql(this) 4124 4125 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4126 4127 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4128 this = expression.this 4129 time_format = self.format_time(expression) 4130 4131 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4132 return self.sql( 4133 exp.cast( 4134 exp.StrToTime(this=this, format=expression.args["format"]), 4135 exp.DataType.Type.DATE, 4136 ) 4137 ) 4138 4139 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4140 return self.sql(this) 4141 4142 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4143 4144 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4145 return self.sql( 4146 exp.func( 4147 "DATEDIFF", 4148 expression.this, 4149 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4150 "day", 4151 ) 4152 ) 4153 4154 def lastday_sql(self, expression: exp.LastDay) -> str: 4155 if self.LAST_DAY_SUPPORTS_DATE_PART: 4156 return self.function_fallback_sql(expression) 4157 4158 unit = expression.text("unit") 4159 if unit and unit != "MONTH": 4160 self.unsupported("Date parts are not supported in LAST_DAY.") 4161 4162 return self.func("LAST_DAY", expression.this) 4163 4164 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4165 from sqlglot.dialects.dialect import unit_to_str 4166 4167 return self.func( 4168 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4169 ) 4170 4171 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4172 if self.CAN_IMPLEMENT_ARRAY_ANY: 4173 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4174 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4175 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4176 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4177 4178 from sqlglot.dialects import Dialect 4179 4180 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4181 if self.dialect.__class__ != Dialect: 4182 self.unsupported("ARRAY_ANY is unsupported") 4183 4184 return self.function_fallback_sql(expression) 4185 4186 def struct_sql(self, expression: exp.Struct) -> str: 4187 expression.set( 4188 "expressions", 4189 [ 4190 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4191 if isinstance(e, exp.PropertyEQ) 4192 else e 4193 for e in expression.expressions 4194 ], 4195 ) 4196 4197 return self.function_fallback_sql(expression) 4198 4199 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4200 low = self.sql(expression, "this") 4201 high = self.sql(expression, "expression") 4202 4203 return f"{low} TO {high}" 4204 4205 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4206 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4207 tables = f" {self.expressions(expression)}" 4208 4209 exists = " IF EXISTS" if expression.args.get("exists") else "" 4210 4211 on_cluster = self.sql(expression, "cluster") 4212 on_cluster = f" {on_cluster}" if on_cluster else "" 4213 4214 identity = self.sql(expression, "identity") 4215 identity = f" {identity} IDENTITY" if identity else "" 4216 4217 option = self.sql(expression, "option") 4218 option = f" {option}" if option else "" 4219 4220 partition = self.sql(expression, "partition") 4221 partition = f" {partition}" if partition else "" 4222 4223 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4224 4225 # This transpiles T-SQL's CONVERT function 4226 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4227 def convert_sql(self, expression: exp.Convert) -> str: 4228 to = expression.this 4229 value = expression.expression 4230 style = expression.args.get("style") 4231 safe = expression.args.get("safe") 4232 strict = expression.args.get("strict") 4233 4234 if not to or not value: 4235 return "" 4236 4237 # Retrieve length of datatype and override to default if not specified 4238 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4239 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4240 4241 transformed: t.Optional[exp.Expression] = None 4242 cast = exp.Cast if strict else exp.TryCast 4243 4244 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4245 if isinstance(style, exp.Literal) and style.is_int: 4246 from sqlglot.dialects.tsql import TSQL 4247 4248 style_value = style.name 4249 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4250 if not converted_style: 4251 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4252 4253 fmt = exp.Literal.string(converted_style) 4254 4255 if to.this == exp.DataType.Type.DATE: 4256 transformed = exp.StrToDate(this=value, format=fmt) 4257 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4258 transformed = exp.StrToTime(this=value, format=fmt) 4259 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4260 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4261 elif to.this == exp.DataType.Type.TEXT: 4262 transformed = exp.TimeToStr(this=value, format=fmt) 4263 4264 if not transformed: 4265 transformed = cast(this=value, to=to, safe=safe) 4266 4267 return self.sql(transformed) 4268 4269 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4270 this = expression.this 4271 if isinstance(this, exp.JSONPathWildcard): 4272 this = self.json_path_part(this) 4273 return f".{this}" if this else "" 4274 4275 if exp.SAFE_IDENTIFIER_RE.match(this): 4276 return f".{this}" 4277 4278 this = self.json_path_part(this) 4279 return ( 4280 f"[{this}]" 4281 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4282 else f".{this}" 4283 ) 4284 4285 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4286 this = self.json_path_part(expression.this) 4287 return f"[{this}]" if this else "" 4288 4289 def _simplify_unless_literal(self, expression: E) -> E: 4290 if not isinstance(expression, exp.Literal): 4291 from sqlglot.optimizer.simplify import simplify 4292 4293 expression = simplify(expression, dialect=self.dialect) 4294 4295 return expression 4296 4297 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4298 this = expression.this 4299 if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS): 4300 self.unsupported( 4301 f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}" 4302 ) 4303 return self.sql(this) 4304 4305 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4306 # The first modifier here will be the one closest to the AggFunc's arg 4307 mods = sorted( 4308 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4309 key=lambda x: 0 4310 if isinstance(x, exp.HavingMax) 4311 else (1 if isinstance(x, exp.Order) else 2), 4312 ) 4313 4314 if mods: 4315 mod = mods[0] 4316 this = expression.__class__(this=mod.this.copy()) 4317 this.meta["inline"] = True 4318 mod.this.replace(this) 4319 return self.sql(expression.this) 4320 4321 agg_func = expression.find(exp.AggFunc) 4322 4323 if agg_func: 4324 agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})" 4325 return self.maybe_comment(agg_func_sql, comments=agg_func.comments) 4326 4327 return f"{self.sql(expression, 'this')} {text}" 4328 4329 def _replace_line_breaks(self, string: str) -> str: 4330 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4331 if self.pretty: 4332 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4333 return string 4334 4335 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4336 option = self.sql(expression, "this") 4337 4338 if expression.expressions: 4339 upper = option.upper() 4340 4341 # Snowflake FILE_FORMAT options are separated by whitespace 4342 sep = " " if upper == "FILE_FORMAT" else ", " 4343 4344 # Databricks copy/format options do not set their list of values with EQ 4345 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4346 values = self.expressions(expression, flat=True, sep=sep) 4347 return f"{option}{op}({values})" 4348 4349 value = self.sql(expression, "expression") 4350 4351 if not value: 4352 return option 4353 4354 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4355 4356 return f"{option}{op}{value}" 4357 4358 def credentials_sql(self, expression: exp.Credentials) -> str: 4359 cred_expr = expression.args.get("credentials") 4360 if isinstance(cred_expr, exp.Literal): 4361 # Redshift case: CREDENTIALS <string> 4362 credentials = self.sql(expression, "credentials") 4363 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4364 else: 4365 # Snowflake case: CREDENTIALS = (...) 4366 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4367 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4368 4369 storage = self.sql(expression, "storage") 4370 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4371 4372 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4373 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4374 4375 iam_role = self.sql(expression, "iam_role") 4376 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4377 4378 region = self.sql(expression, "region") 4379 region = f" REGION {region}" if region else "" 4380 4381 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4382 4383 def copy_sql(self, expression: exp.Copy) -> str: 4384 this = self.sql(expression, "this") 4385 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4386 4387 credentials = self.sql(expression, "credentials") 4388 credentials = self.seg(credentials) if credentials else "" 4389 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4390 files = self.expressions(expression, key="files", flat=True) 4391 4392 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4393 params = self.expressions( 4394 expression, 4395 key="params", 4396 sep=sep, 4397 new_line=True, 4398 skip_last=True, 4399 skip_first=True, 4400 indent=self.COPY_PARAMS_ARE_WRAPPED, 4401 ) 4402 4403 if params: 4404 if self.COPY_PARAMS_ARE_WRAPPED: 4405 params = f" WITH ({params})" 4406 elif not self.pretty: 4407 params = f" {params}" 4408 4409 return f"COPY{this}{kind} {files}{credentials}{params}" 4410 4411 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4412 return "" 4413 4414 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4415 on_sql = "ON" if expression.args.get("on") else "OFF" 4416 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4417 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4418 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4419 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4420 4421 if filter_col or retention_period: 4422 on_sql = self.func("ON", filter_col, retention_period) 4423 4424 return f"DATA_DELETION={on_sql}" 4425 4426 def maskingpolicycolumnconstraint_sql( 4427 self, expression: exp.MaskingPolicyColumnConstraint 4428 ) -> str: 4429 this = self.sql(expression, "this") 4430 expressions = self.expressions(expression, flat=True) 4431 expressions = f" USING ({expressions})" if expressions else "" 4432 return f"MASKING POLICY {this}{expressions}" 4433 4434 def gapfill_sql(self, expression: exp.GapFill) -> str: 4435 this = self.sql(expression, "this") 4436 this = f"TABLE {this}" 4437 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4438 4439 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4440 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4441 4442 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4443 this = self.sql(expression, "this") 4444 expr = expression.expression 4445 4446 if isinstance(expr, exp.Func): 4447 # T-SQL's CLR functions are case sensitive 4448 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4449 else: 4450 expr = self.sql(expression, "expression") 4451 4452 return self.scope_resolution(expr, this) 4453 4454 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4455 if self.PARSE_JSON_NAME is None: 4456 return self.sql(expression.this) 4457 4458 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4459 4460 def rand_sql(self, expression: exp.Rand) -> str: 4461 lower = self.sql(expression, "lower") 4462 upper = self.sql(expression, "upper") 4463 4464 if lower and upper: 4465 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4466 return self.func("RAND", expression.this) 4467 4468 def changes_sql(self, expression: exp.Changes) -> str: 4469 information = self.sql(expression, "information") 4470 information = f"INFORMATION => {information}" 4471 at_before = self.sql(expression, "at_before") 4472 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4473 end = self.sql(expression, "end") 4474 end = f"{self.seg('')}{end}" if end else "" 4475 4476 return f"CHANGES ({information}){at_before}{end}" 4477 4478 def pad_sql(self, expression: exp.Pad) -> str: 4479 prefix = "L" if expression.args.get("is_left") else "R" 4480 4481 fill_pattern = self.sql(expression, "fill_pattern") or None 4482 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4483 fill_pattern = "' '" 4484 4485 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4486 4487 def summarize_sql(self, expression: exp.Summarize) -> str: 4488 table = " TABLE" if expression.args.get("table") else "" 4489 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4490 4491 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4492 generate_series = exp.GenerateSeries(**expression.args) 4493 4494 parent = expression.parent 4495 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4496 parent = parent.parent 4497 4498 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4499 return self.sql(exp.Unnest(expressions=[generate_series])) 4500 4501 if isinstance(parent, exp.Select): 4502 self.unsupported("GenerateSeries projection unnesting is not supported.") 4503 4504 return self.sql(generate_series) 4505 4506 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4507 exprs = expression.expressions 4508 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4509 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4510 else: 4511 rhs = self.expressions(expression) 4512 4513 return self.func(name, expression.this, rhs or None) 4514 4515 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4516 if self.SUPPORTS_CONVERT_TIMEZONE: 4517 return self.function_fallback_sql(expression) 4518 4519 source_tz = expression.args.get("source_tz") 4520 target_tz = expression.args.get("target_tz") 4521 timestamp = expression.args.get("timestamp") 4522 4523 if source_tz and timestamp: 4524 timestamp = exp.AtTimeZone( 4525 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4526 ) 4527 4528 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4529 4530 return self.sql(expr) 4531 4532 def json_sql(self, expression: exp.JSON) -> str: 4533 this = self.sql(expression, "this") 4534 this = f" {this}" if this else "" 4535 4536 _with = expression.args.get("with") 4537 4538 if _with is None: 4539 with_sql = "" 4540 elif not _with: 4541 with_sql = " WITHOUT" 4542 else: 4543 with_sql = " WITH" 4544 4545 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4546 4547 return f"JSON{this}{with_sql}{unique_sql}" 4548 4549 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4550 def _generate_on_options(arg: t.Any) -> str: 4551 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4552 4553 path = self.sql(expression, "path") 4554 returning = self.sql(expression, "returning") 4555 returning = f" RETURNING {returning}" if returning else "" 4556 4557 on_condition = self.sql(expression, "on_condition") 4558 on_condition = f" {on_condition}" if on_condition else "" 4559 4560 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4561 4562 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4563 else_ = "ELSE " if expression.args.get("else_") else "" 4564 condition = self.sql(expression, "expression") 4565 condition = f"WHEN {condition} THEN " if condition else else_ 4566 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4567 return f"{condition}{insert}" 4568 4569 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4570 kind = self.sql(expression, "kind") 4571 expressions = self.seg(self.expressions(expression, sep=" ")) 4572 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4573 return res 4574 4575 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4576 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4577 empty = expression.args.get("empty") 4578 empty = ( 4579 f"DEFAULT {empty} ON EMPTY" 4580 if isinstance(empty, exp.Expression) 4581 else self.sql(expression, "empty") 4582 ) 4583 4584 error = expression.args.get("error") 4585 error = ( 4586 f"DEFAULT {error} ON ERROR" 4587 if isinstance(error, exp.Expression) 4588 else self.sql(expression, "error") 4589 ) 4590 4591 if error and empty: 4592 error = ( 4593 f"{empty} {error}" 4594 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4595 else f"{error} {empty}" 4596 ) 4597 empty = "" 4598 4599 null = self.sql(expression, "null") 4600 4601 return f"{empty}{error}{null}" 4602 4603 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4604 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4605 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4606 4607 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4608 this = self.sql(expression, "this") 4609 path = self.sql(expression, "path") 4610 4611 passing = self.expressions(expression, "passing") 4612 passing = f" PASSING {passing}" if passing else "" 4613 4614 on_condition = self.sql(expression, "on_condition") 4615 on_condition = f" {on_condition}" if on_condition else "" 4616 4617 path = f"{path}{passing}{on_condition}" 4618 4619 return self.func("JSON_EXISTS", this, path) 4620 4621 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4622 array_agg = self.function_fallback_sql(expression) 4623 4624 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4625 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4626 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4627 parent = expression.parent 4628 if isinstance(parent, exp.Filter): 4629 parent_cond = parent.expression.this 4630 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4631 else: 4632 this = expression.this 4633 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4634 if this.find(exp.Column): 4635 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4636 this_sql = ( 4637 self.expressions(this) 4638 if isinstance(this, exp.Distinct) 4639 else self.sql(expression, "this") 4640 ) 4641 4642 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4643 4644 return array_agg 4645 4646 def apply_sql(self, expression: exp.Apply) -> str: 4647 this = self.sql(expression, "this") 4648 expr = self.sql(expression, "expression") 4649 4650 return f"{this} APPLY({expr})" 4651 4652 def grant_sql(self, expression: exp.Grant) -> str: 4653 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4654 4655 kind = self.sql(expression, "kind") 4656 kind = f" {kind}" if kind else "" 4657 4658 securable = self.sql(expression, "securable") 4659 securable = f" {securable}" if securable else "" 4660 4661 principals = self.expressions(expression, key="principals", flat=True) 4662 4663 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4664 4665 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4666 4667 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4668 this = self.sql(expression, "this") 4669 columns = self.expressions(expression, flat=True) 4670 columns = f"({columns})" if columns else "" 4671 4672 return f"{this}{columns}" 4673 4674 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4675 this = self.sql(expression, "this") 4676 4677 kind = self.sql(expression, "kind") 4678 kind = f"{kind} " if kind else "" 4679 4680 return f"{kind}{this}" 4681 4682 def columns_sql(self, expression: exp.Columns): 4683 func = self.function_fallback_sql(expression) 4684 if expression.args.get("unpack"): 4685 func = f"*{func}" 4686 4687 return func 4688 4689 def overlay_sql(self, expression: exp.Overlay): 4690 this = self.sql(expression, "this") 4691 expr = self.sql(expression, "expression") 4692 from_sql = self.sql(expression, "from") 4693 for_sql = self.sql(expression, "for") 4694 for_sql = f" FOR {for_sql}" if for_sql else "" 4695 4696 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4697 4698 @unsupported_args("format") 4699 def todouble_sql(self, expression: exp.ToDouble) -> str: 4700 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4701 4702 def string_sql(self, expression: exp.String) -> str: 4703 this = expression.this 4704 zone = expression.args.get("zone") 4705 4706 if zone: 4707 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4708 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4709 # set for source_tz to transpile the time conversion before the STRING cast 4710 this = exp.ConvertTimezone( 4711 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4712 ) 4713 4714 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4715 4716 def median_sql(self, expression: exp.Median): 4717 if not self.SUPPORTS_MEDIAN: 4718 return self.sql( 4719 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4720 ) 4721 4722 return self.function_fallback_sql(expression) 4723 4724 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4725 filler = self.sql(expression, "this") 4726 filler = f" {filler}" if filler else "" 4727 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4728 return f"TRUNCATE{filler} {with_count}" 4729 4730 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4731 if self.SUPPORTS_UNIX_SECONDS: 4732 return self.function_fallback_sql(expression) 4733 4734 start_ts = exp.cast( 4735 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4736 ) 4737 4738 return self.sql( 4739 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4740 ) 4741 4742 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4743 dim = expression.expression 4744 4745 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4746 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4747 if not (dim.is_int and dim.name == "1"): 4748 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4749 dim = None 4750 4751 # If dimension is required but not specified, default initialize it 4752 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4753 dim = exp.Literal.number(1) 4754 4755 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4756 4757 def attach_sql(self, expression: exp.Attach) -> str: 4758 this = self.sql(expression, "this") 4759 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4760 expressions = self.expressions(expression) 4761 expressions = f" ({expressions})" if expressions else "" 4762 4763 return f"ATTACH{exists_sql} {this}{expressions}" 4764 4765 def detach_sql(self, expression: exp.Detach) -> str: 4766 this = self.sql(expression, "this") 4767 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4768 4769 return f"DETACH{exists_sql} {this}" 4770 4771 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4772 this = self.sql(expression, "this") 4773 value = self.sql(expression, "expression") 4774 value = f" {value}" if value else "" 4775 return f"{this}{value}" 4776 4777 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4778 this_sql = self.sql(expression, "this") 4779 if isinstance(expression.this, exp.Table): 4780 this_sql = f"TABLE {this_sql}" 4781 4782 return self.func( 4783 "FEATURES_AT_TIME", 4784 this_sql, 4785 expression.args.get("time"), 4786 expression.args.get("num_rows"), 4787 expression.args.get("ignore_feature_nulls"), 4788 ) 4789 4790 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4791 return ( 4792 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4793 ) 4794 4795 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4796 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4797 encode = f"{encode} {self.sql(expression, 'this')}" 4798 4799 properties = expression.args.get("properties") 4800 if properties: 4801 encode = f"{encode} {self.properties(properties)}" 4802 4803 return encode 4804 4805 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4806 this = self.sql(expression, "this") 4807 include = f"INCLUDE {this}" 4808 4809 column_def = self.sql(expression, "column_def") 4810 if column_def: 4811 include = f"{include} {column_def}" 4812 4813 alias = self.sql(expression, "alias") 4814 if alias: 4815 include = f"{include} AS {alias}" 4816 4817 return include 4818 4819 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4820 name = f"NAME {self.sql(expression, 'this')}" 4821 return self.func("XMLELEMENT", name, *expression.expressions) 4822 4823 def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str: 4824 this = self.sql(expression, "this") 4825 expr = self.sql(expression, "expression") 4826 expr = f"({expr})" if expr else "" 4827 return f"{this}{expr}" 4828 4829 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4830 partitions = self.expressions(expression, "partition_expressions") 4831 create = self.expressions(expression, "create_expressions") 4832 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4833 4834 def partitionbyrangepropertydynamic_sql( 4835 self, expression: exp.PartitionByRangePropertyDynamic 4836 ) -> str: 4837 start = self.sql(expression, "start") 4838 end = self.sql(expression, "end") 4839 4840 every = expression.args["every"] 4841 if isinstance(every, exp.Interval) and every.this.is_string: 4842 every.this.replace(exp.Literal.number(every.name)) 4843 4844 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4845 4846 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4847 name = self.sql(expression, "this") 4848 values = self.expressions(expression, flat=True) 4849 4850 return f"NAME {name} VALUE {values}" 4851 4852 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4853 kind = self.sql(expression, "kind") 4854 sample = self.sql(expression, "sample") 4855 return f"SAMPLE {sample} {kind}" 4856 4857 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4858 kind = self.sql(expression, "kind") 4859 option = self.sql(expression, "option") 4860 option = f" {option}" if option else "" 4861 this = self.sql(expression, "this") 4862 this = f" {this}" if this else "" 4863 columns = self.expressions(expression) 4864 columns = f" {columns}" if columns else "" 4865 return f"{kind}{option} STATISTICS{this}{columns}" 4866 4867 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4868 this = self.sql(expression, "this") 4869 columns = self.expressions(expression) 4870 inner_expression = self.sql(expression, "expression") 4871 inner_expression = f" {inner_expression}" if inner_expression else "" 4872 update_options = self.sql(expression, "update_options") 4873 update_options = f" {update_options} UPDATE" if update_options else "" 4874 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4875 4876 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4877 kind = self.sql(expression, "kind") 4878 kind = f" {kind}" if kind else "" 4879 return f"DELETE{kind} STATISTICS" 4880 4881 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4882 inner_expression = self.sql(expression, "expression") 4883 return f"LIST CHAINED ROWS{inner_expression}" 4884 4885 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4886 kind = self.sql(expression, "kind") 4887 this = self.sql(expression, "this") 4888 this = f" {this}" if this else "" 4889 inner_expression = self.sql(expression, "expression") 4890 return f"VALIDATE {kind}{this}{inner_expression}" 4891 4892 def analyze_sql(self, expression: exp.Analyze) -> str: 4893 options = self.expressions(expression, key="options", sep=" ") 4894 options = f" {options}" if options else "" 4895 kind = self.sql(expression, "kind") 4896 kind = f" {kind}" if kind else "" 4897 this = self.sql(expression, "this") 4898 this = f" {this}" if this else "" 4899 mode = self.sql(expression, "mode") 4900 mode = f" {mode}" if mode else "" 4901 properties = self.sql(expression, "properties") 4902 properties = f" {properties}" if properties else "" 4903 partition = self.sql(expression, "partition") 4904 partition = f" {partition}" if partition else "" 4905 inner_expression = self.sql(expression, "expression") 4906 inner_expression = f" {inner_expression}" if inner_expression else "" 4907 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4908 4909 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4910 this = self.sql(expression, "this") 4911 namespaces = self.expressions(expression, key="namespaces") 4912 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4913 passing = self.expressions(expression, key="passing") 4914 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4915 columns = self.expressions(expression, key="columns") 4916 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4917 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4918 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4919 4920 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4921 this = self.sql(expression, "this") 4922 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4923 4924 def export_sql(self, expression: exp.Export) -> str: 4925 this = self.sql(expression, "this") 4926 connection = self.sql(expression, "connection") 4927 connection = f"WITH CONNECTION {connection} " if connection else "" 4928 options = self.sql(expression, "options") 4929 return f"EXPORT DATA {connection}{options} AS {this}" 4930 4931 def declare_sql(self, expression: exp.Declare) -> str: 4932 return f"DECLARE {self.expressions(expression, flat=True)}" 4933 4934 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4935 variable = self.sql(expression, "this") 4936 default = self.sql(expression, "default") 4937 default = f" = {default}" if default else "" 4938 4939 kind = self.sql(expression, "kind") 4940 if isinstance(expression.args.get("kind"), exp.Schema): 4941 kind = f"TABLE {kind}" 4942 4943 return f"{variable} AS {kind}{default}" 4944 4945 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4946 kind = self.sql(expression, "kind") 4947 this = self.sql(expression, "this") 4948 set = self.sql(expression, "expression") 4949 using = self.sql(expression, "using") 4950 using = f" USING {using}" if using else "" 4951 4952 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4953 4954 return f"{kind_sql} {this} SET {set}{using}" 4955 4956 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4957 params = self.expressions(expression, key="params", flat=True) 4958 return self.func(expression.name, *expression.expressions) + f"({params})" 4959 4960 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4961 return self.func(expression.name, *expression.expressions) 4962 4963 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4964 return self.anonymousaggfunc_sql(expression) 4965 4966 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4967 return self.parameterizedagg_sql(expression) 4968 4969 def show_sql(self, expression: exp.Show) -> str: 4970 self.unsupported("Unsupported SHOW statement") 4971 return "" 4972 4973 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 4974 # Snowflake GET/PUT statements: 4975 # PUT <file> <internalStage> <properties> 4976 # GET <internalStage> <file> <properties> 4977 props = expression.args.get("properties") 4978 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4979 this = self.sql(expression, "this") 4980 target = self.sql(expression, "target") 4981 4982 if isinstance(expression, exp.Put): 4983 return f"PUT {this} {target}{props_sql}" 4984 else: 4985 return f"GET {target} {this}{props_sql}" 4986 4987 def translatecharacters_sql(self, expression: exp.TranslateCharacters): 4988 this = self.sql(expression, "this") 4989 expr = self.sql(expression, "expression") 4990 with_error = " WITH ERROR" if expression.args.get("with_error") else "" 4991 return f"TRANSLATE({this} USING {expr}{with_error})"
logger =
<Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE =
re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE =
"Argument '{}' is not supported for expression '{}' when targeting {}."
def
unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
30def unsupported_args( 31 *args: t.Union[str, t.Tuple[str, str]], 32) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 33 """ 34 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 35 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 36 """ 37 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 38 for arg in args: 39 if isinstance(arg, str): 40 diagnostic_by_arg[arg] = None 41 else: 42 diagnostic_by_arg[arg[0]] = arg[1] 43 44 def decorator(func: GeneratorMethod) -> GeneratorMethod: 45 @wraps(func) 46 def _func(generator: G, expression: E) -> str: 47 expression_name = expression.__class__.__name__ 48 dialect_name = generator.dialect.__class__.__name__ 49 50 for arg_name, diagnostic in diagnostic_by_arg.items(): 51 if expression.args.get(arg_name): 52 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 53 arg_name, expression_name, dialect_name 54 ) 55 generator.unsupported(diagnostic) 56 57 return func(generator, expression) 58 59 return _func 60 61 return decorator
Decorator that can be used to mark certain args of an Expression
subclass as unsupported.
It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
class
Generator:
75class Generator(metaclass=_Generator): 76 """ 77 Generator converts a given syntax tree to the corresponding SQL string. 78 79 Args: 80 pretty: Whether to format the produced SQL string. 81 Default: False. 82 identify: Determines when an identifier should be quoted. Possible values are: 83 False (default): Never quote, except in cases where it's mandatory by the dialect. 84 True or 'always': Always quote. 85 'safe': Only quote identifiers that are case insensitive. 86 normalize: Whether to normalize identifiers to lowercase. 87 Default: False. 88 pad: The pad size in a formatted string. For example, this affects the indentation of 89 a projection in a query, relative to its nesting level. 90 Default: 2. 91 indent: The indentation size in a formatted string. For example, this affects the 92 indentation of subqueries and filters under a `WHERE` clause. 93 Default: 2. 94 normalize_functions: How to normalize function names. Possible values are: 95 "upper" or True (default): Convert names to uppercase. 96 "lower": Convert names to lowercase. 97 False: Disables function name normalization. 98 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 99 Default ErrorLevel.WARN. 100 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 101 This is only relevant if unsupported_level is ErrorLevel.RAISE. 102 Default: 3 103 leading_comma: Whether the comma is leading or trailing in select expressions. 104 This is only relevant when generating in pretty mode. 105 Default: False 106 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 107 The default is on the smaller end because the length only represents a segment and not the true 108 line length. 109 Default: 80 110 comments: Whether to preserve comments in the output SQL code. 111 Default: True 112 """ 113 114 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 115 **JSON_PATH_PART_TRANSFORMS, 116 exp.AllowedValuesProperty: lambda self, 117 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 118 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 119 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 120 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 121 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 122 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 123 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 124 exp.CaseSpecificColumnConstraint: lambda _, 125 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 126 exp.Ceil: lambda self, e: self.ceil_floor(e), 127 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 128 exp.CharacterSetProperty: lambda self, 129 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 130 exp.ClusteredColumnConstraint: lambda self, 131 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 132 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 133 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 134 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 135 exp.ConvertToCharset: lambda self, e: self.func( 136 "CONVERT", e.this, e.args["dest"], e.args.get("source") 137 ), 138 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 139 exp.CredentialsProperty: lambda self, 140 e: f"CREDENTIALS=({self.expressions(e, 'expressions', sep=' ')})", 141 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 142 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 143 exp.DynamicProperty: lambda *_: "DYNAMIC", 144 exp.EmptyProperty: lambda *_: "EMPTY", 145 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 146 exp.EnviromentProperty: lambda self, e: f"ENVIRONMENT ({self.expressions(e, flat=True)})", 147 exp.EphemeralColumnConstraint: lambda self, 148 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 149 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 150 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 151 exp.Except: lambda self, e: self.set_operations(e), 152 exp.ExternalProperty: lambda *_: "EXTERNAL", 153 exp.Floor: lambda self, e: self.ceil_floor(e), 154 exp.Get: lambda self, e: self.get_put_sql(e), 155 exp.GlobalProperty: lambda *_: "GLOBAL", 156 exp.HeapProperty: lambda *_: "HEAP", 157 exp.IcebergProperty: lambda *_: "ICEBERG", 158 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 159 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 160 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 161 exp.Intersect: lambda self, e: self.set_operations(e), 162 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 163 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 164 exp.LanguageProperty: lambda self, e: self.naked_property(e), 165 exp.LocationProperty: lambda self, e: self.naked_property(e), 166 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 167 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 168 exp.NonClusteredColumnConstraint: lambda self, 169 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 170 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 171 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 172 exp.OnCommitProperty: lambda _, 173 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 174 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 175 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 176 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 177 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 178 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 179 exp.PartitionedByBucket: lambda self, e: self.func("BUCKET", e.this, e.expression), 180 exp.PartitionByTruncate: lambda self, e: self.func("TRUNCATE", e.this, e.expression), 181 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 182 exp.ProjectionPolicyColumnConstraint: lambda self, 183 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 184 exp.Put: lambda self, e: self.get_put_sql(e), 185 exp.RemoteWithConnectionModelProperty: lambda self, 186 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 187 exp.ReturnsProperty: lambda self, e: ( 188 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 189 ), 190 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 191 exp.SecureProperty: lambda *_: "SECURE", 192 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 193 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 194 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 195 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 196 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 197 exp.SqlReadWriteProperty: lambda _, e: e.name, 198 exp.SqlSecurityProperty: lambda _, 199 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 200 exp.StabilityProperty: lambda _, e: e.name, 201 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 202 exp.StreamingTableProperty: lambda *_: "STREAMING", 203 exp.StrictProperty: lambda *_: "STRICT", 204 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 205 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 206 exp.TemporaryProperty: lambda *_: "TEMPORARY", 207 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 208 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 209 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 210 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 211 exp.TransientProperty: lambda *_: "TRANSIENT", 212 exp.Union: lambda self, e: self.set_operations(e), 213 exp.UnloggedProperty: lambda *_: "UNLOGGED", 214 exp.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 215 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 216 exp.Uuid: lambda *_: "UUID()", 217 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 218 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 219 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 220 exp.VolatileProperty: lambda *_: "VOLATILE", 221 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 222 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 223 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 224 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 225 exp.ForceProperty: lambda *_: "FORCE", 226 } 227 228 # Whether null ordering is supported in order by 229 # True: Full Support, None: No support, False: No support for certain cases 230 # such as window specifications, aggregate functions etc 231 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 232 233 # Whether ignore nulls is inside the agg or outside. 234 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 235 IGNORE_NULLS_IN_FUNC = False 236 237 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 238 LOCKING_READS_SUPPORTED = False 239 240 # Whether the EXCEPT and INTERSECT operations can return duplicates 241 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 242 243 # Wrap derived values in parens, usually standard but spark doesn't support it 244 WRAP_DERIVED_VALUES = True 245 246 # Whether create function uses an AS before the RETURN 247 CREATE_FUNCTION_RETURN_AS = True 248 249 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 250 MATCHED_BY_SOURCE = True 251 252 # Whether the INTERVAL expression works only with values like '1 day' 253 SINGLE_STRING_INTERVAL = False 254 255 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 256 INTERVAL_ALLOWS_PLURAL_FORM = True 257 258 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 259 LIMIT_FETCH = "ALL" 260 261 # Whether limit and fetch allows expresions or just limits 262 LIMIT_ONLY_LITERALS = False 263 264 # Whether a table is allowed to be renamed with a db 265 RENAME_TABLE_WITH_DB = True 266 267 # The separator for grouping sets and rollups 268 GROUPINGS_SEP = "," 269 270 # The string used for creating an index on a table 271 INDEX_ON = "ON" 272 273 # Whether join hints should be generated 274 JOIN_HINTS = True 275 276 # Whether table hints should be generated 277 TABLE_HINTS = True 278 279 # Whether query hints should be generated 280 QUERY_HINTS = True 281 282 # What kind of separator to use for query hints 283 QUERY_HINT_SEP = ", " 284 285 # Whether comparing against booleans (e.g. x IS TRUE) is supported 286 IS_BOOL_ALLOWED = True 287 288 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 289 DUPLICATE_KEY_UPDATE_WITH_SET = True 290 291 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 292 LIMIT_IS_TOP = False 293 294 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 295 RETURNING_END = True 296 297 # Whether to generate an unquoted value for EXTRACT's date part argument 298 EXTRACT_ALLOWS_QUOTES = True 299 300 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 301 TZ_TO_WITH_TIME_ZONE = False 302 303 # Whether the NVL2 function is supported 304 NVL2_SUPPORTED = True 305 306 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 307 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 308 309 # Whether VALUES statements can be used as derived tables. 310 # MySQL 5 and Redshift do not allow this, so when False, it will convert 311 # SELECT * VALUES into SELECT UNION 312 VALUES_AS_TABLE = True 313 314 # Whether the word COLUMN is included when adding a column with ALTER TABLE 315 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 316 317 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 318 UNNEST_WITH_ORDINALITY = True 319 320 # Whether FILTER (WHERE cond) can be used for conditional aggregation 321 AGGREGATE_FILTER_SUPPORTED = True 322 323 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 324 SEMI_ANTI_JOIN_WITH_SIDE = True 325 326 # Whether to include the type of a computed column in the CREATE DDL 327 COMPUTED_COLUMN_WITH_TYPE = True 328 329 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 330 SUPPORTS_TABLE_COPY = True 331 332 # Whether parentheses are required around the table sample's expression 333 TABLESAMPLE_REQUIRES_PARENS = True 334 335 # Whether a table sample clause's size needs to be followed by the ROWS keyword 336 TABLESAMPLE_SIZE_IS_ROWS = True 337 338 # The keyword(s) to use when generating a sample clause 339 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 340 341 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 342 TABLESAMPLE_WITH_METHOD = True 343 344 # The keyword to use when specifying the seed of a sample clause 345 TABLESAMPLE_SEED_KEYWORD = "SEED" 346 347 # Whether COLLATE is a function instead of a binary operator 348 COLLATE_IS_FUNC = False 349 350 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 351 DATA_TYPE_SPECIFIERS_ALLOWED = False 352 353 # Whether conditions require booleans WHERE x = 0 vs WHERE x 354 ENSURE_BOOLS = False 355 356 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 357 CTE_RECURSIVE_KEYWORD_REQUIRED = True 358 359 # Whether CONCAT requires >1 arguments 360 SUPPORTS_SINGLE_ARG_CONCAT = True 361 362 # Whether LAST_DAY function supports a date part argument 363 LAST_DAY_SUPPORTS_DATE_PART = True 364 365 # Whether named columns are allowed in table aliases 366 SUPPORTS_TABLE_ALIAS_COLUMNS = True 367 368 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 369 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 370 371 # What delimiter to use for separating JSON key/value pairs 372 JSON_KEY_VALUE_PAIR_SEP = ":" 373 374 # INSERT OVERWRITE TABLE x override 375 INSERT_OVERWRITE = " OVERWRITE TABLE" 376 377 # Whether the SELECT .. INTO syntax is used instead of CTAS 378 SUPPORTS_SELECT_INTO = False 379 380 # Whether UNLOGGED tables can be created 381 SUPPORTS_UNLOGGED_TABLES = False 382 383 # Whether the CREATE TABLE LIKE statement is supported 384 SUPPORTS_CREATE_TABLE_LIKE = True 385 386 # Whether the LikeProperty needs to be specified inside of the schema clause 387 LIKE_PROPERTY_INSIDE_SCHEMA = False 388 389 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 390 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 391 MULTI_ARG_DISTINCT = True 392 393 # Whether the JSON extraction operators expect a value of type JSON 394 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 395 396 # Whether bracketed keys like ["foo"] are supported in JSON paths 397 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 398 399 # Whether to escape keys using single quotes in JSON paths 400 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 401 402 # The JSONPathPart expressions supported by this dialect 403 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 404 405 # Whether any(f(x) for x in array) can be implemented by this dialect 406 CAN_IMPLEMENT_ARRAY_ANY = False 407 408 # Whether the function TO_NUMBER is supported 409 SUPPORTS_TO_NUMBER = True 410 411 # Whether EXCLUDE in window specification is supported 412 SUPPORTS_WINDOW_EXCLUDE = False 413 414 # Whether or not set op modifiers apply to the outer set op or select. 415 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 416 # True means limit 1 happens after the set op, False means it it happens on y. 417 SET_OP_MODIFIERS = True 418 419 # Whether parameters from COPY statement are wrapped in parentheses 420 COPY_PARAMS_ARE_WRAPPED = True 421 422 # Whether values of params are set with "=" token or empty space 423 COPY_PARAMS_EQ_REQUIRED = False 424 425 # Whether COPY statement has INTO keyword 426 COPY_HAS_INTO_KEYWORD = True 427 428 # Whether the conditional TRY(expression) function is supported 429 TRY_SUPPORTED = True 430 431 # Whether the UESCAPE syntax in unicode strings is supported 432 SUPPORTS_UESCAPE = True 433 434 # The keyword to use when generating a star projection with excluded columns 435 STAR_EXCEPT = "EXCEPT" 436 437 # The HEX function name 438 HEX_FUNC = "HEX" 439 440 # The keywords to use when prefixing & separating WITH based properties 441 WITH_PROPERTIES_PREFIX = "WITH" 442 443 # Whether to quote the generated expression of exp.JsonPath 444 QUOTE_JSON_PATH = True 445 446 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 447 PAD_FILL_PATTERN_IS_REQUIRED = False 448 449 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 450 SUPPORTS_EXPLODING_PROJECTIONS = True 451 452 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 453 ARRAY_CONCAT_IS_VAR_LEN = True 454 455 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 456 SUPPORTS_CONVERT_TIMEZONE = False 457 458 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 459 SUPPORTS_MEDIAN = True 460 461 # Whether UNIX_SECONDS(timestamp) is supported 462 SUPPORTS_UNIX_SECONDS = False 463 464 # Whether to wrap <props> in `AlterSet`, e.g., ALTER ... SET (<props>) 465 ALTER_SET_WRAPPED = False 466 467 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 468 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 469 470 # The function name of the exp.ArraySize expression 471 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 472 473 # The syntax to use when altering the type of a column 474 ALTER_SET_TYPE = "SET DATA TYPE" 475 476 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 477 # None -> Doesn't support it at all 478 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 479 # True (Postgres) -> Explicitly requires it 480 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 481 482 TYPE_MAPPING = { 483 exp.DataType.Type.DATETIME2: "TIMESTAMP", 484 exp.DataType.Type.NCHAR: "CHAR", 485 exp.DataType.Type.NVARCHAR: "VARCHAR", 486 exp.DataType.Type.MEDIUMTEXT: "TEXT", 487 exp.DataType.Type.LONGTEXT: "TEXT", 488 exp.DataType.Type.TINYTEXT: "TEXT", 489 exp.DataType.Type.BLOB: "VARBINARY", 490 exp.DataType.Type.MEDIUMBLOB: "BLOB", 491 exp.DataType.Type.LONGBLOB: "BLOB", 492 exp.DataType.Type.TINYBLOB: "BLOB", 493 exp.DataType.Type.INET: "INET", 494 exp.DataType.Type.ROWVERSION: "VARBINARY", 495 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 496 } 497 498 TIME_PART_SINGULARS = { 499 "MICROSECONDS": "MICROSECOND", 500 "SECONDS": "SECOND", 501 "MINUTES": "MINUTE", 502 "HOURS": "HOUR", 503 "DAYS": "DAY", 504 "WEEKS": "WEEK", 505 "MONTHS": "MONTH", 506 "QUARTERS": "QUARTER", 507 "YEARS": "YEAR", 508 } 509 510 AFTER_HAVING_MODIFIER_TRANSFORMS = { 511 "cluster": lambda self, e: self.sql(e, "cluster"), 512 "distribute": lambda self, e: self.sql(e, "distribute"), 513 "sort": lambda self, e: self.sql(e, "sort"), 514 "windows": lambda self, e: ( 515 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 516 if e.args.get("windows") 517 else "" 518 ), 519 "qualify": lambda self, e: self.sql(e, "qualify"), 520 } 521 522 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 523 524 STRUCT_DELIMITER = ("<", ">") 525 526 PARAMETER_TOKEN = "@" 527 NAMED_PLACEHOLDER_TOKEN = ":" 528 529 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 530 531 PROPERTIES_LOCATION = { 532 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 534 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 538 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 540 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 542 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 543 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 544 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 546 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 547 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 549 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 550 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 552 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 556 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.EnviromentProperty: exp.Properties.Location.POST_SCHEMA, 558 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 559 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 560 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 561 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 562 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 563 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 564 exp.HeapProperty: exp.Properties.Location.POST_WITH, 565 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 567 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 570 exp.JournalProperty: exp.Properties.Location.POST_NAME, 571 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 576 exp.LogProperty: exp.Properties.Location.POST_NAME, 577 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 578 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 579 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 580 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 581 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 582 exp.Order: exp.Properties.Location.POST_SCHEMA, 583 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 584 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 585 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 586 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 587 exp.Property: exp.Properties.Location.POST_WITH, 588 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 593 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 594 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 595 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 596 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 597 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 598 exp.Set: exp.Properties.Location.POST_SCHEMA, 599 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 600 exp.SetProperty: exp.Properties.Location.POST_CREATE, 601 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 602 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 603 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 604 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 605 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 606 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 607 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 608 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 609 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 610 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 611 exp.Tags: exp.Properties.Location.POST_WITH, 612 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 613 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 614 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 615 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 616 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 617 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 618 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 619 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 620 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 621 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 622 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 623 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 624 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 625 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 626 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 627 } 628 629 # Keywords that can't be used as unquoted identifier names 630 RESERVED_KEYWORDS: t.Set[str] = set() 631 632 # Expressions whose comments are separated from them for better formatting 633 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 634 exp.Command, 635 exp.Create, 636 exp.Describe, 637 exp.Delete, 638 exp.Drop, 639 exp.From, 640 exp.Insert, 641 exp.Join, 642 exp.MultitableInserts, 643 exp.Select, 644 exp.SetOperation, 645 exp.Update, 646 exp.Where, 647 exp.With, 648 ) 649 650 # Expressions that should not have their comments generated in maybe_comment 651 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 652 exp.Binary, 653 exp.SetOperation, 654 ) 655 656 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 657 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 658 exp.Column, 659 exp.Literal, 660 exp.Neg, 661 exp.Paren, 662 ) 663 664 PARAMETERIZABLE_TEXT_TYPES = { 665 exp.DataType.Type.NVARCHAR, 666 exp.DataType.Type.VARCHAR, 667 exp.DataType.Type.CHAR, 668 exp.DataType.Type.NCHAR, 669 } 670 671 # Expressions that need to have all CTEs under them bubbled up to them 672 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 673 674 RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS: t.Tuple[t.Type[exp.Expression], ...] = () 675 676 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 677 678 __slots__ = ( 679 "pretty", 680 "identify", 681 "normalize", 682 "pad", 683 "_indent", 684 "normalize_functions", 685 "unsupported_level", 686 "max_unsupported", 687 "leading_comma", 688 "max_text_width", 689 "comments", 690 "dialect", 691 "unsupported_messages", 692 "_escaped_quote_end", 693 "_escaped_identifier_end", 694 "_next_name", 695 "_identifier_start", 696 "_identifier_end", 697 "_quote_json_path_key_using_brackets", 698 ) 699 700 def __init__( 701 self, 702 pretty: t.Optional[bool] = None, 703 identify: str | bool = False, 704 normalize: bool = False, 705 pad: int = 2, 706 indent: int = 2, 707 normalize_functions: t.Optional[str | bool] = None, 708 unsupported_level: ErrorLevel = ErrorLevel.WARN, 709 max_unsupported: int = 3, 710 leading_comma: bool = False, 711 max_text_width: int = 80, 712 comments: bool = True, 713 dialect: DialectType = None, 714 ): 715 import sqlglot 716 from sqlglot.dialects import Dialect 717 718 self.pretty = pretty if pretty is not None else sqlglot.pretty 719 self.identify = identify 720 self.normalize = normalize 721 self.pad = pad 722 self._indent = indent 723 self.unsupported_level = unsupported_level 724 self.max_unsupported = max_unsupported 725 self.leading_comma = leading_comma 726 self.max_text_width = max_text_width 727 self.comments = comments 728 self.dialect = Dialect.get_or_raise(dialect) 729 730 # This is both a Dialect property and a Generator argument, so we prioritize the latter 731 self.normalize_functions = ( 732 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 733 ) 734 735 self.unsupported_messages: t.List[str] = [] 736 self._escaped_quote_end: str = ( 737 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 738 ) 739 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 740 741 self._next_name = name_sequence("_t") 742 743 self._identifier_start = self.dialect.IDENTIFIER_START 744 self._identifier_end = self.dialect.IDENTIFIER_END 745 746 self._quote_json_path_key_using_brackets = True 747 748 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 749 """ 750 Generates the SQL string corresponding to the given syntax tree. 751 752 Args: 753 expression: The syntax tree. 754 copy: Whether to copy the expression. The generator performs mutations so 755 it is safer to copy. 756 757 Returns: 758 The SQL string corresponding to `expression`. 759 """ 760 if copy: 761 expression = expression.copy() 762 763 expression = self.preprocess(expression) 764 765 self.unsupported_messages = [] 766 sql = self.sql(expression).strip() 767 768 if self.pretty: 769 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 770 771 if self.unsupported_level == ErrorLevel.IGNORE: 772 return sql 773 774 if self.unsupported_level == ErrorLevel.WARN: 775 for msg in self.unsupported_messages: 776 logger.warning(msg) 777 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 778 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 779 780 return sql 781 782 def preprocess(self, expression: exp.Expression) -> exp.Expression: 783 """Apply generic preprocessing transformations to a given expression.""" 784 expression = self._move_ctes_to_top_level(expression) 785 786 if self.ENSURE_BOOLS: 787 from sqlglot.transforms import ensure_bools 788 789 expression = ensure_bools(expression) 790 791 return expression 792 793 def _move_ctes_to_top_level(self, expression: E) -> E: 794 if ( 795 not expression.parent 796 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 797 and any(node.parent is not expression for node in expression.find_all(exp.With)) 798 ): 799 from sqlglot.transforms import move_ctes_to_top_level 800 801 expression = move_ctes_to_top_level(expression) 802 return expression 803 804 def unsupported(self, message: str) -> None: 805 if self.unsupported_level == ErrorLevel.IMMEDIATE: 806 raise UnsupportedError(message) 807 self.unsupported_messages.append(message) 808 809 def sep(self, sep: str = " ") -> str: 810 return f"{sep.strip()}\n" if self.pretty else sep 811 812 def seg(self, sql: str, sep: str = " ") -> str: 813 return f"{self.sep(sep)}{sql}" 814 815 def sanitize_comment(self, comment: str) -> str: 816 comment = " " + comment if comment[0].strip() else comment 817 comment = comment + " " if comment[-1].strip() else comment 818 819 if not self.dialect.tokenizer_class.NESTED_COMMENTS: 820 # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */ 821 comment = comment.replace("*/", "* /") 822 823 return comment 824 825 def maybe_comment( 826 self, 827 sql: str, 828 expression: t.Optional[exp.Expression] = None, 829 comments: t.Optional[t.List[str]] = None, 830 separated: bool = False, 831 ) -> str: 832 comments = ( 833 ((expression and expression.comments) if comments is None else comments) # type: ignore 834 if self.comments 835 else None 836 ) 837 838 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 839 return sql 840 841 comments_sql = " ".join( 842 f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment 843 ) 844 845 if not comments_sql: 846 return sql 847 848 comments_sql = self._replace_line_breaks(comments_sql) 849 850 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 851 return ( 852 f"{self.sep()}{comments_sql}{sql}" 853 if not sql or sql[0].isspace() 854 else f"{comments_sql}{self.sep()}{sql}" 855 ) 856 857 return f"{sql} {comments_sql}" 858 859 def wrap(self, expression: exp.Expression | str) -> str: 860 this_sql = ( 861 self.sql(expression) 862 if isinstance(expression, exp.UNWRAPPED_QUERIES) 863 else self.sql(expression, "this") 864 ) 865 if not this_sql: 866 return "()" 867 868 this_sql = self.indent(this_sql, level=1, pad=0) 869 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 870 871 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 872 original = self.identify 873 self.identify = False 874 result = func(*args, **kwargs) 875 self.identify = original 876 return result 877 878 def normalize_func(self, name: str) -> str: 879 if self.normalize_functions == "upper" or self.normalize_functions is True: 880 return name.upper() 881 if self.normalize_functions == "lower": 882 return name.lower() 883 return name 884 885 def indent( 886 self, 887 sql: str, 888 level: int = 0, 889 pad: t.Optional[int] = None, 890 skip_first: bool = False, 891 skip_last: bool = False, 892 ) -> str: 893 if not self.pretty or not sql: 894 return sql 895 896 pad = self.pad if pad is None else pad 897 lines = sql.split("\n") 898 899 return "\n".join( 900 ( 901 line 902 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 903 else f"{' ' * (level * self._indent + pad)}{line}" 904 ) 905 for i, line in enumerate(lines) 906 ) 907 908 def sql( 909 self, 910 expression: t.Optional[str | exp.Expression], 911 key: t.Optional[str] = None, 912 comment: bool = True, 913 ) -> str: 914 if not expression: 915 return "" 916 917 if isinstance(expression, str): 918 return expression 919 920 if key: 921 value = expression.args.get(key) 922 if value: 923 return self.sql(value) 924 return "" 925 926 transform = self.TRANSFORMS.get(expression.__class__) 927 928 if callable(transform): 929 sql = transform(self, expression) 930 elif isinstance(expression, exp.Expression): 931 exp_handler_name = f"{expression.key}_sql" 932 933 if hasattr(self, exp_handler_name): 934 sql = getattr(self, exp_handler_name)(expression) 935 elif isinstance(expression, exp.Func): 936 sql = self.function_fallback_sql(expression) 937 elif isinstance(expression, exp.Property): 938 sql = self.property_sql(expression) 939 else: 940 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 941 else: 942 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 943 944 return self.maybe_comment(sql, expression) if self.comments and comment else sql 945 946 def uncache_sql(self, expression: exp.Uncache) -> str: 947 table = self.sql(expression, "this") 948 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 949 return f"UNCACHE TABLE{exists_sql} {table}" 950 951 def cache_sql(self, expression: exp.Cache) -> str: 952 lazy = " LAZY" if expression.args.get("lazy") else "" 953 table = self.sql(expression, "this") 954 options = expression.args.get("options") 955 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 956 sql = self.sql(expression, "expression") 957 sql = f" AS{self.sep()}{sql}" if sql else "" 958 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 959 return self.prepend_ctes(expression, sql) 960 961 def characterset_sql(self, expression: exp.CharacterSet) -> str: 962 if isinstance(expression.parent, exp.Cast): 963 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 964 default = "DEFAULT " if expression.args.get("default") else "" 965 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 966 967 def column_parts(self, expression: exp.Column) -> str: 968 return ".".join( 969 self.sql(part) 970 for part in ( 971 expression.args.get("catalog"), 972 expression.args.get("db"), 973 expression.args.get("table"), 974 expression.args.get("this"), 975 ) 976 if part 977 ) 978 979 def column_sql(self, expression: exp.Column) -> str: 980 join_mark = " (+)" if expression.args.get("join_mark") else "" 981 982 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 983 join_mark = "" 984 self.unsupported("Outer join syntax using the (+) operator is not supported.") 985 986 return f"{self.column_parts(expression)}{join_mark}" 987 988 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 989 this = self.sql(expression, "this") 990 this = f" {this}" if this else "" 991 position = self.sql(expression, "position") 992 return f"{position}{this}" 993 994 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 995 column = self.sql(expression, "this") 996 kind = self.sql(expression, "kind") 997 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 998 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 999 kind = f"{sep}{kind}" if kind else "" 1000 constraints = f" {constraints}" if constraints else "" 1001 position = self.sql(expression, "position") 1002 position = f" {position}" if position else "" 1003 1004 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1005 kind = "" 1006 1007 return f"{exists}{column}{kind}{constraints}{position}" 1008 1009 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 1010 this = self.sql(expression, "this") 1011 kind_sql = self.sql(expression, "kind").strip() 1012 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 1013 1014 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1015 this = self.sql(expression, "this") 1016 if expression.args.get("not_null"): 1017 persisted = " PERSISTED NOT NULL" 1018 elif expression.args.get("persisted"): 1019 persisted = " PERSISTED" 1020 else: 1021 persisted = "" 1022 return f"AS {this}{persisted}" 1023 1024 def autoincrementcolumnconstraint_sql(self, _) -> str: 1025 return self.token_sql(TokenType.AUTO_INCREMENT) 1026 1027 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1028 if isinstance(expression.this, list): 1029 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1030 else: 1031 this = self.sql(expression, "this") 1032 1033 return f"COMPRESS {this}" 1034 1035 def generatedasidentitycolumnconstraint_sql( 1036 self, expression: exp.GeneratedAsIdentityColumnConstraint 1037 ) -> str: 1038 this = "" 1039 if expression.this is not None: 1040 on_null = " ON NULL" if expression.args.get("on_null") else "" 1041 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1042 1043 start = expression.args.get("start") 1044 start = f"START WITH {start}" if start else "" 1045 increment = expression.args.get("increment") 1046 increment = f" INCREMENT BY {increment}" if increment else "" 1047 minvalue = expression.args.get("minvalue") 1048 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1049 maxvalue = expression.args.get("maxvalue") 1050 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1051 cycle = expression.args.get("cycle") 1052 cycle_sql = "" 1053 1054 if cycle is not None: 1055 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1056 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1057 1058 sequence_opts = "" 1059 if start or increment or cycle_sql: 1060 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1061 sequence_opts = f" ({sequence_opts.strip()})" 1062 1063 expr = self.sql(expression, "expression") 1064 expr = f"({expr})" if expr else "IDENTITY" 1065 1066 return f"GENERATED{this} AS {expr}{sequence_opts}" 1067 1068 def generatedasrowcolumnconstraint_sql( 1069 self, expression: exp.GeneratedAsRowColumnConstraint 1070 ) -> str: 1071 start = "START" if expression.args.get("start") else "END" 1072 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1073 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1074 1075 def periodforsystemtimeconstraint_sql( 1076 self, expression: exp.PeriodForSystemTimeConstraint 1077 ) -> str: 1078 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1079 1080 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1081 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1082 1083 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1084 return f"AS {self.sql(expression, 'this')}" 1085 1086 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1087 desc = expression.args.get("desc") 1088 if desc is not None: 1089 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1090 options = self.expressions(expression, key="options", flat=True, sep=" ") 1091 options = f" {options}" if options else "" 1092 return f"PRIMARY KEY{options}" 1093 1094 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1095 this = self.sql(expression, "this") 1096 this = f" {this}" if this else "" 1097 index_type = expression.args.get("index_type") 1098 index_type = f" USING {index_type}" if index_type else "" 1099 on_conflict = self.sql(expression, "on_conflict") 1100 on_conflict = f" {on_conflict}" if on_conflict else "" 1101 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1102 options = self.expressions(expression, key="options", flat=True, sep=" ") 1103 options = f" {options}" if options else "" 1104 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}" 1105 1106 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1107 return self.sql(expression, "this") 1108 1109 def create_sql(self, expression: exp.Create) -> str: 1110 kind = self.sql(expression, "kind") 1111 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1112 properties = expression.args.get("properties") 1113 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1114 1115 this = self.createable_sql(expression, properties_locs) 1116 1117 properties_sql = "" 1118 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1119 exp.Properties.Location.POST_WITH 1120 ): 1121 properties_sql = self.sql( 1122 exp.Properties( 1123 expressions=[ 1124 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1125 *properties_locs[exp.Properties.Location.POST_WITH], 1126 ] 1127 ) 1128 ) 1129 1130 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1131 properties_sql = self.sep() + properties_sql 1132 elif not self.pretty: 1133 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1134 properties_sql = f" {properties_sql}" 1135 1136 begin = " BEGIN" if expression.args.get("begin") else "" 1137 end = " END" if expression.args.get("end") else "" 1138 1139 expression_sql = self.sql(expression, "expression") 1140 if expression_sql: 1141 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1142 1143 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1144 postalias_props_sql = "" 1145 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1146 postalias_props_sql = self.properties( 1147 exp.Properties( 1148 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1149 ), 1150 wrapped=False, 1151 ) 1152 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1153 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1154 1155 postindex_props_sql = "" 1156 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1157 postindex_props_sql = self.properties( 1158 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1159 wrapped=False, 1160 prefix=" ", 1161 ) 1162 1163 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1164 indexes = f" {indexes}" if indexes else "" 1165 index_sql = indexes + postindex_props_sql 1166 1167 replace = " OR REPLACE" if expression.args.get("replace") else "" 1168 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1169 unique = " UNIQUE" if expression.args.get("unique") else "" 1170 1171 clustered = expression.args.get("clustered") 1172 if clustered is None: 1173 clustered_sql = "" 1174 elif clustered: 1175 clustered_sql = " CLUSTERED COLUMNSTORE" 1176 else: 1177 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1178 1179 postcreate_props_sql = "" 1180 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1181 postcreate_props_sql = self.properties( 1182 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1183 sep=" ", 1184 prefix=" ", 1185 wrapped=False, 1186 ) 1187 1188 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1189 1190 postexpression_props_sql = "" 1191 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1192 postexpression_props_sql = self.properties( 1193 exp.Properties( 1194 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1195 ), 1196 sep=" ", 1197 prefix=" ", 1198 wrapped=False, 1199 ) 1200 1201 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1202 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1203 no_schema_binding = ( 1204 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1205 ) 1206 1207 clone = self.sql(expression, "clone") 1208 clone = f" {clone}" if clone else "" 1209 1210 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1211 properties_expression = f"{expression_sql}{properties_sql}" 1212 else: 1213 properties_expression = f"{properties_sql}{expression_sql}" 1214 1215 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1216 return self.prepend_ctes(expression, expression_sql) 1217 1218 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1219 start = self.sql(expression, "start") 1220 start = f"START WITH {start}" if start else "" 1221 increment = self.sql(expression, "increment") 1222 increment = f" INCREMENT BY {increment}" if increment else "" 1223 minvalue = self.sql(expression, "minvalue") 1224 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1225 maxvalue = self.sql(expression, "maxvalue") 1226 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1227 owned = self.sql(expression, "owned") 1228 owned = f" OWNED BY {owned}" if owned else "" 1229 1230 cache = expression.args.get("cache") 1231 if cache is None: 1232 cache_str = "" 1233 elif cache is True: 1234 cache_str = " CACHE" 1235 else: 1236 cache_str = f" CACHE {cache}" 1237 1238 options = self.expressions(expression, key="options", flat=True, sep=" ") 1239 options = f" {options}" if options else "" 1240 1241 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1242 1243 def clone_sql(self, expression: exp.Clone) -> str: 1244 this = self.sql(expression, "this") 1245 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1246 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1247 return f"{shallow}{keyword} {this}" 1248 1249 def describe_sql(self, expression: exp.Describe) -> str: 1250 style = expression.args.get("style") 1251 style = f" {style}" if style else "" 1252 partition = self.sql(expression, "partition") 1253 partition = f" {partition}" if partition else "" 1254 format = self.sql(expression, "format") 1255 format = f" {format}" if format else "" 1256 1257 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1258 1259 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1260 tag = self.sql(expression, "tag") 1261 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1262 1263 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1264 with_ = self.sql(expression, "with") 1265 if with_: 1266 sql = f"{with_}{self.sep()}{sql}" 1267 return sql 1268 1269 def with_sql(self, expression: exp.With) -> str: 1270 sql = self.expressions(expression, flat=True) 1271 recursive = ( 1272 "RECURSIVE " 1273 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1274 else "" 1275 ) 1276 search = self.sql(expression, "search") 1277 search = f" {search}" if search else "" 1278 1279 return f"WITH {recursive}{sql}{search}" 1280 1281 def cte_sql(self, expression: exp.CTE) -> str: 1282 alias = expression.args.get("alias") 1283 if alias: 1284 alias.add_comments(expression.pop_comments()) 1285 1286 alias_sql = self.sql(expression, "alias") 1287 1288 materialized = expression.args.get("materialized") 1289 if materialized is False: 1290 materialized = "NOT MATERIALIZED " 1291 elif materialized: 1292 materialized = "MATERIALIZED " 1293 1294 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1295 1296 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1297 alias = self.sql(expression, "this") 1298 columns = self.expressions(expression, key="columns", flat=True) 1299 columns = f"({columns})" if columns else "" 1300 1301 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1302 columns = "" 1303 self.unsupported("Named columns are not supported in table alias.") 1304 1305 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1306 alias = self._next_name() 1307 1308 return f"{alias}{columns}" 1309 1310 def bitstring_sql(self, expression: exp.BitString) -> str: 1311 this = self.sql(expression, "this") 1312 if self.dialect.BIT_START: 1313 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1314 return f"{int(this, 2)}" 1315 1316 def hexstring_sql( 1317 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1318 ) -> str: 1319 this = self.sql(expression, "this") 1320 is_integer_type = expression.args.get("is_integer") 1321 1322 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1323 not self.dialect.HEX_START and not binary_function_repr 1324 ): 1325 # Integer representation will be returned if: 1326 # - The read dialect treats the hex value as integer literal but not the write 1327 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1328 return f"{int(this, 16)}" 1329 1330 if not is_integer_type: 1331 # Read dialect treats the hex value as BINARY/BLOB 1332 if binary_function_repr: 1333 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1334 return self.func(binary_function_repr, exp.Literal.string(this)) 1335 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1336 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1337 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1338 1339 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1340 1341 def bytestring_sql(self, expression: exp.ByteString) -> str: 1342 this = self.sql(expression, "this") 1343 if self.dialect.BYTE_START: 1344 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1345 return this 1346 1347 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1348 this = self.sql(expression, "this") 1349 escape = expression.args.get("escape") 1350 1351 if self.dialect.UNICODE_START: 1352 escape_substitute = r"\\\1" 1353 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1354 else: 1355 escape_substitute = r"\\u\1" 1356 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1357 1358 if escape: 1359 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1360 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1361 else: 1362 escape_pattern = ESCAPED_UNICODE_RE 1363 escape_sql = "" 1364 1365 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1366 this = escape_pattern.sub(escape_substitute, this) 1367 1368 return f"{left_quote}{this}{right_quote}{escape_sql}" 1369 1370 def rawstring_sql(self, expression: exp.RawString) -> str: 1371 string = expression.this 1372 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1373 string = string.replace("\\", "\\\\") 1374 1375 string = self.escape_str(string, escape_backslash=False) 1376 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1377 1378 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1379 this = self.sql(expression, "this") 1380 specifier = self.sql(expression, "expression") 1381 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1382 return f"{this}{specifier}" 1383 1384 def datatype_sql(self, expression: exp.DataType) -> str: 1385 nested = "" 1386 values = "" 1387 interior = self.expressions(expression, flat=True) 1388 1389 type_value = expression.this 1390 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1391 type_sql = self.sql(expression, "kind") 1392 else: 1393 type_sql = ( 1394 self.TYPE_MAPPING.get(type_value, type_value.value) 1395 if isinstance(type_value, exp.DataType.Type) 1396 else type_value 1397 ) 1398 1399 if interior: 1400 if expression.args.get("nested"): 1401 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1402 if expression.args.get("values") is not None: 1403 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1404 values = self.expressions(expression, key="values", flat=True) 1405 values = f"{delimiters[0]}{values}{delimiters[1]}" 1406 elif type_value == exp.DataType.Type.INTERVAL: 1407 nested = f" {interior}" 1408 else: 1409 nested = f"({interior})" 1410 1411 type_sql = f"{type_sql}{nested}{values}" 1412 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1413 exp.DataType.Type.TIMETZ, 1414 exp.DataType.Type.TIMESTAMPTZ, 1415 ): 1416 type_sql = f"{type_sql} WITH TIME ZONE" 1417 1418 return type_sql 1419 1420 def directory_sql(self, expression: exp.Directory) -> str: 1421 local = "LOCAL " if expression.args.get("local") else "" 1422 row_format = self.sql(expression, "row_format") 1423 row_format = f" {row_format}" if row_format else "" 1424 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1425 1426 def delete_sql(self, expression: exp.Delete) -> str: 1427 this = self.sql(expression, "this") 1428 this = f" FROM {this}" if this else "" 1429 using = self.sql(expression, "using") 1430 using = f" USING {using}" if using else "" 1431 cluster = self.sql(expression, "cluster") 1432 cluster = f" {cluster}" if cluster else "" 1433 where = self.sql(expression, "where") 1434 returning = self.sql(expression, "returning") 1435 limit = self.sql(expression, "limit") 1436 tables = self.expressions(expression, key="tables") 1437 tables = f" {tables}" if tables else "" 1438 if self.RETURNING_END: 1439 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1440 else: 1441 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1442 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1443 1444 def drop_sql(self, expression: exp.Drop) -> str: 1445 this = self.sql(expression, "this") 1446 expressions = self.expressions(expression, flat=True) 1447 expressions = f" ({expressions})" if expressions else "" 1448 kind = expression.args["kind"] 1449 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1450 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1451 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1452 on_cluster = self.sql(expression, "cluster") 1453 on_cluster = f" {on_cluster}" if on_cluster else "" 1454 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1455 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1456 cascade = " CASCADE" if expression.args.get("cascade") else "" 1457 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1458 purge = " PURGE" if expression.args.get("purge") else "" 1459 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1460 1461 def set_operation(self, expression: exp.SetOperation) -> str: 1462 op_type = type(expression) 1463 op_name = op_type.key.upper() 1464 1465 distinct = expression.args.get("distinct") 1466 if ( 1467 distinct is False 1468 and op_type in (exp.Except, exp.Intersect) 1469 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1470 ): 1471 self.unsupported(f"{op_name} ALL is not supported") 1472 1473 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1474 1475 if distinct is None: 1476 distinct = default_distinct 1477 if distinct is None: 1478 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1479 1480 if distinct is default_distinct: 1481 distinct_or_all = "" 1482 else: 1483 distinct_or_all = " DISTINCT" if distinct else " ALL" 1484 1485 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 1486 side_kind = f"{side_kind} " if side_kind else "" 1487 1488 by_name = " BY NAME" if expression.args.get("by_name") else "" 1489 on = self.expressions(expression, key="on", flat=True) 1490 on = f" ON ({on})" if on else "" 1491 1492 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}" 1493 1494 def set_operations(self, expression: exp.SetOperation) -> str: 1495 if not self.SET_OP_MODIFIERS: 1496 limit = expression.args.get("limit") 1497 order = expression.args.get("order") 1498 1499 if limit or order: 1500 select = self._move_ctes_to_top_level( 1501 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1502 ) 1503 1504 if limit: 1505 select = select.limit(limit.pop(), copy=False) 1506 if order: 1507 select = select.order_by(order.pop(), copy=False) 1508 return self.sql(select) 1509 1510 sqls: t.List[str] = [] 1511 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1512 1513 while stack: 1514 node = stack.pop() 1515 1516 if isinstance(node, exp.SetOperation): 1517 stack.append(node.expression) 1518 stack.append( 1519 self.maybe_comment( 1520 self.set_operation(node), comments=node.comments, separated=True 1521 ) 1522 ) 1523 stack.append(node.this) 1524 else: 1525 sqls.append(self.sql(node)) 1526 1527 this = self.sep().join(sqls) 1528 this = self.query_modifiers(expression, this) 1529 return self.prepend_ctes(expression, this) 1530 1531 def fetch_sql(self, expression: exp.Fetch) -> str: 1532 direction = expression.args.get("direction") 1533 direction = f" {direction}" if direction else "" 1534 count = self.sql(expression, "count") 1535 count = f" {count}" if count else "" 1536 limit_options = self.sql(expression, "limit_options") 1537 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1538 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1539 1540 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1541 percent = " PERCENT" if expression.args.get("percent") else "" 1542 rows = " ROWS" if expression.args.get("rows") else "" 1543 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1544 if not with_ties and rows: 1545 with_ties = " ONLY" 1546 return f"{percent}{rows}{with_ties}" 1547 1548 def filter_sql(self, expression: exp.Filter) -> str: 1549 if self.AGGREGATE_FILTER_SUPPORTED: 1550 this = self.sql(expression, "this") 1551 where = self.sql(expression, "expression").strip() 1552 return f"{this} FILTER({where})" 1553 1554 agg = expression.this 1555 agg_arg = agg.this 1556 cond = expression.expression.this 1557 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1558 return self.sql(agg) 1559 1560 def hint_sql(self, expression: exp.Hint) -> str: 1561 if not self.QUERY_HINTS: 1562 self.unsupported("Hints are not supported") 1563 return "" 1564 1565 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1566 1567 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1568 using = self.sql(expression, "using") 1569 using = f" USING {using}" if using else "" 1570 columns = self.expressions(expression, key="columns", flat=True) 1571 columns = f"({columns})" if columns else "" 1572 partition_by = self.expressions(expression, key="partition_by", flat=True) 1573 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1574 where = self.sql(expression, "where") 1575 include = self.expressions(expression, key="include", flat=True) 1576 if include: 1577 include = f" INCLUDE ({include})" 1578 with_storage = self.expressions(expression, key="with_storage", flat=True) 1579 with_storage = f" WITH ({with_storage})" if with_storage else "" 1580 tablespace = self.sql(expression, "tablespace") 1581 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1582 on = self.sql(expression, "on") 1583 on = f" ON {on}" if on else "" 1584 1585 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1586 1587 def index_sql(self, expression: exp.Index) -> str: 1588 unique = "UNIQUE " if expression.args.get("unique") else "" 1589 primary = "PRIMARY " if expression.args.get("primary") else "" 1590 amp = "AMP " if expression.args.get("amp") else "" 1591 name = self.sql(expression, "this") 1592 name = f"{name} " if name else "" 1593 table = self.sql(expression, "table") 1594 table = f"{self.INDEX_ON} {table}" if table else "" 1595 1596 index = "INDEX " if not table else "" 1597 1598 params = self.sql(expression, "params") 1599 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1600 1601 def identifier_sql(self, expression: exp.Identifier) -> str: 1602 text = expression.name 1603 lower = text.lower() 1604 text = lower if self.normalize and not expression.quoted else text 1605 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1606 if ( 1607 expression.quoted 1608 or self.dialect.can_identify(text, self.identify) 1609 or lower in self.RESERVED_KEYWORDS 1610 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1611 ): 1612 text = f"{self._identifier_start}{text}{self._identifier_end}" 1613 return text 1614 1615 def hex_sql(self, expression: exp.Hex) -> str: 1616 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1617 if self.dialect.HEX_LOWERCASE: 1618 text = self.func("LOWER", text) 1619 1620 return text 1621 1622 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1623 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1624 if not self.dialect.HEX_LOWERCASE: 1625 text = self.func("LOWER", text) 1626 return text 1627 1628 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1629 input_format = self.sql(expression, "input_format") 1630 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1631 output_format = self.sql(expression, "output_format") 1632 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1633 return self.sep().join((input_format, output_format)) 1634 1635 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1636 string = self.sql(exp.Literal.string(expression.name)) 1637 return f"{prefix}{string}" 1638 1639 def partition_sql(self, expression: exp.Partition) -> str: 1640 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1641 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1642 1643 def properties_sql(self, expression: exp.Properties) -> str: 1644 root_properties = [] 1645 with_properties = [] 1646 1647 for p in expression.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc == exp.Properties.Location.POST_WITH: 1650 with_properties.append(p) 1651 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1652 root_properties.append(p) 1653 1654 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1655 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1656 1657 if root_props and with_props and not self.pretty: 1658 with_props = " " + with_props 1659 1660 return root_props + with_props 1661 1662 def root_properties(self, properties: exp.Properties) -> str: 1663 if properties.expressions: 1664 return self.expressions(properties, indent=False, sep=" ") 1665 return "" 1666 1667 def properties( 1668 self, 1669 properties: exp.Properties, 1670 prefix: str = "", 1671 sep: str = ", ", 1672 suffix: str = "", 1673 wrapped: bool = True, 1674 ) -> str: 1675 if properties.expressions: 1676 expressions = self.expressions(properties, sep=sep, indent=False) 1677 if expressions: 1678 expressions = self.wrap(expressions) if wrapped else expressions 1679 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1680 return "" 1681 1682 def with_properties(self, properties: exp.Properties) -> str: 1683 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1684 1685 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1686 properties_locs = defaultdict(list) 1687 for p in properties.expressions: 1688 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1689 if p_loc != exp.Properties.Location.UNSUPPORTED: 1690 properties_locs[p_loc].append(p) 1691 else: 1692 self.unsupported(f"Unsupported property {p.key}") 1693 1694 return properties_locs 1695 1696 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1697 if isinstance(expression.this, exp.Dot): 1698 return self.sql(expression, "this") 1699 return f"'{expression.name}'" if string_key else expression.name 1700 1701 def property_sql(self, expression: exp.Property) -> str: 1702 property_cls = expression.__class__ 1703 if property_cls == exp.Property: 1704 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1705 1706 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1707 if not property_name: 1708 self.unsupported(f"Unsupported property {expression.key}") 1709 1710 return f"{property_name}={self.sql(expression, 'this')}" 1711 1712 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1713 if self.SUPPORTS_CREATE_TABLE_LIKE: 1714 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1715 options = f" {options}" if options else "" 1716 1717 like = f"LIKE {self.sql(expression, 'this')}{options}" 1718 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1719 like = f"({like})" 1720 1721 return like 1722 1723 if expression.expressions: 1724 self.unsupported("Transpilation of LIKE property options is unsupported") 1725 1726 select = exp.select("*").from_(expression.this).limit(0) 1727 return f"AS {self.sql(select)}" 1728 1729 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1730 no = "NO " if expression.args.get("no") else "" 1731 protection = " PROTECTION" if expression.args.get("protection") else "" 1732 return f"{no}FALLBACK{protection}" 1733 1734 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1735 no = "NO " if expression.args.get("no") else "" 1736 local = expression.args.get("local") 1737 local = f"{local} " if local else "" 1738 dual = "DUAL " if expression.args.get("dual") else "" 1739 before = "BEFORE " if expression.args.get("before") else "" 1740 after = "AFTER " if expression.args.get("after") else "" 1741 return f"{no}{local}{dual}{before}{after}JOURNAL" 1742 1743 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1744 freespace = self.sql(expression, "this") 1745 percent = " PERCENT" if expression.args.get("percent") else "" 1746 return f"FREESPACE={freespace}{percent}" 1747 1748 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1749 if expression.args.get("default"): 1750 property = "DEFAULT" 1751 elif expression.args.get("on"): 1752 property = "ON" 1753 else: 1754 property = "OFF" 1755 return f"CHECKSUM={property}" 1756 1757 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1758 if expression.args.get("no"): 1759 return "NO MERGEBLOCKRATIO" 1760 if expression.args.get("default"): 1761 return "DEFAULT MERGEBLOCKRATIO" 1762 1763 percent = " PERCENT" if expression.args.get("percent") else "" 1764 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1765 1766 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1767 default = expression.args.get("default") 1768 minimum = expression.args.get("minimum") 1769 maximum = expression.args.get("maximum") 1770 if default or minimum or maximum: 1771 if default: 1772 prop = "DEFAULT" 1773 elif minimum: 1774 prop = "MINIMUM" 1775 else: 1776 prop = "MAXIMUM" 1777 return f"{prop} DATABLOCKSIZE" 1778 units = expression.args.get("units") 1779 units = f" {units}" if units else "" 1780 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1781 1782 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1783 autotemp = expression.args.get("autotemp") 1784 always = expression.args.get("always") 1785 default = expression.args.get("default") 1786 manual = expression.args.get("manual") 1787 never = expression.args.get("never") 1788 1789 if autotemp is not None: 1790 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1791 elif always: 1792 prop = "ALWAYS" 1793 elif default: 1794 prop = "DEFAULT" 1795 elif manual: 1796 prop = "MANUAL" 1797 elif never: 1798 prop = "NEVER" 1799 return f"BLOCKCOMPRESSION={prop}" 1800 1801 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1802 no = expression.args.get("no") 1803 no = " NO" if no else "" 1804 concurrent = expression.args.get("concurrent") 1805 concurrent = " CONCURRENT" if concurrent else "" 1806 target = self.sql(expression, "target") 1807 target = f" {target}" if target else "" 1808 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1809 1810 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1811 if isinstance(expression.this, list): 1812 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1813 if expression.this: 1814 modulus = self.sql(expression, "this") 1815 remainder = self.sql(expression, "expression") 1816 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1817 1818 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1819 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1820 return f"FROM ({from_expressions}) TO ({to_expressions})" 1821 1822 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1823 this = self.sql(expression, "this") 1824 1825 for_values_or_default = expression.expression 1826 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1827 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1828 else: 1829 for_values_or_default = " DEFAULT" 1830 1831 return f"PARTITION OF {this}{for_values_or_default}" 1832 1833 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1834 kind = expression.args.get("kind") 1835 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1836 for_or_in = expression.args.get("for_or_in") 1837 for_or_in = f" {for_or_in}" if for_or_in else "" 1838 lock_type = expression.args.get("lock_type") 1839 override = " OVERRIDE" if expression.args.get("override") else "" 1840 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1841 1842 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1843 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1844 statistics = expression.args.get("statistics") 1845 statistics_sql = "" 1846 if statistics is not None: 1847 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1848 return f"{data_sql}{statistics_sql}" 1849 1850 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1851 this = self.sql(expression, "this") 1852 this = f"HISTORY_TABLE={this}" if this else "" 1853 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1854 data_consistency = ( 1855 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1856 ) 1857 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1858 retention_period = ( 1859 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1860 ) 1861 1862 if this: 1863 on_sql = self.func("ON", this, data_consistency, retention_period) 1864 else: 1865 on_sql = "ON" if expression.args.get("on") else "OFF" 1866 1867 sql = f"SYSTEM_VERSIONING={on_sql}" 1868 1869 return f"WITH({sql})" if expression.args.get("with") else sql 1870 1871 def insert_sql(self, expression: exp.Insert) -> str: 1872 hint = self.sql(expression, "hint") 1873 overwrite = expression.args.get("overwrite") 1874 1875 if isinstance(expression.this, exp.Directory): 1876 this = " OVERWRITE" if overwrite else " INTO" 1877 else: 1878 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1879 1880 stored = self.sql(expression, "stored") 1881 stored = f" {stored}" if stored else "" 1882 alternative = expression.args.get("alternative") 1883 alternative = f" OR {alternative}" if alternative else "" 1884 ignore = " IGNORE" if expression.args.get("ignore") else "" 1885 is_function = expression.args.get("is_function") 1886 if is_function: 1887 this = f"{this} FUNCTION" 1888 this = f"{this} {self.sql(expression, 'this')}" 1889 1890 exists = " IF EXISTS" if expression.args.get("exists") else "" 1891 where = self.sql(expression, "where") 1892 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1893 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1894 on_conflict = self.sql(expression, "conflict") 1895 on_conflict = f" {on_conflict}" if on_conflict else "" 1896 by_name = " BY NAME" if expression.args.get("by_name") else "" 1897 returning = self.sql(expression, "returning") 1898 1899 if self.RETURNING_END: 1900 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1901 else: 1902 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1903 1904 partition_by = self.sql(expression, "partition") 1905 partition_by = f" {partition_by}" if partition_by else "" 1906 settings = self.sql(expression, "settings") 1907 settings = f" {settings}" if settings else "" 1908 1909 source = self.sql(expression, "source") 1910 source = f"TABLE {source}" if source else "" 1911 1912 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1913 return self.prepend_ctes(expression, sql) 1914 1915 def introducer_sql(self, expression: exp.Introducer) -> str: 1916 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1917 1918 def kill_sql(self, expression: exp.Kill) -> str: 1919 kind = self.sql(expression, "kind") 1920 kind = f" {kind}" if kind else "" 1921 this = self.sql(expression, "this") 1922 this = f" {this}" if this else "" 1923 return f"KILL{kind}{this}" 1924 1925 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1926 return expression.name 1927 1928 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1929 return expression.name 1930 1931 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1932 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1933 1934 constraint = self.sql(expression, "constraint") 1935 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1936 1937 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1938 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1939 action = self.sql(expression, "action") 1940 1941 expressions = self.expressions(expression, flat=True) 1942 if expressions: 1943 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1944 expressions = f" {set_keyword}{expressions}" 1945 1946 where = self.sql(expression, "where") 1947 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1948 1949 def returning_sql(self, expression: exp.Returning) -> str: 1950 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1951 1952 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1953 fields = self.sql(expression, "fields") 1954 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1955 escaped = self.sql(expression, "escaped") 1956 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1957 items = self.sql(expression, "collection_items") 1958 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1959 keys = self.sql(expression, "map_keys") 1960 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1961 lines = self.sql(expression, "lines") 1962 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1963 null = self.sql(expression, "null") 1964 null = f" NULL DEFINED AS {null}" if null else "" 1965 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1966 1967 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1968 return f"WITH ({self.expressions(expression, flat=True)})" 1969 1970 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1971 this = f"{self.sql(expression, 'this')} INDEX" 1972 target = self.sql(expression, "target") 1973 target = f" FOR {target}" if target else "" 1974 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1975 1976 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1977 this = self.sql(expression, "this") 1978 kind = self.sql(expression, "kind") 1979 expr = self.sql(expression, "expression") 1980 return f"{this} ({kind} => {expr})" 1981 1982 def table_parts(self, expression: exp.Table) -> str: 1983 return ".".join( 1984 self.sql(part) 1985 for part in ( 1986 expression.args.get("catalog"), 1987 expression.args.get("db"), 1988 expression.args.get("this"), 1989 ) 1990 if part is not None 1991 ) 1992 1993 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1994 table = self.table_parts(expression) 1995 only = "ONLY " if expression.args.get("only") else "" 1996 partition = self.sql(expression, "partition") 1997 partition = f" {partition}" if partition else "" 1998 version = self.sql(expression, "version") 1999 version = f" {version}" if version else "" 2000 alias = self.sql(expression, "alias") 2001 alias = f"{sep}{alias}" if alias else "" 2002 2003 sample = self.sql(expression, "sample") 2004 if self.dialect.ALIAS_POST_TABLESAMPLE: 2005 sample_pre_alias = sample 2006 sample_post_alias = "" 2007 else: 2008 sample_pre_alias = "" 2009 sample_post_alias = sample 2010 2011 hints = self.expressions(expression, key="hints", sep=" ") 2012 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2013 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2014 joins = self.indent( 2015 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2016 ) 2017 laterals = self.expressions(expression, key="laterals", sep="") 2018 2019 file_format = self.sql(expression, "format") 2020 if file_format: 2021 pattern = self.sql(expression, "pattern") 2022 pattern = f", PATTERN => {pattern}" if pattern else "" 2023 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2024 2025 ordinality = expression.args.get("ordinality") or "" 2026 if ordinality: 2027 ordinality = f" WITH ORDINALITY{alias}" 2028 alias = "" 2029 2030 when = self.sql(expression, "when") 2031 if when: 2032 table = f"{table} {when}" 2033 2034 changes = self.sql(expression, "changes") 2035 changes = f" {changes}" if changes else "" 2036 2037 rows_from = self.expressions(expression, key="rows_from") 2038 if rows_from: 2039 table = f"ROWS FROM {self.wrap(rows_from)}" 2040 2041 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2042 2043 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2044 table = self.func("TABLE", expression.this) 2045 alias = self.sql(expression, "alias") 2046 alias = f" AS {alias}" if alias else "" 2047 sample = self.sql(expression, "sample") 2048 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2049 joins = self.indent( 2050 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2051 ) 2052 return f"{table}{alias}{pivots}{sample}{joins}" 2053 2054 def tablesample_sql( 2055 self, 2056 expression: exp.TableSample, 2057 tablesample_keyword: t.Optional[str] = None, 2058 ) -> str: 2059 method = self.sql(expression, "method") 2060 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2061 numerator = self.sql(expression, "bucket_numerator") 2062 denominator = self.sql(expression, "bucket_denominator") 2063 field = self.sql(expression, "bucket_field") 2064 field = f" ON {field}" if field else "" 2065 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2066 seed = self.sql(expression, "seed") 2067 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2068 2069 size = self.sql(expression, "size") 2070 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2071 size = f"{size} ROWS" 2072 2073 percent = self.sql(expression, "percent") 2074 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2075 percent = f"{percent} PERCENT" 2076 2077 expr = f"{bucket}{percent}{size}" 2078 if self.TABLESAMPLE_REQUIRES_PARENS: 2079 expr = f"({expr})" 2080 2081 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2082 2083 def pivot_sql(self, expression: exp.Pivot) -> str: 2084 expressions = self.expressions(expression, flat=True) 2085 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2086 2087 group = self.sql(expression, "group") 2088 2089 if expression.this: 2090 this = self.sql(expression, "this") 2091 if not expressions: 2092 return f"UNPIVOT {this}" 2093 2094 on = f"{self.seg('ON')} {expressions}" 2095 into = self.sql(expression, "into") 2096 into = f"{self.seg('INTO')} {into}" if into else "" 2097 using = self.expressions(expression, key="using", flat=True) 2098 using = f"{self.seg('USING')} {using}" if using else "" 2099 return f"{direction} {this}{on}{into}{using}{group}" 2100 2101 alias = self.sql(expression, "alias") 2102 alias = f" AS {alias}" if alias else "" 2103 2104 fields = self.expressions( 2105 expression, 2106 "fields", 2107 sep=" ", 2108 dynamic=True, 2109 new_line=True, 2110 skip_first=True, 2111 skip_last=True, 2112 ) 2113 2114 include_nulls = expression.args.get("include_nulls") 2115 if include_nulls is not None: 2116 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2117 else: 2118 nulls = "" 2119 2120 default_on_null = self.sql(expression, "default_on_null") 2121 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2122 return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}" 2123 2124 def version_sql(self, expression: exp.Version) -> str: 2125 this = f"FOR {expression.name}" 2126 kind = expression.text("kind") 2127 expr = self.sql(expression, "expression") 2128 return f"{this} {kind} {expr}" 2129 2130 def tuple_sql(self, expression: exp.Tuple) -> str: 2131 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2132 2133 def update_sql(self, expression: exp.Update) -> str: 2134 this = self.sql(expression, "this") 2135 set_sql = self.expressions(expression, flat=True) 2136 from_sql = self.sql(expression, "from") 2137 where_sql = self.sql(expression, "where") 2138 returning = self.sql(expression, "returning") 2139 order = self.sql(expression, "order") 2140 limit = self.sql(expression, "limit") 2141 if self.RETURNING_END: 2142 expression_sql = f"{from_sql}{where_sql}{returning}" 2143 else: 2144 expression_sql = f"{returning}{from_sql}{where_sql}" 2145 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2146 return self.prepend_ctes(expression, sql) 2147 2148 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2149 values_as_table = values_as_table and self.VALUES_AS_TABLE 2150 2151 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2152 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2153 args = self.expressions(expression) 2154 alias = self.sql(expression, "alias") 2155 values = f"VALUES{self.seg('')}{args}" 2156 values = ( 2157 f"({values})" 2158 if self.WRAP_DERIVED_VALUES 2159 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2160 else values 2161 ) 2162 return f"{values} AS {alias}" if alias else values 2163 2164 # Converts `VALUES...` expression into a series of select unions. 2165 alias_node = expression.args.get("alias") 2166 column_names = alias_node and alias_node.columns 2167 2168 selects: t.List[exp.Query] = [] 2169 2170 for i, tup in enumerate(expression.expressions): 2171 row = tup.expressions 2172 2173 if i == 0 and column_names: 2174 row = [ 2175 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2176 ] 2177 2178 selects.append(exp.Select(expressions=row)) 2179 2180 if self.pretty: 2181 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2182 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2183 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2184 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2185 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2186 2187 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2188 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2189 return f"({unions}){alias}" 2190 2191 def var_sql(self, expression: exp.Var) -> str: 2192 return self.sql(expression, "this") 2193 2194 @unsupported_args("expressions") 2195 def into_sql(self, expression: exp.Into) -> str: 2196 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2197 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2198 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2199 2200 def from_sql(self, expression: exp.From) -> str: 2201 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2202 2203 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2204 grouping_sets = self.expressions(expression, indent=False) 2205 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2206 2207 def rollup_sql(self, expression: exp.Rollup) -> str: 2208 expressions = self.expressions(expression, indent=False) 2209 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2210 2211 def cube_sql(self, expression: exp.Cube) -> str: 2212 expressions = self.expressions(expression, indent=False) 2213 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2214 2215 def group_sql(self, expression: exp.Group) -> str: 2216 group_by_all = expression.args.get("all") 2217 if group_by_all is True: 2218 modifier = " ALL" 2219 elif group_by_all is False: 2220 modifier = " DISTINCT" 2221 else: 2222 modifier = "" 2223 2224 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2225 2226 grouping_sets = self.expressions(expression, key="grouping_sets") 2227 cube = self.expressions(expression, key="cube") 2228 rollup = self.expressions(expression, key="rollup") 2229 2230 groupings = csv( 2231 self.seg(grouping_sets) if grouping_sets else "", 2232 self.seg(cube) if cube else "", 2233 self.seg(rollup) if rollup else "", 2234 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2235 sep=self.GROUPINGS_SEP, 2236 ) 2237 2238 if ( 2239 expression.expressions 2240 and groupings 2241 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2242 ): 2243 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2244 2245 return f"{group_by}{groupings}" 2246 2247 def having_sql(self, expression: exp.Having) -> str: 2248 this = self.indent(self.sql(expression, "this")) 2249 return f"{self.seg('HAVING')}{self.sep()}{this}" 2250 2251 def connect_sql(self, expression: exp.Connect) -> str: 2252 start = self.sql(expression, "start") 2253 start = self.seg(f"START WITH {start}") if start else "" 2254 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2255 connect = self.sql(expression, "connect") 2256 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2257 return start + connect 2258 2259 def prior_sql(self, expression: exp.Prior) -> str: 2260 return f"PRIOR {self.sql(expression, 'this')}" 2261 2262 def join_sql(self, expression: exp.Join) -> str: 2263 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2264 side = None 2265 else: 2266 side = expression.side 2267 2268 op_sql = " ".join( 2269 op 2270 for op in ( 2271 expression.method, 2272 "GLOBAL" if expression.args.get("global") else None, 2273 side, 2274 expression.kind, 2275 expression.hint if self.JOIN_HINTS else None, 2276 ) 2277 if op 2278 ) 2279 match_cond = self.sql(expression, "match_condition") 2280 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2281 on_sql = self.sql(expression, "on") 2282 using = expression.args.get("using") 2283 2284 if not on_sql and using: 2285 on_sql = csv(*(self.sql(column) for column in using)) 2286 2287 this = expression.this 2288 this_sql = self.sql(this) 2289 2290 exprs = self.expressions(expression) 2291 if exprs: 2292 this_sql = f"{this_sql},{self.seg(exprs)}" 2293 2294 if on_sql: 2295 on_sql = self.indent(on_sql, skip_first=True) 2296 space = self.seg(" " * self.pad) if self.pretty else " " 2297 if using: 2298 on_sql = f"{space}USING ({on_sql})" 2299 else: 2300 on_sql = f"{space}ON {on_sql}" 2301 elif not op_sql: 2302 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2303 return f" {this_sql}" 2304 2305 return f", {this_sql}" 2306 2307 if op_sql != "STRAIGHT_JOIN": 2308 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2309 2310 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2311 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}" 2312 2313 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2314 args = self.expressions(expression, flat=True) 2315 args = f"({args})" if len(args.split(",")) > 1 else args 2316 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2317 2318 def lateral_op(self, expression: exp.Lateral) -> str: 2319 cross_apply = expression.args.get("cross_apply") 2320 2321 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2322 if cross_apply is True: 2323 op = "INNER JOIN " 2324 elif cross_apply is False: 2325 op = "LEFT JOIN " 2326 else: 2327 op = "" 2328 2329 return f"{op}LATERAL" 2330 2331 def lateral_sql(self, expression: exp.Lateral) -> str: 2332 this = self.sql(expression, "this") 2333 2334 if expression.args.get("view"): 2335 alias = expression.args["alias"] 2336 columns = self.expressions(alias, key="columns", flat=True) 2337 table = f" {alias.name}" if alias.name else "" 2338 columns = f" AS {columns}" if columns else "" 2339 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2340 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2341 2342 alias = self.sql(expression, "alias") 2343 alias = f" AS {alias}" if alias else "" 2344 2345 ordinality = expression.args.get("ordinality") or "" 2346 if ordinality: 2347 ordinality = f" WITH ORDINALITY{alias}" 2348 alias = "" 2349 2350 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}" 2351 2352 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2353 this = self.sql(expression, "this") 2354 2355 args = [ 2356 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2357 for e in (expression.args.get(k) for k in ("offset", "expression")) 2358 if e 2359 ] 2360 2361 args_sql = ", ".join(self.sql(e) for e in args) 2362 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2363 expressions = self.expressions(expression, flat=True) 2364 limit_options = self.sql(expression, "limit_options") 2365 expressions = f" BY {expressions}" if expressions else "" 2366 2367 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2368 2369 def offset_sql(self, expression: exp.Offset) -> str: 2370 this = self.sql(expression, "this") 2371 value = expression.expression 2372 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2373 expressions = self.expressions(expression, flat=True) 2374 expressions = f" BY {expressions}" if expressions else "" 2375 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2376 2377 def setitem_sql(self, expression: exp.SetItem) -> str: 2378 kind = self.sql(expression, "kind") 2379 kind = f"{kind} " if kind else "" 2380 this = self.sql(expression, "this") 2381 expressions = self.expressions(expression) 2382 collate = self.sql(expression, "collate") 2383 collate = f" COLLATE {collate}" if collate else "" 2384 global_ = "GLOBAL " if expression.args.get("global") else "" 2385 return f"{global_}{kind}{this}{expressions}{collate}" 2386 2387 def set_sql(self, expression: exp.Set) -> str: 2388 expressions = f" {self.expressions(expression, flat=True)}" 2389 tag = " TAG" if expression.args.get("tag") else "" 2390 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2391 2392 def pragma_sql(self, expression: exp.Pragma) -> str: 2393 return f"PRAGMA {self.sql(expression, 'this')}" 2394 2395 def lock_sql(self, expression: exp.Lock) -> str: 2396 if not self.LOCKING_READS_SUPPORTED: 2397 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2398 return "" 2399 2400 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2401 expressions = self.expressions(expression, flat=True) 2402 expressions = f" OF {expressions}" if expressions else "" 2403 wait = expression.args.get("wait") 2404 2405 if wait is not None: 2406 if isinstance(wait, exp.Literal): 2407 wait = f" WAIT {self.sql(wait)}" 2408 else: 2409 wait = " NOWAIT" if wait else " SKIP LOCKED" 2410 2411 return f"{lock_type}{expressions}{wait or ''}" 2412 2413 def literal_sql(self, expression: exp.Literal) -> str: 2414 text = expression.this or "" 2415 if expression.is_string: 2416 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2417 return text 2418 2419 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2420 if self.dialect.ESCAPED_SEQUENCES: 2421 to_escaped = self.dialect.ESCAPED_SEQUENCES 2422 text = "".join( 2423 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2424 ) 2425 2426 return self._replace_line_breaks(text).replace( 2427 self.dialect.QUOTE_END, self._escaped_quote_end 2428 ) 2429 2430 def loaddata_sql(self, expression: exp.LoadData) -> str: 2431 local = " LOCAL" if expression.args.get("local") else "" 2432 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2433 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2434 this = f" INTO TABLE {self.sql(expression, 'this')}" 2435 partition = self.sql(expression, "partition") 2436 partition = f" {partition}" if partition else "" 2437 input_format = self.sql(expression, "input_format") 2438 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2439 serde = self.sql(expression, "serde") 2440 serde = f" SERDE {serde}" if serde else "" 2441 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2442 2443 def null_sql(self, *_) -> str: 2444 return "NULL" 2445 2446 def boolean_sql(self, expression: exp.Boolean) -> str: 2447 return "TRUE" if expression.this else "FALSE" 2448 2449 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2450 this = self.sql(expression, "this") 2451 this = f"{this} " if this else this 2452 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2453 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2454 2455 def withfill_sql(self, expression: exp.WithFill) -> str: 2456 from_sql = self.sql(expression, "from") 2457 from_sql = f" FROM {from_sql}" if from_sql else "" 2458 to_sql = self.sql(expression, "to") 2459 to_sql = f" TO {to_sql}" if to_sql else "" 2460 step_sql = self.sql(expression, "step") 2461 step_sql = f" STEP {step_sql}" if step_sql else "" 2462 interpolated_values = [ 2463 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2464 if isinstance(e, exp.Alias) 2465 else self.sql(e, "this") 2466 for e in expression.args.get("interpolate") or [] 2467 ] 2468 interpolate = ( 2469 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2470 ) 2471 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2472 2473 def cluster_sql(self, expression: exp.Cluster) -> str: 2474 return self.op_expressions("CLUSTER BY", expression) 2475 2476 def distribute_sql(self, expression: exp.Distribute) -> str: 2477 return self.op_expressions("DISTRIBUTE BY", expression) 2478 2479 def sort_sql(self, expression: exp.Sort) -> str: 2480 return self.op_expressions("SORT BY", expression) 2481 2482 def ordered_sql(self, expression: exp.Ordered) -> str: 2483 desc = expression.args.get("desc") 2484 asc = not desc 2485 2486 nulls_first = expression.args.get("nulls_first") 2487 nulls_last = not nulls_first 2488 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2489 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2490 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2491 2492 this = self.sql(expression, "this") 2493 2494 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2495 nulls_sort_change = "" 2496 if nulls_first and ( 2497 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2498 ): 2499 nulls_sort_change = " NULLS FIRST" 2500 elif ( 2501 nulls_last 2502 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2503 and not nulls_are_last 2504 ): 2505 nulls_sort_change = " NULLS LAST" 2506 2507 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2508 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2509 window = expression.find_ancestor(exp.Window, exp.Select) 2510 if isinstance(window, exp.Window) and window.args.get("spec"): 2511 self.unsupported( 2512 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2513 ) 2514 nulls_sort_change = "" 2515 elif self.NULL_ORDERING_SUPPORTED is False and ( 2516 (asc and nulls_sort_change == " NULLS LAST") 2517 or (desc and nulls_sort_change == " NULLS FIRST") 2518 ): 2519 # BigQuery does not allow these ordering/nulls combinations when used under 2520 # an aggregation func or under a window containing one 2521 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2522 2523 if isinstance(ancestor, exp.Window): 2524 ancestor = ancestor.this 2525 if isinstance(ancestor, exp.AggFunc): 2526 self.unsupported( 2527 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2528 ) 2529 nulls_sort_change = "" 2530 elif self.NULL_ORDERING_SUPPORTED is None: 2531 if expression.this.is_int: 2532 self.unsupported( 2533 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2534 ) 2535 elif not isinstance(expression.this, exp.Rand): 2536 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2537 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2538 nulls_sort_change = "" 2539 2540 with_fill = self.sql(expression, "with_fill") 2541 with_fill = f" {with_fill}" if with_fill else "" 2542 2543 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2544 2545 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2546 window_frame = self.sql(expression, "window_frame") 2547 window_frame = f"{window_frame} " if window_frame else "" 2548 2549 this = self.sql(expression, "this") 2550 2551 return f"{window_frame}{this}" 2552 2553 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2554 partition = self.partition_by_sql(expression) 2555 order = self.sql(expression, "order") 2556 measures = self.expressions(expression, key="measures") 2557 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2558 rows = self.sql(expression, "rows") 2559 rows = self.seg(rows) if rows else "" 2560 after = self.sql(expression, "after") 2561 after = self.seg(after) if after else "" 2562 pattern = self.sql(expression, "pattern") 2563 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2564 definition_sqls = [ 2565 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2566 for definition in expression.args.get("define", []) 2567 ] 2568 definitions = self.expressions(sqls=definition_sqls) 2569 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2570 body = "".join( 2571 ( 2572 partition, 2573 order, 2574 measures, 2575 rows, 2576 after, 2577 pattern, 2578 define, 2579 ) 2580 ) 2581 alias = self.sql(expression, "alias") 2582 alias = f" {alias}" if alias else "" 2583 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2584 2585 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2586 limit = expression.args.get("limit") 2587 2588 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2589 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2590 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2591 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2592 2593 return csv( 2594 *sqls, 2595 *[self.sql(join) for join in expression.args.get("joins") or []], 2596 self.sql(expression, "match"), 2597 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2598 self.sql(expression, "prewhere"), 2599 self.sql(expression, "where"), 2600 self.sql(expression, "connect"), 2601 self.sql(expression, "group"), 2602 self.sql(expression, "having"), 2603 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2604 self.sql(expression, "order"), 2605 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2606 *self.after_limit_modifiers(expression), 2607 self.options_modifier(expression), 2608 self.for_modifiers(expression), 2609 sep="", 2610 ) 2611 2612 def options_modifier(self, expression: exp.Expression) -> str: 2613 options = self.expressions(expression, key="options") 2614 return f" {options}" if options else "" 2615 2616 def for_modifiers(self, expression: exp.Expression) -> str: 2617 for_modifiers = self.expressions(expression, key="for") 2618 return f"{self.sep()}FOR XML{self.seg(for_modifiers)}" if for_modifiers else "" 2619 2620 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2621 self.unsupported("Unsupported query option.") 2622 return "" 2623 2624 def offset_limit_modifiers( 2625 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2626 ) -> t.List[str]: 2627 return [ 2628 self.sql(expression, "offset") if fetch else self.sql(limit), 2629 self.sql(limit) if fetch else self.sql(expression, "offset"), 2630 ] 2631 2632 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2633 locks = self.expressions(expression, key="locks", sep=" ") 2634 locks = f" {locks}" if locks else "" 2635 return [locks, self.sql(expression, "sample")] 2636 2637 def select_sql(self, expression: exp.Select) -> str: 2638 into = expression.args.get("into") 2639 if not self.SUPPORTS_SELECT_INTO and into: 2640 into.pop() 2641 2642 hint = self.sql(expression, "hint") 2643 distinct = self.sql(expression, "distinct") 2644 distinct = f" {distinct}" if distinct else "" 2645 kind = self.sql(expression, "kind") 2646 2647 limit = expression.args.get("limit") 2648 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2649 top = self.limit_sql(limit, top=True) 2650 limit.pop() 2651 else: 2652 top = "" 2653 2654 expressions = self.expressions(expression) 2655 2656 if kind: 2657 if kind in self.SELECT_KINDS: 2658 kind = f" AS {kind}" 2659 else: 2660 if kind == "STRUCT": 2661 expressions = self.expressions( 2662 sqls=[ 2663 self.sql( 2664 exp.Struct( 2665 expressions=[ 2666 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2667 if isinstance(e, exp.Alias) 2668 else e 2669 for e in expression.expressions 2670 ] 2671 ) 2672 ) 2673 ] 2674 ) 2675 kind = "" 2676 2677 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2678 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2679 2680 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2681 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2682 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2683 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2684 sql = self.query_modifiers( 2685 expression, 2686 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2687 self.sql(expression, "into", comment=False), 2688 self.sql(expression, "from", comment=False), 2689 ) 2690 2691 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2692 if expression.args.get("with"): 2693 sql = self.maybe_comment(sql, expression) 2694 expression.pop_comments() 2695 2696 sql = self.prepend_ctes(expression, sql) 2697 2698 if not self.SUPPORTS_SELECT_INTO and into: 2699 if into.args.get("temporary"): 2700 table_kind = " TEMPORARY" 2701 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2702 table_kind = " UNLOGGED" 2703 else: 2704 table_kind = "" 2705 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2706 2707 return sql 2708 2709 def schema_sql(self, expression: exp.Schema) -> str: 2710 this = self.sql(expression, "this") 2711 sql = self.schema_columns_sql(expression) 2712 return f"{this} {sql}" if this and sql else this or sql 2713 2714 def schema_columns_sql(self, expression: exp.Schema) -> str: 2715 if expression.expressions: 2716 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2717 return "" 2718 2719 def star_sql(self, expression: exp.Star) -> str: 2720 except_ = self.expressions(expression, key="except", flat=True) 2721 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2722 replace = self.expressions(expression, key="replace", flat=True) 2723 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2724 rename = self.expressions(expression, key="rename", flat=True) 2725 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2726 return f"*{except_}{replace}{rename}" 2727 2728 def parameter_sql(self, expression: exp.Parameter) -> str: 2729 this = self.sql(expression, "this") 2730 return f"{self.PARAMETER_TOKEN}{this}" 2731 2732 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2733 this = self.sql(expression, "this") 2734 kind = expression.text("kind") 2735 if kind: 2736 kind = f"{kind}." 2737 return f"@@{kind}{this}" 2738 2739 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2740 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2741 2742 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2743 alias = self.sql(expression, "alias") 2744 alias = f"{sep}{alias}" if alias else "" 2745 sample = self.sql(expression, "sample") 2746 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2747 alias = f"{sample}{alias}" 2748 2749 # Set to None so it's not generated again by self.query_modifiers() 2750 expression.set("sample", None) 2751 2752 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2753 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2754 return self.prepend_ctes(expression, sql) 2755 2756 def qualify_sql(self, expression: exp.Qualify) -> str: 2757 this = self.indent(self.sql(expression, "this")) 2758 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2759 2760 def unnest_sql(self, expression: exp.Unnest) -> str: 2761 args = self.expressions(expression, flat=True) 2762 2763 alias = expression.args.get("alias") 2764 offset = expression.args.get("offset") 2765 2766 if self.UNNEST_WITH_ORDINALITY: 2767 if alias and isinstance(offset, exp.Expression): 2768 alias.append("columns", offset) 2769 2770 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2771 columns = alias.columns 2772 alias = self.sql(columns[0]) if columns else "" 2773 else: 2774 alias = self.sql(alias) 2775 2776 alias = f" AS {alias}" if alias else alias 2777 if self.UNNEST_WITH_ORDINALITY: 2778 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2779 else: 2780 if isinstance(offset, exp.Expression): 2781 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2782 elif offset: 2783 suffix = f"{alias} WITH OFFSET" 2784 else: 2785 suffix = alias 2786 2787 return f"UNNEST({args}){suffix}" 2788 2789 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2790 return "" 2791 2792 def where_sql(self, expression: exp.Where) -> str: 2793 this = self.indent(self.sql(expression, "this")) 2794 return f"{self.seg('WHERE')}{self.sep()}{this}" 2795 2796 def window_sql(self, expression: exp.Window) -> str: 2797 this = self.sql(expression, "this") 2798 partition = self.partition_by_sql(expression) 2799 order = expression.args.get("order") 2800 order = self.order_sql(order, flat=True) if order else "" 2801 spec = self.sql(expression, "spec") 2802 alias = self.sql(expression, "alias") 2803 over = self.sql(expression, "over") or "OVER" 2804 2805 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2806 2807 first = expression.args.get("first") 2808 if first is None: 2809 first = "" 2810 else: 2811 first = "FIRST" if first else "LAST" 2812 2813 if not partition and not order and not spec and alias: 2814 return f"{this} {alias}" 2815 2816 args = self.format_args( 2817 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 2818 ) 2819 return f"{this} ({args})" 2820 2821 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2822 partition = self.expressions(expression, key="partition_by", flat=True) 2823 return f"PARTITION BY {partition}" if partition else "" 2824 2825 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2826 kind = self.sql(expression, "kind") 2827 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2828 end = ( 2829 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2830 or "CURRENT ROW" 2831 ) 2832 2833 window_spec = f"{kind} BETWEEN {start} AND {end}" 2834 2835 exclude = self.sql(expression, "exclude") 2836 if exclude: 2837 if self.SUPPORTS_WINDOW_EXCLUDE: 2838 window_spec += f" EXCLUDE {exclude}" 2839 else: 2840 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 2841 2842 return window_spec 2843 2844 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2845 this = self.sql(expression, "this") 2846 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2847 return f"{this} WITHIN GROUP ({expression_sql})" 2848 2849 def between_sql(self, expression: exp.Between) -> str: 2850 this = self.sql(expression, "this") 2851 low = self.sql(expression, "low") 2852 high = self.sql(expression, "high") 2853 return f"{this} BETWEEN {low} AND {high}" 2854 2855 def bracket_offset_expressions( 2856 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2857 ) -> t.List[exp.Expression]: 2858 return apply_index_offset( 2859 expression.this, 2860 expression.expressions, 2861 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2862 dialect=self.dialect, 2863 ) 2864 2865 def bracket_sql(self, expression: exp.Bracket) -> str: 2866 expressions = self.bracket_offset_expressions(expression) 2867 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2868 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2869 2870 def all_sql(self, expression: exp.All) -> str: 2871 return f"ALL {self.wrap(expression)}" 2872 2873 def any_sql(self, expression: exp.Any) -> str: 2874 this = self.sql(expression, "this") 2875 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2876 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2877 this = self.wrap(this) 2878 return f"ANY{this}" 2879 return f"ANY {this}" 2880 2881 def exists_sql(self, expression: exp.Exists) -> str: 2882 return f"EXISTS{self.wrap(expression)}" 2883 2884 def case_sql(self, expression: exp.Case) -> str: 2885 this = self.sql(expression, "this") 2886 statements = [f"CASE {this}" if this else "CASE"] 2887 2888 for e in expression.args["ifs"]: 2889 statements.append(f"WHEN {self.sql(e, 'this')}") 2890 statements.append(f"THEN {self.sql(e, 'true')}") 2891 2892 default = self.sql(expression, "default") 2893 2894 if default: 2895 statements.append(f"ELSE {default}") 2896 2897 statements.append("END") 2898 2899 if self.pretty and self.too_wide(statements): 2900 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2901 2902 return " ".join(statements) 2903 2904 def constraint_sql(self, expression: exp.Constraint) -> str: 2905 this = self.sql(expression, "this") 2906 expressions = self.expressions(expression, flat=True) 2907 return f"CONSTRAINT {this} {expressions}" 2908 2909 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2910 order = expression.args.get("order") 2911 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2912 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2913 2914 def extract_sql(self, expression: exp.Extract) -> str: 2915 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2916 expression_sql = self.sql(expression, "expression") 2917 return f"EXTRACT({this} FROM {expression_sql})" 2918 2919 def trim_sql(self, expression: exp.Trim) -> str: 2920 trim_type = self.sql(expression, "position") 2921 2922 if trim_type == "LEADING": 2923 func_name = "LTRIM" 2924 elif trim_type == "TRAILING": 2925 func_name = "RTRIM" 2926 else: 2927 func_name = "TRIM" 2928 2929 return self.func(func_name, expression.this, expression.expression) 2930 2931 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2932 args = expression.expressions 2933 if isinstance(expression, exp.ConcatWs): 2934 args = args[1:] # Skip the delimiter 2935 2936 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2937 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2938 2939 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2940 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2941 2942 return args 2943 2944 def concat_sql(self, expression: exp.Concat) -> str: 2945 expressions = self.convert_concat_args(expression) 2946 2947 # Some dialects don't allow a single-argument CONCAT call 2948 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2949 return self.sql(expressions[0]) 2950 2951 return self.func("CONCAT", *expressions) 2952 2953 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2954 return self.func( 2955 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2956 ) 2957 2958 def check_sql(self, expression: exp.Check) -> str: 2959 this = self.sql(expression, key="this") 2960 return f"CHECK ({this})" 2961 2962 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2963 expressions = self.expressions(expression, flat=True) 2964 expressions = f" ({expressions})" if expressions else "" 2965 reference = self.sql(expression, "reference") 2966 reference = f" {reference}" if reference else "" 2967 delete = self.sql(expression, "delete") 2968 delete = f" ON DELETE {delete}" if delete else "" 2969 update = self.sql(expression, "update") 2970 update = f" ON UPDATE {update}" if update else "" 2971 options = self.expressions(expression, key="options", flat=True, sep=" ") 2972 options = f" {options}" if options else "" 2973 return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}" 2974 2975 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2976 expressions = self.expressions(expression, flat=True) 2977 options = self.expressions(expression, key="options", flat=True, sep=" ") 2978 options = f" {options}" if options else "" 2979 return f"PRIMARY KEY ({expressions}){options}" 2980 2981 def if_sql(self, expression: exp.If) -> str: 2982 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2983 2984 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2985 modifier = expression.args.get("modifier") 2986 modifier = f" {modifier}" if modifier else "" 2987 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2988 2989 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2990 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2991 2992 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2993 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2994 2995 if expression.args.get("escape"): 2996 path = self.escape_str(path) 2997 2998 if self.QUOTE_JSON_PATH: 2999 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 3000 3001 return path 3002 3003 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 3004 if isinstance(expression, exp.JSONPathPart): 3005 transform = self.TRANSFORMS.get(expression.__class__) 3006 if not callable(transform): 3007 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 3008 return "" 3009 3010 return transform(self, expression) 3011 3012 if isinstance(expression, int): 3013 return str(expression) 3014 3015 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 3016 escaped = expression.replace("'", "\\'") 3017 escaped = f"\\'{expression}\\'" 3018 else: 3019 escaped = expression.replace('"', '\\"') 3020 escaped = f'"{escaped}"' 3021 3022 return escaped 3023 3024 def formatjson_sql(self, expression: exp.FormatJson) -> str: 3025 return f"{self.sql(expression, 'this')} FORMAT JSON" 3026 3027 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 3028 null_handling = expression.args.get("null_handling") 3029 null_handling = f" {null_handling}" if null_handling else "" 3030 3031 unique_keys = expression.args.get("unique_keys") 3032 if unique_keys is not None: 3033 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 3034 else: 3035 unique_keys = "" 3036 3037 return_type = self.sql(expression, "return_type") 3038 return_type = f" RETURNING {return_type}" if return_type else "" 3039 encoding = self.sql(expression, "encoding") 3040 encoding = f" ENCODING {encoding}" if encoding else "" 3041 3042 return self.func( 3043 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 3044 *expression.expressions, 3045 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 3046 ) 3047 3048 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 3049 return self.jsonobject_sql(expression) 3050 3051 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 3052 null_handling = expression.args.get("null_handling") 3053 null_handling = f" {null_handling}" if null_handling else "" 3054 return_type = self.sql(expression, "return_type") 3055 return_type = f" RETURNING {return_type}" if return_type else "" 3056 strict = " STRICT" if expression.args.get("strict") else "" 3057 return self.func( 3058 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 3059 ) 3060 3061 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 3062 this = self.sql(expression, "this") 3063 order = self.sql(expression, "order") 3064 null_handling = expression.args.get("null_handling") 3065 null_handling = f" {null_handling}" if null_handling else "" 3066 return_type = self.sql(expression, "return_type") 3067 return_type = f" RETURNING {return_type}" if return_type else "" 3068 strict = " STRICT" if expression.args.get("strict") else "" 3069 return self.func( 3070 "JSON_ARRAYAGG", 3071 this, 3072 suffix=f"{order}{null_handling}{return_type}{strict})", 3073 ) 3074 3075 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3076 path = self.sql(expression, "path") 3077 path = f" PATH {path}" if path else "" 3078 nested_schema = self.sql(expression, "nested_schema") 3079 3080 if nested_schema: 3081 return f"NESTED{path} {nested_schema}" 3082 3083 this = self.sql(expression, "this") 3084 kind = self.sql(expression, "kind") 3085 kind = f" {kind}" if kind else "" 3086 return f"{this}{kind}{path}" 3087 3088 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3089 return self.func("COLUMNS", *expression.expressions) 3090 3091 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3092 this = self.sql(expression, "this") 3093 path = self.sql(expression, "path") 3094 path = f", {path}" if path else "" 3095 error_handling = expression.args.get("error_handling") 3096 error_handling = f" {error_handling}" if error_handling else "" 3097 empty_handling = expression.args.get("empty_handling") 3098 empty_handling = f" {empty_handling}" if empty_handling else "" 3099 schema = self.sql(expression, "schema") 3100 return self.func( 3101 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3102 ) 3103 3104 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3105 this = self.sql(expression, "this") 3106 kind = self.sql(expression, "kind") 3107 path = self.sql(expression, "path") 3108 path = f" {path}" if path else "" 3109 as_json = " AS JSON" if expression.args.get("as_json") else "" 3110 return f"{this} {kind}{path}{as_json}" 3111 3112 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3113 this = self.sql(expression, "this") 3114 path = self.sql(expression, "path") 3115 path = f", {path}" if path else "" 3116 expressions = self.expressions(expression) 3117 with_ = ( 3118 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3119 if expressions 3120 else "" 3121 ) 3122 return f"OPENJSON({this}{path}){with_}" 3123 3124 def in_sql(self, expression: exp.In) -> str: 3125 query = expression.args.get("query") 3126 unnest = expression.args.get("unnest") 3127 field = expression.args.get("field") 3128 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3129 3130 if query: 3131 in_sql = self.sql(query) 3132 elif unnest: 3133 in_sql = self.in_unnest_op(unnest) 3134 elif field: 3135 in_sql = self.sql(field) 3136 else: 3137 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3138 3139 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3140 3141 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3142 return f"(SELECT {self.sql(unnest)})" 3143 3144 def interval_sql(self, expression: exp.Interval) -> str: 3145 unit = self.sql(expression, "unit") 3146 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3147 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3148 unit = f" {unit}" if unit else "" 3149 3150 if self.SINGLE_STRING_INTERVAL: 3151 this = expression.this.name if expression.this else "" 3152 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3153 3154 this = self.sql(expression, "this") 3155 if this: 3156 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3157 this = f" {this}" if unwrapped else f" ({this})" 3158 3159 return f"INTERVAL{this}{unit}" 3160 3161 def return_sql(self, expression: exp.Return) -> str: 3162 return f"RETURN {self.sql(expression, 'this')}" 3163 3164 def reference_sql(self, expression: exp.Reference) -> str: 3165 this = self.sql(expression, "this") 3166 expressions = self.expressions(expression, flat=True) 3167 expressions = f"({expressions})" if expressions else "" 3168 options = self.expressions(expression, key="options", flat=True, sep=" ") 3169 options = f" {options}" if options else "" 3170 return f"REFERENCES {this}{expressions}{options}" 3171 3172 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3173 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3174 parent = expression.parent 3175 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3176 return self.func( 3177 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3178 ) 3179 3180 def paren_sql(self, expression: exp.Paren) -> str: 3181 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3182 return f"({sql}{self.seg(')', sep='')}" 3183 3184 def neg_sql(self, expression: exp.Neg) -> str: 3185 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3186 this_sql = self.sql(expression, "this") 3187 sep = " " if this_sql[0] == "-" else "" 3188 return f"-{sep}{this_sql}" 3189 3190 def not_sql(self, expression: exp.Not) -> str: 3191 return f"NOT {self.sql(expression, 'this')}" 3192 3193 def alias_sql(self, expression: exp.Alias) -> str: 3194 alias = self.sql(expression, "alias") 3195 alias = f" AS {alias}" if alias else "" 3196 return f"{self.sql(expression, 'this')}{alias}" 3197 3198 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3199 alias = expression.args["alias"] 3200 3201 parent = expression.parent 3202 pivot = parent and parent.parent 3203 3204 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3205 identifier_alias = isinstance(alias, exp.Identifier) 3206 literal_alias = isinstance(alias, exp.Literal) 3207 3208 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3209 alias.replace(exp.Literal.string(alias.output_name)) 3210 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3211 alias.replace(exp.to_identifier(alias.output_name)) 3212 3213 return self.alias_sql(expression) 3214 3215 def aliases_sql(self, expression: exp.Aliases) -> str: 3216 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3217 3218 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3219 this = self.sql(expression, "this") 3220 index = self.sql(expression, "expression") 3221 return f"{this} AT {index}" 3222 3223 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3224 this = self.sql(expression, "this") 3225 zone = self.sql(expression, "zone") 3226 return f"{this} AT TIME ZONE {zone}" 3227 3228 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3229 this = self.sql(expression, "this") 3230 zone = self.sql(expression, "zone") 3231 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3232 3233 def add_sql(self, expression: exp.Add) -> str: 3234 return self.binary(expression, "+") 3235 3236 def and_sql( 3237 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3238 ) -> str: 3239 return self.connector_sql(expression, "AND", stack) 3240 3241 def or_sql( 3242 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3243 ) -> str: 3244 return self.connector_sql(expression, "OR", stack) 3245 3246 def xor_sql( 3247 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3248 ) -> str: 3249 return self.connector_sql(expression, "XOR", stack) 3250 3251 def connector_sql( 3252 self, 3253 expression: exp.Connector, 3254 op: str, 3255 stack: t.Optional[t.List[str | exp.Expression]] = None, 3256 ) -> str: 3257 if stack is not None: 3258 if expression.expressions: 3259 stack.append(self.expressions(expression, sep=f" {op} ")) 3260 else: 3261 stack.append(expression.right) 3262 if expression.comments and self.comments: 3263 for comment in expression.comments: 3264 if comment: 3265 op += f" /*{self.sanitize_comment(comment)}*/" 3266 stack.extend((op, expression.left)) 3267 return op 3268 3269 stack = [expression] 3270 sqls: t.List[str] = [] 3271 ops = set() 3272 3273 while stack: 3274 node = stack.pop() 3275 if isinstance(node, exp.Connector): 3276 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3277 else: 3278 sql = self.sql(node) 3279 if sqls and sqls[-1] in ops: 3280 sqls[-1] += f" {sql}" 3281 else: 3282 sqls.append(sql) 3283 3284 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3285 return sep.join(sqls) 3286 3287 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3288 return self.binary(expression, "&") 3289 3290 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3291 return self.binary(expression, "<<") 3292 3293 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3294 return f"~{self.sql(expression, 'this')}" 3295 3296 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3297 return self.binary(expression, "|") 3298 3299 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3300 return self.binary(expression, ">>") 3301 3302 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3303 return self.binary(expression, "^") 3304 3305 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3306 format_sql = self.sql(expression, "format") 3307 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3308 to_sql = self.sql(expression, "to") 3309 to_sql = f" {to_sql}" if to_sql else "" 3310 action = self.sql(expression, "action") 3311 action = f" {action}" if action else "" 3312 default = self.sql(expression, "default") 3313 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3314 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3315 3316 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3317 zone = self.sql(expression, "this") 3318 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3319 3320 def collate_sql(self, expression: exp.Collate) -> str: 3321 if self.COLLATE_IS_FUNC: 3322 return self.function_fallback_sql(expression) 3323 return self.binary(expression, "COLLATE") 3324 3325 def command_sql(self, expression: exp.Command) -> str: 3326 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3327 3328 def comment_sql(self, expression: exp.Comment) -> str: 3329 this = self.sql(expression, "this") 3330 kind = expression.args["kind"] 3331 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3332 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3333 expression_sql = self.sql(expression, "expression") 3334 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3335 3336 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3337 this = self.sql(expression, "this") 3338 delete = " DELETE" if expression.args.get("delete") else "" 3339 recompress = self.sql(expression, "recompress") 3340 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3341 to_disk = self.sql(expression, "to_disk") 3342 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3343 to_volume = self.sql(expression, "to_volume") 3344 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3345 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3346 3347 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3348 where = self.sql(expression, "where") 3349 group = self.sql(expression, "group") 3350 aggregates = self.expressions(expression, key="aggregates") 3351 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3352 3353 if not (where or group or aggregates) and len(expression.expressions) == 1: 3354 return f"TTL {self.expressions(expression, flat=True)}" 3355 3356 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3357 3358 def transaction_sql(self, expression: exp.Transaction) -> str: 3359 return "BEGIN" 3360 3361 def commit_sql(self, expression: exp.Commit) -> str: 3362 chain = expression.args.get("chain") 3363 if chain is not None: 3364 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3365 3366 return f"COMMIT{chain or ''}" 3367 3368 def rollback_sql(self, expression: exp.Rollback) -> str: 3369 savepoint = expression.args.get("savepoint") 3370 savepoint = f" TO {savepoint}" if savepoint else "" 3371 return f"ROLLBACK{savepoint}" 3372 3373 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3374 this = self.sql(expression, "this") 3375 3376 dtype = self.sql(expression, "dtype") 3377 if dtype: 3378 collate = self.sql(expression, "collate") 3379 collate = f" COLLATE {collate}" if collate else "" 3380 using = self.sql(expression, "using") 3381 using = f" USING {using}" if using else "" 3382 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 3383 return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}" 3384 3385 default = self.sql(expression, "default") 3386 if default: 3387 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3388 3389 comment = self.sql(expression, "comment") 3390 if comment: 3391 return f"ALTER COLUMN {this} COMMENT {comment}" 3392 3393 visible = expression.args.get("visible") 3394 if visible: 3395 return f"ALTER COLUMN {this} SET {visible}" 3396 3397 allow_null = expression.args.get("allow_null") 3398 drop = expression.args.get("drop") 3399 3400 if not drop and not allow_null: 3401 self.unsupported("Unsupported ALTER COLUMN syntax") 3402 3403 if allow_null is not None: 3404 keyword = "DROP" if drop else "SET" 3405 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3406 3407 return f"ALTER COLUMN {this} DROP DEFAULT" 3408 3409 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3410 this = self.sql(expression, "this") 3411 3412 visible = expression.args.get("visible") 3413 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3414 3415 return f"ALTER INDEX {this} {visible_sql}" 3416 3417 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3418 this = self.sql(expression, "this") 3419 if not isinstance(expression.this, exp.Var): 3420 this = f"KEY DISTKEY {this}" 3421 return f"ALTER DISTSTYLE {this}" 3422 3423 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3424 compound = " COMPOUND" if expression.args.get("compound") else "" 3425 this = self.sql(expression, "this") 3426 expressions = self.expressions(expression, flat=True) 3427 expressions = f"({expressions})" if expressions else "" 3428 return f"ALTER{compound} SORTKEY {this or expressions}" 3429 3430 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3431 if not self.RENAME_TABLE_WITH_DB: 3432 # Remove db from tables 3433 expression = expression.transform( 3434 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3435 ).assert_is(exp.AlterRename) 3436 this = self.sql(expression, "this") 3437 return f"RENAME TO {this}" 3438 3439 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3440 exists = " IF EXISTS" if expression.args.get("exists") else "" 3441 old_column = self.sql(expression, "this") 3442 new_column = self.sql(expression, "to") 3443 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3444 3445 def alterset_sql(self, expression: exp.AlterSet) -> str: 3446 exprs = self.expressions(expression, flat=True) 3447 if self.ALTER_SET_WRAPPED: 3448 exprs = f"({exprs})" 3449 3450 return f"SET {exprs}" 3451 3452 def alter_sql(self, expression: exp.Alter) -> str: 3453 actions = expression.args["actions"] 3454 3455 if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance( 3456 actions[0], exp.ColumnDef 3457 ): 3458 actions_sql = self.expressions(expression, key="actions", flat=True) 3459 actions_sql = f"ADD {actions_sql}" 3460 else: 3461 actions_list = [] 3462 for action in actions: 3463 if isinstance(action, (exp.ColumnDef, exp.Schema)): 3464 action_sql = self.add_column_sql(action) 3465 else: 3466 action_sql = self.sql(action) 3467 if isinstance(action, exp.Query): 3468 action_sql = f"AS {action_sql}" 3469 3470 actions_list.append(action_sql) 3471 3472 actions_sql = self.format_args(*actions_list) 3473 3474 exists = " IF EXISTS" if expression.args.get("exists") else "" 3475 on_cluster = self.sql(expression, "cluster") 3476 on_cluster = f" {on_cluster}" if on_cluster else "" 3477 only = " ONLY" if expression.args.get("only") else "" 3478 options = self.expressions(expression, key="options") 3479 options = f", {options}" if options else "" 3480 kind = self.sql(expression, "kind") 3481 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3482 3483 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}" 3484 3485 def add_column_sql(self, expression: exp.Expression) -> str: 3486 sql = self.sql(expression) 3487 if isinstance(expression, exp.Schema): 3488 column_text = " COLUMNS" 3489 elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3490 column_text = " COLUMN" 3491 else: 3492 column_text = "" 3493 3494 return f"ADD{column_text} {sql}" 3495 3496 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3497 expressions = self.expressions(expression) 3498 exists = " IF EXISTS " if expression.args.get("exists") else " " 3499 return f"DROP{exists}{expressions}" 3500 3501 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3502 return f"ADD {self.expressions(expression)}" 3503 3504 def distinct_sql(self, expression: exp.Distinct) -> str: 3505 this = self.expressions(expression, flat=True) 3506 3507 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3508 case = exp.case() 3509 for arg in expression.expressions: 3510 case = case.when(arg.is_(exp.null()), exp.null()) 3511 this = self.sql(case.else_(f"({this})")) 3512 3513 this = f" {this}" if this else "" 3514 3515 on = self.sql(expression, "on") 3516 on = f" ON {on}" if on else "" 3517 return f"DISTINCT{this}{on}" 3518 3519 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3520 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3521 3522 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3523 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3524 3525 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3526 this_sql = self.sql(expression, "this") 3527 expression_sql = self.sql(expression, "expression") 3528 kind = "MAX" if expression.args.get("max") else "MIN" 3529 return f"{this_sql} HAVING {kind} {expression_sql}" 3530 3531 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3532 return self.sql( 3533 exp.Cast( 3534 this=exp.Div(this=expression.this, expression=expression.expression), 3535 to=exp.DataType(this=exp.DataType.Type.INT), 3536 ) 3537 ) 3538 3539 def dpipe_sql(self, expression: exp.DPipe) -> str: 3540 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3541 return self.func( 3542 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3543 ) 3544 return self.binary(expression, "||") 3545 3546 def div_sql(self, expression: exp.Div) -> str: 3547 l, r = expression.left, expression.right 3548 3549 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3550 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3551 3552 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3553 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3554 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3555 3556 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3557 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3558 return self.sql( 3559 exp.cast( 3560 l / r, 3561 to=exp.DataType.Type.BIGINT, 3562 ) 3563 ) 3564 3565 return self.binary(expression, "/") 3566 3567 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3568 n = exp._wrap(expression.this, exp.Binary) 3569 d = exp._wrap(expression.expression, exp.Binary) 3570 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3571 3572 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3573 return self.binary(expression, "OVERLAPS") 3574 3575 def distance_sql(self, expression: exp.Distance) -> str: 3576 return self.binary(expression, "<->") 3577 3578 def dot_sql(self, expression: exp.Dot) -> str: 3579 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3580 3581 def eq_sql(self, expression: exp.EQ) -> str: 3582 return self.binary(expression, "=") 3583 3584 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3585 return self.binary(expression, ":=") 3586 3587 def escape_sql(self, expression: exp.Escape) -> str: 3588 return self.binary(expression, "ESCAPE") 3589 3590 def glob_sql(self, expression: exp.Glob) -> str: 3591 return self.binary(expression, "GLOB") 3592 3593 def gt_sql(self, expression: exp.GT) -> str: 3594 return self.binary(expression, ">") 3595 3596 def gte_sql(self, expression: exp.GTE) -> str: 3597 return self.binary(expression, ">=") 3598 3599 def ilike_sql(self, expression: exp.ILike) -> str: 3600 return self.binary(expression, "ILIKE") 3601 3602 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3603 return self.binary(expression, "ILIKE ANY") 3604 3605 def is_sql(self, expression: exp.Is) -> str: 3606 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3607 return self.sql( 3608 expression.this if expression.expression.this else exp.not_(expression.this) 3609 ) 3610 return self.binary(expression, "IS") 3611 3612 def like_sql(self, expression: exp.Like) -> str: 3613 return self.binary(expression, "LIKE") 3614 3615 def likeany_sql(self, expression: exp.LikeAny) -> str: 3616 return self.binary(expression, "LIKE ANY") 3617 3618 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3619 return self.binary(expression, "SIMILAR TO") 3620 3621 def lt_sql(self, expression: exp.LT) -> str: 3622 return self.binary(expression, "<") 3623 3624 def lte_sql(self, expression: exp.LTE) -> str: 3625 return self.binary(expression, "<=") 3626 3627 def mod_sql(self, expression: exp.Mod) -> str: 3628 return self.binary(expression, "%") 3629 3630 def mul_sql(self, expression: exp.Mul) -> str: 3631 return self.binary(expression, "*") 3632 3633 def neq_sql(self, expression: exp.NEQ) -> str: 3634 return self.binary(expression, "<>") 3635 3636 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3637 return self.binary(expression, "IS NOT DISTINCT FROM") 3638 3639 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3640 return self.binary(expression, "IS DISTINCT FROM") 3641 3642 def slice_sql(self, expression: exp.Slice) -> str: 3643 return self.binary(expression, ":") 3644 3645 def sub_sql(self, expression: exp.Sub) -> str: 3646 return self.binary(expression, "-") 3647 3648 def trycast_sql(self, expression: exp.TryCast) -> str: 3649 return self.cast_sql(expression, safe_prefix="TRY_") 3650 3651 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3652 return self.cast_sql(expression) 3653 3654 def try_sql(self, expression: exp.Try) -> str: 3655 if not self.TRY_SUPPORTED: 3656 self.unsupported("Unsupported TRY function") 3657 return self.sql(expression, "this") 3658 3659 return self.func("TRY", expression.this) 3660 3661 def log_sql(self, expression: exp.Log) -> str: 3662 this = expression.this 3663 expr = expression.expression 3664 3665 if self.dialect.LOG_BASE_FIRST is False: 3666 this, expr = expr, this 3667 elif self.dialect.LOG_BASE_FIRST is None and expr: 3668 if this.name in ("2", "10"): 3669 return self.func(f"LOG{this.name}", expr) 3670 3671 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3672 3673 return self.func("LOG", this, expr) 3674 3675 def use_sql(self, expression: exp.Use) -> str: 3676 kind = self.sql(expression, "kind") 3677 kind = f" {kind}" if kind else "" 3678 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3679 this = f" {this}" if this else "" 3680 return f"USE{kind}{this}" 3681 3682 def binary(self, expression: exp.Binary, op: str) -> str: 3683 sqls: t.List[str] = [] 3684 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3685 binary_type = type(expression) 3686 3687 while stack: 3688 node = stack.pop() 3689 3690 if type(node) is binary_type: 3691 op_func = node.args.get("operator") 3692 if op_func: 3693 op = f"OPERATOR({self.sql(op_func)})" 3694 3695 stack.append(node.right) 3696 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3697 stack.append(node.left) 3698 else: 3699 sqls.append(self.sql(node)) 3700 3701 return "".join(sqls) 3702 3703 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3704 to_clause = self.sql(expression, "to") 3705 if to_clause: 3706 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3707 3708 return self.function_fallback_sql(expression) 3709 3710 def function_fallback_sql(self, expression: exp.Func) -> str: 3711 args = [] 3712 3713 for key in expression.arg_types: 3714 arg_value = expression.args.get(key) 3715 3716 if isinstance(arg_value, list): 3717 for value in arg_value: 3718 args.append(value) 3719 elif arg_value is not None: 3720 args.append(arg_value) 3721 3722 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3723 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3724 else: 3725 name = expression.sql_name() 3726 3727 return self.func(name, *args) 3728 3729 def func( 3730 self, 3731 name: str, 3732 *args: t.Optional[exp.Expression | str], 3733 prefix: str = "(", 3734 suffix: str = ")", 3735 normalize: bool = True, 3736 ) -> str: 3737 name = self.normalize_func(name) if normalize else name 3738 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3739 3740 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3741 arg_sqls = tuple( 3742 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3743 ) 3744 if self.pretty and self.too_wide(arg_sqls): 3745 return self.indent( 3746 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3747 ) 3748 return sep.join(arg_sqls) 3749 3750 def too_wide(self, args: t.Iterable) -> bool: 3751 return sum(len(arg) for arg in args) > self.max_text_width 3752 3753 def format_time( 3754 self, 3755 expression: exp.Expression, 3756 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3757 inverse_time_trie: t.Optional[t.Dict] = None, 3758 ) -> t.Optional[str]: 3759 return format_time( 3760 self.sql(expression, "format"), 3761 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3762 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3763 ) 3764 3765 def expressions( 3766 self, 3767 expression: t.Optional[exp.Expression] = None, 3768 key: t.Optional[str] = None, 3769 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3770 flat: bool = False, 3771 indent: bool = True, 3772 skip_first: bool = False, 3773 skip_last: bool = False, 3774 sep: str = ", ", 3775 prefix: str = "", 3776 dynamic: bool = False, 3777 new_line: bool = False, 3778 ) -> str: 3779 expressions = expression.args.get(key or "expressions") if expression else sqls 3780 3781 if not expressions: 3782 return "" 3783 3784 if flat: 3785 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3786 3787 num_sqls = len(expressions) 3788 result_sqls = [] 3789 3790 for i, e in enumerate(expressions): 3791 sql = self.sql(e, comment=False) 3792 if not sql: 3793 continue 3794 3795 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3796 3797 if self.pretty: 3798 if self.leading_comma: 3799 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3800 else: 3801 result_sqls.append( 3802 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3803 ) 3804 else: 3805 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3806 3807 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3808 if new_line: 3809 result_sqls.insert(0, "") 3810 result_sqls.append("") 3811 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3812 else: 3813 result_sql = "".join(result_sqls) 3814 3815 return ( 3816 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3817 if indent 3818 else result_sql 3819 ) 3820 3821 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3822 flat = flat or isinstance(expression.parent, exp.Properties) 3823 expressions_sql = self.expressions(expression, flat=flat) 3824 if flat: 3825 return f"{op} {expressions_sql}" 3826 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3827 3828 def naked_property(self, expression: exp.Property) -> str: 3829 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3830 if not property_name: 3831 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3832 return f"{property_name} {self.sql(expression, 'this')}" 3833 3834 def tag_sql(self, expression: exp.Tag) -> str: 3835 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3836 3837 def token_sql(self, token_type: TokenType) -> str: 3838 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3839 3840 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3841 this = self.sql(expression, "this") 3842 expressions = self.no_identify(self.expressions, expression) 3843 expressions = ( 3844 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3845 ) 3846 return f"{this}{expressions}" if expressions.strip() != "" else this 3847 3848 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3849 this = self.sql(expression, "this") 3850 expressions = self.expressions(expression, flat=True) 3851 return f"{this}({expressions})" 3852 3853 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3854 return self.binary(expression, "=>") 3855 3856 def when_sql(self, expression: exp.When) -> str: 3857 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3858 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3859 condition = self.sql(expression, "condition") 3860 condition = f" AND {condition}" if condition else "" 3861 3862 then_expression = expression.args.get("then") 3863 if isinstance(then_expression, exp.Insert): 3864 this = self.sql(then_expression, "this") 3865 this = f"INSERT {this}" if this else "INSERT" 3866 then = self.sql(then_expression, "expression") 3867 then = f"{this} VALUES {then}" if then else this 3868 elif isinstance(then_expression, exp.Update): 3869 if isinstance(then_expression.args.get("expressions"), exp.Star): 3870 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3871 else: 3872 then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}" 3873 else: 3874 then = self.sql(then_expression) 3875 return f"WHEN {matched}{source}{condition} THEN {then}" 3876 3877 def whens_sql(self, expression: exp.Whens) -> str: 3878 return self.expressions(expression, sep=" ", indent=False) 3879 3880 def merge_sql(self, expression: exp.Merge) -> str: 3881 table = expression.this 3882 table_alias = "" 3883 3884 hints = table.args.get("hints") 3885 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3886 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3887 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3888 3889 this = self.sql(table) 3890 using = f"USING {self.sql(expression, 'using')}" 3891 on = f"ON {self.sql(expression, 'on')}" 3892 whens = self.sql(expression, "whens") 3893 3894 returning = self.sql(expression, "returning") 3895 if returning: 3896 whens = f"{whens}{returning}" 3897 3898 sep = self.sep() 3899 3900 return self.prepend_ctes( 3901 expression, 3902 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3903 ) 3904 3905 @unsupported_args("format") 3906 def tochar_sql(self, expression: exp.ToChar) -> str: 3907 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3908 3909 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3910 if not self.SUPPORTS_TO_NUMBER: 3911 self.unsupported("Unsupported TO_NUMBER function") 3912 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3913 3914 fmt = expression.args.get("format") 3915 if not fmt: 3916 self.unsupported("Conversion format is required for TO_NUMBER") 3917 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3918 3919 return self.func("TO_NUMBER", expression.this, fmt) 3920 3921 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3922 this = self.sql(expression, "this") 3923 kind = self.sql(expression, "kind") 3924 settings_sql = self.expressions(expression, key="settings", sep=" ") 3925 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3926 return f"{this}({kind}{args})" 3927 3928 def dictrange_sql(self, expression: exp.DictRange) -> str: 3929 this = self.sql(expression, "this") 3930 max = self.sql(expression, "max") 3931 min = self.sql(expression, "min") 3932 return f"{this}(MIN {min} MAX {max})" 3933 3934 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3935 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3936 3937 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3938 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3939 3940 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3941 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3942 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3943 3944 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3945 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3946 expressions = self.expressions(expression, flat=True) 3947 expressions = f" {self.wrap(expressions)}" if expressions else "" 3948 buckets = self.sql(expression, "buckets") 3949 kind = self.sql(expression, "kind") 3950 buckets = f" BUCKETS {buckets}" if buckets else "" 3951 order = self.sql(expression, "order") 3952 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3953 3954 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3955 return "" 3956 3957 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3958 expressions = self.expressions(expression, key="expressions", flat=True) 3959 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3960 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3961 buckets = self.sql(expression, "buckets") 3962 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3963 3964 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3965 this = self.sql(expression, "this") 3966 having = self.sql(expression, "having") 3967 3968 if having: 3969 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3970 3971 return self.func("ANY_VALUE", this) 3972 3973 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3974 transform = self.func("TRANSFORM", *expression.expressions) 3975 row_format_before = self.sql(expression, "row_format_before") 3976 row_format_before = f" {row_format_before}" if row_format_before else "" 3977 record_writer = self.sql(expression, "record_writer") 3978 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3979 using = f" USING {self.sql(expression, 'command_script')}" 3980 schema = self.sql(expression, "schema") 3981 schema = f" AS {schema}" if schema else "" 3982 row_format_after = self.sql(expression, "row_format_after") 3983 row_format_after = f" {row_format_after}" if row_format_after else "" 3984 record_reader = self.sql(expression, "record_reader") 3985 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3986 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3987 3988 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3989 key_block_size = self.sql(expression, "key_block_size") 3990 if key_block_size: 3991 return f"KEY_BLOCK_SIZE = {key_block_size}" 3992 3993 using = self.sql(expression, "using") 3994 if using: 3995 return f"USING {using}" 3996 3997 parser = self.sql(expression, "parser") 3998 if parser: 3999 return f"WITH PARSER {parser}" 4000 4001 comment = self.sql(expression, "comment") 4002 if comment: 4003 return f"COMMENT {comment}" 4004 4005 visible = expression.args.get("visible") 4006 if visible is not None: 4007 return "VISIBLE" if visible else "INVISIBLE" 4008 4009 engine_attr = self.sql(expression, "engine_attr") 4010 if engine_attr: 4011 return f"ENGINE_ATTRIBUTE = {engine_attr}" 4012 4013 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 4014 if secondary_engine_attr: 4015 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 4016 4017 self.unsupported("Unsupported index constraint option.") 4018 return "" 4019 4020 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 4021 enforced = " ENFORCED" if expression.args.get("enforced") else "" 4022 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 4023 4024 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 4025 kind = self.sql(expression, "kind") 4026 kind = f"{kind} INDEX" if kind else "INDEX" 4027 this = self.sql(expression, "this") 4028 this = f" {this}" if this else "" 4029 index_type = self.sql(expression, "index_type") 4030 index_type = f" USING {index_type}" if index_type else "" 4031 expressions = self.expressions(expression, flat=True) 4032 expressions = f" ({expressions})" if expressions else "" 4033 options = self.expressions(expression, key="options", sep=" ") 4034 options = f" {options}" if options else "" 4035 return f"{kind}{this}{index_type}{expressions}{options}" 4036 4037 def nvl2_sql(self, expression: exp.Nvl2) -> str: 4038 if self.NVL2_SUPPORTED: 4039 return self.function_fallback_sql(expression) 4040 4041 case = exp.Case().when( 4042 expression.this.is_(exp.null()).not_(copy=False), 4043 expression.args["true"], 4044 copy=False, 4045 ) 4046 else_cond = expression.args.get("false") 4047 if else_cond: 4048 case.else_(else_cond, copy=False) 4049 4050 return self.sql(case) 4051 4052 def comprehension_sql(self, expression: exp.Comprehension) -> str: 4053 this = self.sql(expression, "this") 4054 expr = self.sql(expression, "expression") 4055 iterator = self.sql(expression, "iterator") 4056 condition = self.sql(expression, "condition") 4057 condition = f" IF {condition}" if condition else "" 4058 return f"{this} FOR {expr} IN {iterator}{condition}" 4059 4060 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 4061 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 4062 4063 def opclass_sql(self, expression: exp.Opclass) -> str: 4064 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 4065 4066 def predict_sql(self, expression: exp.Predict) -> str: 4067 model = self.sql(expression, "this") 4068 model = f"MODEL {model}" 4069 table = self.sql(expression, "expression") 4070 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 4071 parameters = self.sql(expression, "params_struct") 4072 return self.func("PREDICT", model, table, parameters or None) 4073 4074 def forin_sql(self, expression: exp.ForIn) -> str: 4075 this = self.sql(expression, "this") 4076 expression_sql = self.sql(expression, "expression") 4077 return f"FOR {this} DO {expression_sql}" 4078 4079 def refresh_sql(self, expression: exp.Refresh) -> str: 4080 this = self.sql(expression, "this") 4081 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 4082 return f"REFRESH {table}{this}" 4083 4084 def toarray_sql(self, expression: exp.ToArray) -> str: 4085 arg = expression.this 4086 if not arg.type: 4087 from sqlglot.optimizer.annotate_types import annotate_types 4088 4089 arg = annotate_types(arg, dialect=self.dialect) 4090 4091 if arg.is_type(exp.DataType.Type.ARRAY): 4092 return self.sql(arg) 4093 4094 cond_for_null = arg.is_(exp.null()) 4095 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4096 4097 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4098 this = expression.this 4099 time_format = self.format_time(expression) 4100 4101 if time_format: 4102 return self.sql( 4103 exp.cast( 4104 exp.StrToTime(this=this, format=expression.args["format"]), 4105 exp.DataType.Type.TIME, 4106 ) 4107 ) 4108 4109 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4110 return self.sql(this) 4111 4112 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4113 4114 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4115 this = expression.this 4116 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4117 return self.sql(this) 4118 4119 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4120 4121 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4122 this = expression.this 4123 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4124 return self.sql(this) 4125 4126 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4127 4128 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4129 this = expression.this 4130 time_format = self.format_time(expression) 4131 4132 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4133 return self.sql( 4134 exp.cast( 4135 exp.StrToTime(this=this, format=expression.args["format"]), 4136 exp.DataType.Type.DATE, 4137 ) 4138 ) 4139 4140 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4141 return self.sql(this) 4142 4143 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4144 4145 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4146 return self.sql( 4147 exp.func( 4148 "DATEDIFF", 4149 expression.this, 4150 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4151 "day", 4152 ) 4153 ) 4154 4155 def lastday_sql(self, expression: exp.LastDay) -> str: 4156 if self.LAST_DAY_SUPPORTS_DATE_PART: 4157 return self.function_fallback_sql(expression) 4158 4159 unit = expression.text("unit") 4160 if unit and unit != "MONTH": 4161 self.unsupported("Date parts are not supported in LAST_DAY.") 4162 4163 return self.func("LAST_DAY", expression.this) 4164 4165 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4166 from sqlglot.dialects.dialect import unit_to_str 4167 4168 return self.func( 4169 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4170 ) 4171 4172 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4173 if self.CAN_IMPLEMENT_ARRAY_ANY: 4174 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4175 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4176 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4177 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4178 4179 from sqlglot.dialects import Dialect 4180 4181 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4182 if self.dialect.__class__ != Dialect: 4183 self.unsupported("ARRAY_ANY is unsupported") 4184 4185 return self.function_fallback_sql(expression) 4186 4187 def struct_sql(self, expression: exp.Struct) -> str: 4188 expression.set( 4189 "expressions", 4190 [ 4191 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4192 if isinstance(e, exp.PropertyEQ) 4193 else e 4194 for e in expression.expressions 4195 ], 4196 ) 4197 4198 return self.function_fallback_sql(expression) 4199 4200 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4201 low = self.sql(expression, "this") 4202 high = self.sql(expression, "expression") 4203 4204 return f"{low} TO {high}" 4205 4206 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4207 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4208 tables = f" {self.expressions(expression)}" 4209 4210 exists = " IF EXISTS" if expression.args.get("exists") else "" 4211 4212 on_cluster = self.sql(expression, "cluster") 4213 on_cluster = f" {on_cluster}" if on_cluster else "" 4214 4215 identity = self.sql(expression, "identity") 4216 identity = f" {identity} IDENTITY" if identity else "" 4217 4218 option = self.sql(expression, "option") 4219 option = f" {option}" if option else "" 4220 4221 partition = self.sql(expression, "partition") 4222 partition = f" {partition}" if partition else "" 4223 4224 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4225 4226 # This transpiles T-SQL's CONVERT function 4227 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4228 def convert_sql(self, expression: exp.Convert) -> str: 4229 to = expression.this 4230 value = expression.expression 4231 style = expression.args.get("style") 4232 safe = expression.args.get("safe") 4233 strict = expression.args.get("strict") 4234 4235 if not to or not value: 4236 return "" 4237 4238 # Retrieve length of datatype and override to default if not specified 4239 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4240 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4241 4242 transformed: t.Optional[exp.Expression] = None 4243 cast = exp.Cast if strict else exp.TryCast 4244 4245 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4246 if isinstance(style, exp.Literal) and style.is_int: 4247 from sqlglot.dialects.tsql import TSQL 4248 4249 style_value = style.name 4250 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4251 if not converted_style: 4252 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4253 4254 fmt = exp.Literal.string(converted_style) 4255 4256 if to.this == exp.DataType.Type.DATE: 4257 transformed = exp.StrToDate(this=value, format=fmt) 4258 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4259 transformed = exp.StrToTime(this=value, format=fmt) 4260 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4261 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4262 elif to.this == exp.DataType.Type.TEXT: 4263 transformed = exp.TimeToStr(this=value, format=fmt) 4264 4265 if not transformed: 4266 transformed = cast(this=value, to=to, safe=safe) 4267 4268 return self.sql(transformed) 4269 4270 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4271 this = expression.this 4272 if isinstance(this, exp.JSONPathWildcard): 4273 this = self.json_path_part(this) 4274 return f".{this}" if this else "" 4275 4276 if exp.SAFE_IDENTIFIER_RE.match(this): 4277 return f".{this}" 4278 4279 this = self.json_path_part(this) 4280 return ( 4281 f"[{this}]" 4282 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4283 else f".{this}" 4284 ) 4285 4286 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4287 this = self.json_path_part(expression.this) 4288 return f"[{this}]" if this else "" 4289 4290 def _simplify_unless_literal(self, expression: E) -> E: 4291 if not isinstance(expression, exp.Literal): 4292 from sqlglot.optimizer.simplify import simplify 4293 4294 expression = simplify(expression, dialect=self.dialect) 4295 4296 return expression 4297 4298 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4299 this = expression.this 4300 if isinstance(this, self.RESPECT_IGNORE_NULLS_UNSUPPORTED_EXPRESSIONS): 4301 self.unsupported( 4302 f"RESPECT/IGNORE NULLS is not supported for {type(this).key} in {self.dialect.__class__.__name__}" 4303 ) 4304 return self.sql(this) 4305 4306 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4307 # The first modifier here will be the one closest to the AggFunc's arg 4308 mods = sorted( 4309 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4310 key=lambda x: 0 4311 if isinstance(x, exp.HavingMax) 4312 else (1 if isinstance(x, exp.Order) else 2), 4313 ) 4314 4315 if mods: 4316 mod = mods[0] 4317 this = expression.__class__(this=mod.this.copy()) 4318 this.meta["inline"] = True 4319 mod.this.replace(this) 4320 return self.sql(expression.this) 4321 4322 agg_func = expression.find(exp.AggFunc) 4323 4324 if agg_func: 4325 agg_func_sql = self.sql(agg_func, comment=False)[:-1] + f" {text})" 4326 return self.maybe_comment(agg_func_sql, comments=agg_func.comments) 4327 4328 return f"{self.sql(expression, 'this')} {text}" 4329 4330 def _replace_line_breaks(self, string: str) -> str: 4331 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4332 if self.pretty: 4333 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4334 return string 4335 4336 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4337 option = self.sql(expression, "this") 4338 4339 if expression.expressions: 4340 upper = option.upper() 4341 4342 # Snowflake FILE_FORMAT options are separated by whitespace 4343 sep = " " if upper == "FILE_FORMAT" else ", " 4344 4345 # Databricks copy/format options do not set their list of values with EQ 4346 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4347 values = self.expressions(expression, flat=True, sep=sep) 4348 return f"{option}{op}({values})" 4349 4350 value = self.sql(expression, "expression") 4351 4352 if not value: 4353 return option 4354 4355 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4356 4357 return f"{option}{op}{value}" 4358 4359 def credentials_sql(self, expression: exp.Credentials) -> str: 4360 cred_expr = expression.args.get("credentials") 4361 if isinstance(cred_expr, exp.Literal): 4362 # Redshift case: CREDENTIALS <string> 4363 credentials = self.sql(expression, "credentials") 4364 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4365 else: 4366 # Snowflake case: CREDENTIALS = (...) 4367 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4368 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4369 4370 storage = self.sql(expression, "storage") 4371 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4372 4373 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4374 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4375 4376 iam_role = self.sql(expression, "iam_role") 4377 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4378 4379 region = self.sql(expression, "region") 4380 region = f" REGION {region}" if region else "" 4381 4382 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4383 4384 def copy_sql(self, expression: exp.Copy) -> str: 4385 this = self.sql(expression, "this") 4386 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4387 4388 credentials = self.sql(expression, "credentials") 4389 credentials = self.seg(credentials) if credentials else "" 4390 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4391 files = self.expressions(expression, key="files", flat=True) 4392 4393 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4394 params = self.expressions( 4395 expression, 4396 key="params", 4397 sep=sep, 4398 new_line=True, 4399 skip_last=True, 4400 skip_first=True, 4401 indent=self.COPY_PARAMS_ARE_WRAPPED, 4402 ) 4403 4404 if params: 4405 if self.COPY_PARAMS_ARE_WRAPPED: 4406 params = f" WITH ({params})" 4407 elif not self.pretty: 4408 params = f" {params}" 4409 4410 return f"COPY{this}{kind} {files}{credentials}{params}" 4411 4412 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4413 return "" 4414 4415 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4416 on_sql = "ON" if expression.args.get("on") else "OFF" 4417 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4418 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4419 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4420 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4421 4422 if filter_col or retention_period: 4423 on_sql = self.func("ON", filter_col, retention_period) 4424 4425 return f"DATA_DELETION={on_sql}" 4426 4427 def maskingpolicycolumnconstraint_sql( 4428 self, expression: exp.MaskingPolicyColumnConstraint 4429 ) -> str: 4430 this = self.sql(expression, "this") 4431 expressions = self.expressions(expression, flat=True) 4432 expressions = f" USING ({expressions})" if expressions else "" 4433 return f"MASKING POLICY {this}{expressions}" 4434 4435 def gapfill_sql(self, expression: exp.GapFill) -> str: 4436 this = self.sql(expression, "this") 4437 this = f"TABLE {this}" 4438 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4439 4440 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4441 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4442 4443 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4444 this = self.sql(expression, "this") 4445 expr = expression.expression 4446 4447 if isinstance(expr, exp.Func): 4448 # T-SQL's CLR functions are case sensitive 4449 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4450 else: 4451 expr = self.sql(expression, "expression") 4452 4453 return self.scope_resolution(expr, this) 4454 4455 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4456 if self.PARSE_JSON_NAME is None: 4457 return self.sql(expression.this) 4458 4459 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4460 4461 def rand_sql(self, expression: exp.Rand) -> str: 4462 lower = self.sql(expression, "lower") 4463 upper = self.sql(expression, "upper") 4464 4465 if lower and upper: 4466 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4467 return self.func("RAND", expression.this) 4468 4469 def changes_sql(self, expression: exp.Changes) -> str: 4470 information = self.sql(expression, "information") 4471 information = f"INFORMATION => {information}" 4472 at_before = self.sql(expression, "at_before") 4473 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4474 end = self.sql(expression, "end") 4475 end = f"{self.seg('')}{end}" if end else "" 4476 4477 return f"CHANGES ({information}){at_before}{end}" 4478 4479 def pad_sql(self, expression: exp.Pad) -> str: 4480 prefix = "L" if expression.args.get("is_left") else "R" 4481 4482 fill_pattern = self.sql(expression, "fill_pattern") or None 4483 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4484 fill_pattern = "' '" 4485 4486 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4487 4488 def summarize_sql(self, expression: exp.Summarize) -> str: 4489 table = " TABLE" if expression.args.get("table") else "" 4490 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4491 4492 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4493 generate_series = exp.GenerateSeries(**expression.args) 4494 4495 parent = expression.parent 4496 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4497 parent = parent.parent 4498 4499 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4500 return self.sql(exp.Unnest(expressions=[generate_series])) 4501 4502 if isinstance(parent, exp.Select): 4503 self.unsupported("GenerateSeries projection unnesting is not supported.") 4504 4505 return self.sql(generate_series) 4506 4507 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4508 exprs = expression.expressions 4509 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4510 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4511 else: 4512 rhs = self.expressions(expression) 4513 4514 return self.func(name, expression.this, rhs or None) 4515 4516 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4517 if self.SUPPORTS_CONVERT_TIMEZONE: 4518 return self.function_fallback_sql(expression) 4519 4520 source_tz = expression.args.get("source_tz") 4521 target_tz = expression.args.get("target_tz") 4522 timestamp = expression.args.get("timestamp") 4523 4524 if source_tz and timestamp: 4525 timestamp = exp.AtTimeZone( 4526 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4527 ) 4528 4529 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4530 4531 return self.sql(expr) 4532 4533 def json_sql(self, expression: exp.JSON) -> str: 4534 this = self.sql(expression, "this") 4535 this = f" {this}" if this else "" 4536 4537 _with = expression.args.get("with") 4538 4539 if _with is None: 4540 with_sql = "" 4541 elif not _with: 4542 with_sql = " WITHOUT" 4543 else: 4544 with_sql = " WITH" 4545 4546 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4547 4548 return f"JSON{this}{with_sql}{unique_sql}" 4549 4550 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4551 def _generate_on_options(arg: t.Any) -> str: 4552 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4553 4554 path = self.sql(expression, "path") 4555 returning = self.sql(expression, "returning") 4556 returning = f" RETURNING {returning}" if returning else "" 4557 4558 on_condition = self.sql(expression, "on_condition") 4559 on_condition = f" {on_condition}" if on_condition else "" 4560 4561 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4562 4563 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4564 else_ = "ELSE " if expression.args.get("else_") else "" 4565 condition = self.sql(expression, "expression") 4566 condition = f"WHEN {condition} THEN " if condition else else_ 4567 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4568 return f"{condition}{insert}" 4569 4570 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4571 kind = self.sql(expression, "kind") 4572 expressions = self.seg(self.expressions(expression, sep=" ")) 4573 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4574 return res 4575 4576 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4577 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4578 empty = expression.args.get("empty") 4579 empty = ( 4580 f"DEFAULT {empty} ON EMPTY" 4581 if isinstance(empty, exp.Expression) 4582 else self.sql(expression, "empty") 4583 ) 4584 4585 error = expression.args.get("error") 4586 error = ( 4587 f"DEFAULT {error} ON ERROR" 4588 if isinstance(error, exp.Expression) 4589 else self.sql(expression, "error") 4590 ) 4591 4592 if error and empty: 4593 error = ( 4594 f"{empty} {error}" 4595 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4596 else f"{error} {empty}" 4597 ) 4598 empty = "" 4599 4600 null = self.sql(expression, "null") 4601 4602 return f"{empty}{error}{null}" 4603 4604 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4605 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4606 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4607 4608 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4609 this = self.sql(expression, "this") 4610 path = self.sql(expression, "path") 4611 4612 passing = self.expressions(expression, "passing") 4613 passing = f" PASSING {passing}" if passing else "" 4614 4615 on_condition = self.sql(expression, "on_condition") 4616 on_condition = f" {on_condition}" if on_condition else "" 4617 4618 path = f"{path}{passing}{on_condition}" 4619 4620 return self.func("JSON_EXISTS", this, path) 4621 4622 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4623 array_agg = self.function_fallback_sql(expression) 4624 4625 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4626 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4627 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4628 parent = expression.parent 4629 if isinstance(parent, exp.Filter): 4630 parent_cond = parent.expression.this 4631 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4632 else: 4633 this = expression.this 4634 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4635 if this.find(exp.Column): 4636 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4637 this_sql = ( 4638 self.expressions(this) 4639 if isinstance(this, exp.Distinct) 4640 else self.sql(expression, "this") 4641 ) 4642 4643 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4644 4645 return array_agg 4646 4647 def apply_sql(self, expression: exp.Apply) -> str: 4648 this = self.sql(expression, "this") 4649 expr = self.sql(expression, "expression") 4650 4651 return f"{this} APPLY({expr})" 4652 4653 def grant_sql(self, expression: exp.Grant) -> str: 4654 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4655 4656 kind = self.sql(expression, "kind") 4657 kind = f" {kind}" if kind else "" 4658 4659 securable = self.sql(expression, "securable") 4660 securable = f" {securable}" if securable else "" 4661 4662 principals = self.expressions(expression, key="principals", flat=True) 4663 4664 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4665 4666 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4667 4668 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4669 this = self.sql(expression, "this") 4670 columns = self.expressions(expression, flat=True) 4671 columns = f"({columns})" if columns else "" 4672 4673 return f"{this}{columns}" 4674 4675 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4676 this = self.sql(expression, "this") 4677 4678 kind = self.sql(expression, "kind") 4679 kind = f"{kind} " if kind else "" 4680 4681 return f"{kind}{this}" 4682 4683 def columns_sql(self, expression: exp.Columns): 4684 func = self.function_fallback_sql(expression) 4685 if expression.args.get("unpack"): 4686 func = f"*{func}" 4687 4688 return func 4689 4690 def overlay_sql(self, expression: exp.Overlay): 4691 this = self.sql(expression, "this") 4692 expr = self.sql(expression, "expression") 4693 from_sql = self.sql(expression, "from") 4694 for_sql = self.sql(expression, "for") 4695 for_sql = f" FOR {for_sql}" if for_sql else "" 4696 4697 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4698 4699 @unsupported_args("format") 4700 def todouble_sql(self, expression: exp.ToDouble) -> str: 4701 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4702 4703 def string_sql(self, expression: exp.String) -> str: 4704 this = expression.this 4705 zone = expression.args.get("zone") 4706 4707 if zone: 4708 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4709 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4710 # set for source_tz to transpile the time conversion before the STRING cast 4711 this = exp.ConvertTimezone( 4712 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4713 ) 4714 4715 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4716 4717 def median_sql(self, expression: exp.Median): 4718 if not self.SUPPORTS_MEDIAN: 4719 return self.sql( 4720 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4721 ) 4722 4723 return self.function_fallback_sql(expression) 4724 4725 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4726 filler = self.sql(expression, "this") 4727 filler = f" {filler}" if filler else "" 4728 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4729 return f"TRUNCATE{filler} {with_count}" 4730 4731 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4732 if self.SUPPORTS_UNIX_SECONDS: 4733 return self.function_fallback_sql(expression) 4734 4735 start_ts = exp.cast( 4736 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4737 ) 4738 4739 return self.sql( 4740 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4741 ) 4742 4743 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4744 dim = expression.expression 4745 4746 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4747 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4748 if not (dim.is_int and dim.name == "1"): 4749 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4750 dim = None 4751 4752 # If dimension is required but not specified, default initialize it 4753 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4754 dim = exp.Literal.number(1) 4755 4756 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4757 4758 def attach_sql(self, expression: exp.Attach) -> str: 4759 this = self.sql(expression, "this") 4760 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4761 expressions = self.expressions(expression) 4762 expressions = f" ({expressions})" if expressions else "" 4763 4764 return f"ATTACH{exists_sql} {this}{expressions}" 4765 4766 def detach_sql(self, expression: exp.Detach) -> str: 4767 this = self.sql(expression, "this") 4768 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4769 4770 return f"DETACH{exists_sql} {this}" 4771 4772 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4773 this = self.sql(expression, "this") 4774 value = self.sql(expression, "expression") 4775 value = f" {value}" if value else "" 4776 return f"{this}{value}" 4777 4778 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4779 this_sql = self.sql(expression, "this") 4780 if isinstance(expression.this, exp.Table): 4781 this_sql = f"TABLE {this_sql}" 4782 4783 return self.func( 4784 "FEATURES_AT_TIME", 4785 this_sql, 4786 expression.args.get("time"), 4787 expression.args.get("num_rows"), 4788 expression.args.get("ignore_feature_nulls"), 4789 ) 4790 4791 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4792 return ( 4793 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4794 ) 4795 4796 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4797 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4798 encode = f"{encode} {self.sql(expression, 'this')}" 4799 4800 properties = expression.args.get("properties") 4801 if properties: 4802 encode = f"{encode} {self.properties(properties)}" 4803 4804 return encode 4805 4806 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4807 this = self.sql(expression, "this") 4808 include = f"INCLUDE {this}" 4809 4810 column_def = self.sql(expression, "column_def") 4811 if column_def: 4812 include = f"{include} {column_def}" 4813 4814 alias = self.sql(expression, "alias") 4815 if alias: 4816 include = f"{include} AS {alias}" 4817 4818 return include 4819 4820 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4821 name = f"NAME {self.sql(expression, 'this')}" 4822 return self.func("XMLELEMENT", name, *expression.expressions) 4823 4824 def xmlkeyvalueoption_sql(self, expression: exp.XMLKeyValueOption) -> str: 4825 this = self.sql(expression, "this") 4826 expr = self.sql(expression, "expression") 4827 expr = f"({expr})" if expr else "" 4828 return f"{this}{expr}" 4829 4830 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4831 partitions = self.expressions(expression, "partition_expressions") 4832 create = self.expressions(expression, "create_expressions") 4833 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4834 4835 def partitionbyrangepropertydynamic_sql( 4836 self, expression: exp.PartitionByRangePropertyDynamic 4837 ) -> str: 4838 start = self.sql(expression, "start") 4839 end = self.sql(expression, "end") 4840 4841 every = expression.args["every"] 4842 if isinstance(every, exp.Interval) and every.this.is_string: 4843 every.this.replace(exp.Literal.number(every.name)) 4844 4845 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4846 4847 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4848 name = self.sql(expression, "this") 4849 values = self.expressions(expression, flat=True) 4850 4851 return f"NAME {name} VALUE {values}" 4852 4853 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4854 kind = self.sql(expression, "kind") 4855 sample = self.sql(expression, "sample") 4856 return f"SAMPLE {sample} {kind}" 4857 4858 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4859 kind = self.sql(expression, "kind") 4860 option = self.sql(expression, "option") 4861 option = f" {option}" if option else "" 4862 this = self.sql(expression, "this") 4863 this = f" {this}" if this else "" 4864 columns = self.expressions(expression) 4865 columns = f" {columns}" if columns else "" 4866 return f"{kind}{option} STATISTICS{this}{columns}" 4867 4868 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4869 this = self.sql(expression, "this") 4870 columns = self.expressions(expression) 4871 inner_expression = self.sql(expression, "expression") 4872 inner_expression = f" {inner_expression}" if inner_expression else "" 4873 update_options = self.sql(expression, "update_options") 4874 update_options = f" {update_options} UPDATE" if update_options else "" 4875 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4876 4877 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4878 kind = self.sql(expression, "kind") 4879 kind = f" {kind}" if kind else "" 4880 return f"DELETE{kind} STATISTICS" 4881 4882 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4883 inner_expression = self.sql(expression, "expression") 4884 return f"LIST CHAINED ROWS{inner_expression}" 4885 4886 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4887 kind = self.sql(expression, "kind") 4888 this = self.sql(expression, "this") 4889 this = f" {this}" if this else "" 4890 inner_expression = self.sql(expression, "expression") 4891 return f"VALIDATE {kind}{this}{inner_expression}" 4892 4893 def analyze_sql(self, expression: exp.Analyze) -> str: 4894 options = self.expressions(expression, key="options", sep=" ") 4895 options = f" {options}" if options else "" 4896 kind = self.sql(expression, "kind") 4897 kind = f" {kind}" if kind else "" 4898 this = self.sql(expression, "this") 4899 this = f" {this}" if this else "" 4900 mode = self.sql(expression, "mode") 4901 mode = f" {mode}" if mode else "" 4902 properties = self.sql(expression, "properties") 4903 properties = f" {properties}" if properties else "" 4904 partition = self.sql(expression, "partition") 4905 partition = f" {partition}" if partition else "" 4906 inner_expression = self.sql(expression, "expression") 4907 inner_expression = f" {inner_expression}" if inner_expression else "" 4908 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4909 4910 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4911 this = self.sql(expression, "this") 4912 namespaces = self.expressions(expression, key="namespaces") 4913 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4914 passing = self.expressions(expression, key="passing") 4915 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4916 columns = self.expressions(expression, key="columns") 4917 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4918 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4919 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4920 4921 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4922 this = self.sql(expression, "this") 4923 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4924 4925 def export_sql(self, expression: exp.Export) -> str: 4926 this = self.sql(expression, "this") 4927 connection = self.sql(expression, "connection") 4928 connection = f"WITH CONNECTION {connection} " if connection else "" 4929 options = self.sql(expression, "options") 4930 return f"EXPORT DATA {connection}{options} AS {this}" 4931 4932 def declare_sql(self, expression: exp.Declare) -> str: 4933 return f"DECLARE {self.expressions(expression, flat=True)}" 4934 4935 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4936 variable = self.sql(expression, "this") 4937 default = self.sql(expression, "default") 4938 default = f" = {default}" if default else "" 4939 4940 kind = self.sql(expression, "kind") 4941 if isinstance(expression.args.get("kind"), exp.Schema): 4942 kind = f"TABLE {kind}" 4943 4944 return f"{variable} AS {kind}{default}" 4945 4946 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4947 kind = self.sql(expression, "kind") 4948 this = self.sql(expression, "this") 4949 set = self.sql(expression, "expression") 4950 using = self.sql(expression, "using") 4951 using = f" USING {using}" if using else "" 4952 4953 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4954 4955 return f"{kind_sql} {this} SET {set}{using}" 4956 4957 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4958 params = self.expressions(expression, key="params", flat=True) 4959 return self.func(expression.name, *expression.expressions) + f"({params})" 4960 4961 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4962 return self.func(expression.name, *expression.expressions) 4963 4964 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4965 return self.anonymousaggfunc_sql(expression) 4966 4967 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4968 return self.parameterizedagg_sql(expression) 4969 4970 def show_sql(self, expression: exp.Show) -> str: 4971 self.unsupported("Unsupported SHOW statement") 4972 return "" 4973 4974 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 4975 # Snowflake GET/PUT statements: 4976 # PUT <file> <internalStage> <properties> 4977 # GET <internalStage> <file> <properties> 4978 props = expression.args.get("properties") 4979 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4980 this = self.sql(expression, "this") 4981 target = self.sql(expression, "target") 4982 4983 if isinstance(expression, exp.Put): 4984 return f"PUT {this} {target}{props_sql}" 4985 else: 4986 return f"GET {target} {this}{props_sql}" 4987 4988 def translatecharacters_sql(self, expression: exp.TranslateCharacters): 4989 this = self.sql(expression, "this") 4990 expr = self.sql(expression, "expression") 4991 with_error = " WITH ERROR" if expression.args.get("with_error") else "" 4992 return f"TRANSLATE({this} USING {expr}{with_error})"
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 or 'always': Always quote. '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
WHERE
clause. 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: Optional[bool] = None, identify: str | bool = False, normalize: bool = False, pad: int = 2, indent: int = 2, normalize_functions: Union[str, bool, NoneType] = 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)
700 def __init__( 701 self, 702 pretty: t.Optional[bool] = None, 703 identify: str | bool = False, 704 normalize: bool = False, 705 pad: int = 2, 706 indent: int = 2, 707 normalize_functions: t.Optional[str | bool] = None, 708 unsupported_level: ErrorLevel = ErrorLevel.WARN, 709 max_unsupported: int = 3, 710 leading_comma: bool = False, 711 max_text_width: int = 80, 712 comments: bool = True, 713 dialect: DialectType = None, 714 ): 715 import sqlglot 716 from sqlglot.dialects import Dialect 717 718 self.pretty = pretty if pretty is not None else sqlglot.pretty 719 self.identify = identify 720 self.normalize = normalize 721 self.pad = pad 722 self._indent = indent 723 self.unsupported_level = unsupported_level 724 self.max_unsupported = max_unsupported 725 self.leading_comma = leading_comma 726 self.max_text_width = max_text_width 727 self.comments = comments 728 self.dialect = Dialect.get_or_raise(dialect) 729 730 # This is both a Dialect property and a Generator argument, so we prioritize the latter 731 self.normalize_functions = ( 732 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 733 ) 734 735 self.unsupported_messages: t.List[str] = [] 736 self._escaped_quote_end: str = ( 737 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 738 ) 739 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 740 741 self._next_name = name_sequence("_t") 742 743 self._identifier_start = self.dialect.IDENTIFIER_START 744 self._identifier_end = self.dialect.IDENTIFIER_END 745 746 self._quote_json_path_key_using_brackets = True
TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] =
{<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConvertToCharset'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CredentialsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EnviromentProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Get'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionedByBucket'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PartitionByTruncate'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Put'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>}
TYPE_MAPPING =
{<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS =
{'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS =
{'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EnviromentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES =
{<Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.CHAR: 'CHAR'>}
748 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 749 """ 750 Generates the SQL string corresponding to the given syntax tree. 751 752 Args: 753 expression: The syntax tree. 754 copy: Whether to copy the expression. The generator performs mutations so 755 it is safer to copy. 756 757 Returns: 758 The SQL string corresponding to `expression`. 759 """ 760 if copy: 761 expression = expression.copy() 762 763 expression = self.preprocess(expression) 764 765 self.unsupported_messages = [] 766 sql = self.sql(expression).strip() 767 768 if self.pretty: 769 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 770 771 if self.unsupported_level == ErrorLevel.IGNORE: 772 return sql 773 774 if self.unsupported_level == ErrorLevel.WARN: 775 for msg in self.unsupported_messages: 776 logger.warning(msg) 777 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 778 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 779 780 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
.
def
preprocess( self, expression: sqlglot.expressions.Expression) -> sqlglot.expressions.Expression:
782 def preprocess(self, expression: exp.Expression) -> exp.Expression: 783 """Apply generic preprocessing transformations to a given expression.""" 784 expression = self._move_ctes_to_top_level(expression) 785 786 if self.ENSURE_BOOLS: 787 from sqlglot.transforms import ensure_bools 788 789 expression = ensure_bools(expression) 790 791 return expression
Apply generic preprocessing transformations to a given expression.
def
sanitize_comment(self, comment: str) -> str:
815 def sanitize_comment(self, comment: str) -> str: 816 comment = " " + comment if comment[0].strip() else comment 817 comment = comment + " " if comment[-1].strip() else comment 818 819 if not self.dialect.tokenizer_class.NESTED_COMMENTS: 820 # Necessary workaround to avoid syntax errors due to nesting: /* ... */ ... */ 821 comment = comment.replace("*/", "* /") 822 823 return comment
def
maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
825 def maybe_comment( 826 self, 827 sql: str, 828 expression: t.Optional[exp.Expression] = None, 829 comments: t.Optional[t.List[str]] = None, 830 separated: bool = False, 831 ) -> str: 832 comments = ( 833 ((expression and expression.comments) if comments is None else comments) # type: ignore 834 if self.comments 835 else None 836 ) 837 838 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 839 return sql 840 841 comments_sql = " ".join( 842 f"/*{self.sanitize_comment(comment)}*/" for comment in comments if comment 843 ) 844 845 if not comments_sql: 846 return sql 847 848 comments_sql = self._replace_line_breaks(comments_sql) 849 850 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 851 return ( 852 f"{self.sep()}{comments_sql}{sql}" 853 if not sql or sql[0].isspace() 854 else f"{comments_sql}{self.sep()}{sql}" 855 ) 856 857 return f"{sql} {comments_sql}"
859 def wrap(self, expression: exp.Expression | str) -> str: 860 this_sql = ( 861 self.sql(expression) 862 if isinstance(expression, exp.UNWRAPPED_QUERIES) 863 else self.sql(expression, "this") 864 ) 865 if not this_sql: 866 return "()" 867 868 this_sql = self.indent(this_sql, level=1, pad=0) 869 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}"
def
indent( self, sql: str, level: int = 0, pad: Optional[int] = None, skip_first: bool = False, skip_last: bool = False) -> str:
885 def indent( 886 self, 887 sql: str, 888 level: int = 0, 889 pad: t.Optional[int] = None, 890 skip_first: bool = False, 891 skip_last: bool = False, 892 ) -> str: 893 if not self.pretty or not sql: 894 return sql 895 896 pad = self.pad if pad is None else pad 897 lines = sql.split("\n") 898 899 return "\n".join( 900 ( 901 line 902 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 903 else f"{' ' * (level * self._indent + pad)}{line}" 904 ) 905 for i, line in enumerate(lines) 906 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
908 def sql( 909 self, 910 expression: t.Optional[str | exp.Expression], 911 key: t.Optional[str] = None, 912 comment: bool = True, 913 ) -> str: 914 if not expression: 915 return "" 916 917 if isinstance(expression, str): 918 return expression 919 920 if key: 921 value = expression.args.get(key) 922 if value: 923 return self.sql(value) 924 return "" 925 926 transform = self.TRANSFORMS.get(expression.__class__) 927 928 if callable(transform): 929 sql = transform(self, expression) 930 elif isinstance(expression, exp.Expression): 931 exp_handler_name = f"{expression.key}_sql" 932 933 if hasattr(self, exp_handler_name): 934 sql = getattr(self, exp_handler_name)(expression) 935 elif isinstance(expression, exp.Func): 936 sql = self.function_fallback_sql(expression) 937 elif isinstance(expression, exp.Property): 938 sql = self.property_sql(expression) 939 else: 940 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 941 else: 942 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 943 944 return self.maybe_comment(sql, expression) if self.comments and comment else sql
951 def cache_sql(self, expression: exp.Cache) -> str: 952 lazy = " LAZY" if expression.args.get("lazy") else "" 953 table = self.sql(expression, "this") 954 options = expression.args.get("options") 955 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 956 sql = self.sql(expression, "expression") 957 sql = f" AS{self.sep()}{sql}" if sql else "" 958 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 959 return self.prepend_ctes(expression, sql)
961 def characterset_sql(self, expression: exp.CharacterSet) -> str: 962 if isinstance(expression.parent, exp.Cast): 963 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 964 default = "DEFAULT " if expression.args.get("default") else "" 965 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
979 def column_sql(self, expression: exp.Column) -> str: 980 join_mark = " (+)" if expression.args.get("join_mark") else "" 981 982 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 983 join_mark = "" 984 self.unsupported("Outer join syntax using the (+) operator is not supported.") 985 986 return f"{self.column_parts(expression)}{join_mark}"
994 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 995 column = self.sql(expression, "this") 996 kind = self.sql(expression, "kind") 997 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 998 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 999 kind = f"{sep}{kind}" if kind else "" 1000 constraints = f" {constraints}" if constraints else "" 1001 position = self.sql(expression, "position") 1002 position = f" {position}" if position else "" 1003 1004 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 1005 kind = "" 1006 1007 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
1014 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 1015 this = self.sql(expression, "this") 1016 if expression.args.get("not_null"): 1017 persisted = " PERSISTED NOT NULL" 1018 elif expression.args.get("persisted"): 1019 persisted = " PERSISTED" 1020 else: 1021 persisted = "" 1022 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1035 def generatedasidentitycolumnconstraint_sql( 1036 self, expression: exp.GeneratedAsIdentityColumnConstraint 1037 ) -> str: 1038 this = "" 1039 if expression.this is not None: 1040 on_null = " ON NULL" if expression.args.get("on_null") else "" 1041 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1042 1043 start = expression.args.get("start") 1044 start = f"START WITH {start}" if start else "" 1045 increment = expression.args.get("increment") 1046 increment = f" INCREMENT BY {increment}" if increment else "" 1047 minvalue = expression.args.get("minvalue") 1048 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1049 maxvalue = expression.args.get("maxvalue") 1050 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1051 cycle = expression.args.get("cycle") 1052 cycle_sql = "" 1053 1054 if cycle is not None: 1055 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1056 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1057 1058 sequence_opts = "" 1059 if start or increment or cycle_sql: 1060 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1061 sequence_opts = f" ({sequence_opts.strip()})" 1062 1063 expr = self.sql(expression, "expression") 1064 expr = f"({expr})" if expr else "IDENTITY" 1065 1066 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1068 def generatedasrowcolumnconstraint_sql( 1069 self, expression: exp.GeneratedAsRowColumnConstraint 1070 ) -> str: 1071 start = "START" if expression.args.get("start") else "END" 1072 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1073 return f"GENERATED ALWAYS AS ROW {start}{hidden}"
def
periodforsystemtimeconstraint_sql( self, expression: sqlglot.expressions.PeriodForSystemTimeConstraint) -> str:
def
notnullcolumnconstraint_sql(self, expression: sqlglot.expressions.NotNullColumnConstraint) -> str:
def
transformcolumnconstraint_sql(self, expression: sqlglot.expressions.TransformColumnConstraint) -> str:
def
primarykeycolumnconstraint_sql(self, expression: sqlglot.expressions.PrimaryKeyColumnConstraint) -> str:
1086 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1087 desc = expression.args.get("desc") 1088 if desc is not None: 1089 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1090 options = self.expressions(expression, key="options", flat=True, sep=" ") 1091 options = f" {options}" if options else "" 1092 return f"PRIMARY KEY{options}"
def
uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1094 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1095 this = self.sql(expression, "this") 1096 this = f" {this}" if this else "" 1097 index_type = expression.args.get("index_type") 1098 index_type = f" USING {index_type}" if index_type else "" 1099 on_conflict = self.sql(expression, "on_conflict") 1100 on_conflict = f" {on_conflict}" if on_conflict else "" 1101 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1102 options = self.expressions(expression, key="options", flat=True, sep=" ") 1103 options = f" {options}" if options else "" 1104 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}{options}"
1109 def create_sql(self, expression: exp.Create) -> str: 1110 kind = self.sql(expression, "kind") 1111 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1112 properties = expression.args.get("properties") 1113 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1114 1115 this = self.createable_sql(expression, properties_locs) 1116 1117 properties_sql = "" 1118 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1119 exp.Properties.Location.POST_WITH 1120 ): 1121 properties_sql = self.sql( 1122 exp.Properties( 1123 expressions=[ 1124 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1125 *properties_locs[exp.Properties.Location.POST_WITH], 1126 ] 1127 ) 1128 ) 1129 1130 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1131 properties_sql = self.sep() + properties_sql 1132 elif not self.pretty: 1133 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1134 properties_sql = f" {properties_sql}" 1135 1136 begin = " BEGIN" if expression.args.get("begin") else "" 1137 end = " END" if expression.args.get("end") else "" 1138 1139 expression_sql = self.sql(expression, "expression") 1140 if expression_sql: 1141 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1142 1143 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1144 postalias_props_sql = "" 1145 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1146 postalias_props_sql = self.properties( 1147 exp.Properties( 1148 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1149 ), 1150 wrapped=False, 1151 ) 1152 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1153 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1154 1155 postindex_props_sql = "" 1156 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1157 postindex_props_sql = self.properties( 1158 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1159 wrapped=False, 1160 prefix=" ", 1161 ) 1162 1163 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1164 indexes = f" {indexes}" if indexes else "" 1165 index_sql = indexes + postindex_props_sql 1166 1167 replace = " OR REPLACE" if expression.args.get("replace") else "" 1168 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1169 unique = " UNIQUE" if expression.args.get("unique") else "" 1170 1171 clustered = expression.args.get("clustered") 1172 if clustered is None: 1173 clustered_sql = "" 1174 elif clustered: 1175 clustered_sql = " CLUSTERED COLUMNSTORE" 1176 else: 1177 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1178 1179 postcreate_props_sql = "" 1180 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1181 postcreate_props_sql = self.properties( 1182 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1183 sep=" ", 1184 prefix=" ", 1185 wrapped=False, 1186 ) 1187 1188 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1189 1190 postexpression_props_sql = "" 1191 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1192 postexpression_props_sql = self.properties( 1193 exp.Properties( 1194 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1195 ), 1196 sep=" ", 1197 prefix=" ", 1198 wrapped=False, 1199 ) 1200 1201 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1202 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1203 no_schema_binding = ( 1204 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1205 ) 1206 1207 clone = self.sql(expression, "clone") 1208 clone = f" {clone}" if clone else "" 1209 1210 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1211 properties_expression = f"{expression_sql}{properties_sql}" 1212 else: 1213 properties_expression = f"{properties_sql}{expression_sql}" 1214 1215 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1216 return self.prepend_ctes(expression, expression_sql)
1218 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1219 start = self.sql(expression, "start") 1220 start = f"START WITH {start}" if start else "" 1221 increment = self.sql(expression, "increment") 1222 increment = f" INCREMENT BY {increment}" if increment else "" 1223 minvalue = self.sql(expression, "minvalue") 1224 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1225 maxvalue = self.sql(expression, "maxvalue") 1226 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1227 owned = self.sql(expression, "owned") 1228 owned = f" OWNED BY {owned}" if owned else "" 1229 1230 cache = expression.args.get("cache") 1231 if cache is None: 1232 cache_str = "" 1233 elif cache is True: 1234 cache_str = " CACHE" 1235 else: 1236 cache_str = f" CACHE {cache}" 1237 1238 options = self.expressions(expression, key="options", flat=True, sep=" ") 1239 options = f" {options}" if options else "" 1240 1241 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1243 def clone_sql(self, expression: exp.Clone) -> str: 1244 this = self.sql(expression, "this") 1245 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1246 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1247 return f"{shallow}{keyword} {this}"
1249 def describe_sql(self, expression: exp.Describe) -> str: 1250 style = expression.args.get("style") 1251 style = f" {style}" if style else "" 1252 partition = self.sql(expression, "partition") 1253 partition = f" {partition}" if partition else "" 1254 format = self.sql(expression, "format") 1255 format = f" {format}" if format else "" 1256 1257 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1269 def with_sql(self, expression: exp.With) -> str: 1270 sql = self.expressions(expression, flat=True) 1271 recursive = ( 1272 "RECURSIVE " 1273 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1274 else "" 1275 ) 1276 search = self.sql(expression, "search") 1277 search = f" {search}" if search else "" 1278 1279 return f"WITH {recursive}{sql}{search}"
1281 def cte_sql(self, expression: exp.CTE) -> str: 1282 alias = expression.args.get("alias") 1283 if alias: 1284 alias.add_comments(expression.pop_comments()) 1285 1286 alias_sql = self.sql(expression, "alias") 1287 1288 materialized = expression.args.get("materialized") 1289 if materialized is False: 1290 materialized = "NOT MATERIALIZED " 1291 elif materialized: 1292 materialized = "MATERIALIZED " 1293 1294 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1296 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1297 alias = self.sql(expression, "this") 1298 columns = self.expressions(expression, key="columns", flat=True) 1299 columns = f"({columns})" if columns else "" 1300 1301 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1302 columns = "" 1303 self.unsupported("Named columns are not supported in table alias.") 1304 1305 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1306 alias = self._next_name() 1307 1308 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1316 def hexstring_sql( 1317 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1318 ) -> str: 1319 this = self.sql(expression, "this") 1320 is_integer_type = expression.args.get("is_integer") 1321 1322 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1323 not self.dialect.HEX_START and not binary_function_repr 1324 ): 1325 # Integer representation will be returned if: 1326 # - The read dialect treats the hex value as integer literal but not the write 1327 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1328 return f"{int(this, 16)}" 1329 1330 if not is_integer_type: 1331 # Read dialect treats the hex value as BINARY/BLOB 1332 if binary_function_repr: 1333 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1334 return self.func(binary_function_repr, exp.Literal.string(this)) 1335 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1336 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1337 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1338 1339 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1347 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1348 this = self.sql(expression, "this") 1349 escape = expression.args.get("escape") 1350 1351 if self.dialect.UNICODE_START: 1352 escape_substitute = r"\\\1" 1353 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1354 else: 1355 escape_substitute = r"\\u\1" 1356 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1357 1358 if escape: 1359 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1360 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1361 else: 1362 escape_pattern = ESCAPED_UNICODE_RE 1363 escape_sql = "" 1364 1365 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1366 this = escape_pattern.sub(escape_substitute, this) 1367 1368 return f"{left_quote}{this}{right_quote}{escape_sql}"
1370 def rawstring_sql(self, expression: exp.RawString) -> str: 1371 string = expression.this 1372 if "\\" in self.dialect.tokenizer_class.STRING_ESCAPES: 1373 string = string.replace("\\", "\\\\") 1374 1375 string = self.escape_str(string, escape_backslash=False) 1376 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}"
1384 def datatype_sql(self, expression: exp.DataType) -> str: 1385 nested = "" 1386 values = "" 1387 interior = self.expressions(expression, flat=True) 1388 1389 type_value = expression.this 1390 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1391 type_sql = self.sql(expression, "kind") 1392 else: 1393 type_sql = ( 1394 self.TYPE_MAPPING.get(type_value, type_value.value) 1395 if isinstance(type_value, exp.DataType.Type) 1396 else type_value 1397 ) 1398 1399 if interior: 1400 if expression.args.get("nested"): 1401 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1402 if expression.args.get("values") is not None: 1403 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1404 values = self.expressions(expression, key="values", flat=True) 1405 values = f"{delimiters[0]}{values}{delimiters[1]}" 1406 elif type_value == exp.DataType.Type.INTERVAL: 1407 nested = f" {interior}" 1408 else: 1409 nested = f"({interior})" 1410 1411 type_sql = f"{type_sql}{nested}{values}" 1412 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1413 exp.DataType.Type.TIMETZ, 1414 exp.DataType.Type.TIMESTAMPTZ, 1415 ): 1416 type_sql = f"{type_sql} WITH TIME ZONE" 1417 1418 return type_sql
1420 def directory_sql(self, expression: exp.Directory) -> str: 1421 local = "LOCAL " if expression.args.get("local") else "" 1422 row_format = self.sql(expression, "row_format") 1423 row_format = f" {row_format}" if row_format else "" 1424 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1426 def delete_sql(self, expression: exp.Delete) -> str: 1427 this = self.sql(expression, "this") 1428 this = f" FROM {this}" if this else "" 1429 using = self.sql(expression, "using") 1430 using = f" USING {using}" if using else "" 1431 cluster = self.sql(expression, "cluster") 1432 cluster = f" {cluster}" if cluster else "" 1433 where = self.sql(expression, "where") 1434 returning = self.sql(expression, "returning") 1435 limit = self.sql(expression, "limit") 1436 tables = self.expressions(expression, key="tables") 1437 tables = f" {tables}" if tables else "" 1438 if self.RETURNING_END: 1439 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1440 else: 1441 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1442 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1444 def drop_sql(self, expression: exp.Drop) -> str: 1445 this = self.sql(expression, "this") 1446 expressions = self.expressions(expression, flat=True) 1447 expressions = f" ({expressions})" if expressions else "" 1448 kind = expression.args["kind"] 1449 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1450 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1451 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1452 on_cluster = self.sql(expression, "cluster") 1453 on_cluster = f" {on_cluster}" if on_cluster else "" 1454 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1455 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1456 cascade = " CASCADE" if expression.args.get("cascade") else "" 1457 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1458 purge = " PURGE" if expression.args.get("purge") else "" 1459 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1461 def set_operation(self, expression: exp.SetOperation) -> str: 1462 op_type = type(expression) 1463 op_name = op_type.key.upper() 1464 1465 distinct = expression.args.get("distinct") 1466 if ( 1467 distinct is False 1468 and op_type in (exp.Except, exp.Intersect) 1469 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1470 ): 1471 self.unsupported(f"{op_name} ALL is not supported") 1472 1473 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1474 1475 if distinct is None: 1476 distinct = default_distinct 1477 if distinct is None: 1478 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1479 1480 if distinct is default_distinct: 1481 distinct_or_all = "" 1482 else: 1483 distinct_or_all = " DISTINCT" if distinct else " ALL" 1484 1485 side_kind = " ".join(filter(None, [expression.side, expression.kind])) 1486 side_kind = f"{side_kind} " if side_kind else "" 1487 1488 by_name = " BY NAME" if expression.args.get("by_name") else "" 1489 on = self.expressions(expression, key="on", flat=True) 1490 on = f" ON ({on})" if on else "" 1491 1492 return f"{side_kind}{op_name}{distinct_or_all}{by_name}{on}"
1494 def set_operations(self, expression: exp.SetOperation) -> str: 1495 if not self.SET_OP_MODIFIERS: 1496 limit = expression.args.get("limit") 1497 order = expression.args.get("order") 1498 1499 if limit or order: 1500 select = self._move_ctes_to_top_level( 1501 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1502 ) 1503 1504 if limit: 1505 select = select.limit(limit.pop(), copy=False) 1506 if order: 1507 select = select.order_by(order.pop(), copy=False) 1508 return self.sql(select) 1509 1510 sqls: t.List[str] = [] 1511 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1512 1513 while stack: 1514 node = stack.pop() 1515 1516 if isinstance(node, exp.SetOperation): 1517 stack.append(node.expression) 1518 stack.append( 1519 self.maybe_comment( 1520 self.set_operation(node), comments=node.comments, separated=True 1521 ) 1522 ) 1523 stack.append(node.this) 1524 else: 1525 sqls.append(self.sql(node)) 1526 1527 this = self.sep().join(sqls) 1528 this = self.query_modifiers(expression, this) 1529 return self.prepend_ctes(expression, this)
1531 def fetch_sql(self, expression: exp.Fetch) -> str: 1532 direction = expression.args.get("direction") 1533 direction = f" {direction}" if direction else "" 1534 count = self.sql(expression, "count") 1535 count = f" {count}" if count else "" 1536 limit_options = self.sql(expression, "limit_options") 1537 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1538 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1540 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1541 percent = " PERCENT" if expression.args.get("percent") else "" 1542 rows = " ROWS" if expression.args.get("rows") else "" 1543 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1544 if not with_ties and rows: 1545 with_ties = " ONLY" 1546 return f"{percent}{rows}{with_ties}"
1548 def filter_sql(self, expression: exp.Filter) -> str: 1549 if self.AGGREGATE_FILTER_SUPPORTED: 1550 this = self.sql(expression, "this") 1551 where = self.sql(expression, "expression").strip() 1552 return f"{this} FILTER({where})" 1553 1554 agg = expression.this 1555 agg_arg = agg.this 1556 cond = expression.expression.this 1557 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1558 return self.sql(agg)
1567 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1568 using = self.sql(expression, "using") 1569 using = f" USING {using}" if using else "" 1570 columns = self.expressions(expression, key="columns", flat=True) 1571 columns = f"({columns})" if columns else "" 1572 partition_by = self.expressions(expression, key="partition_by", flat=True) 1573 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1574 where = self.sql(expression, "where") 1575 include = self.expressions(expression, key="include", flat=True) 1576 if include: 1577 include = f" INCLUDE ({include})" 1578 with_storage = self.expressions(expression, key="with_storage", flat=True) 1579 with_storage = f" WITH ({with_storage})" if with_storage else "" 1580 tablespace = self.sql(expression, "tablespace") 1581 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1582 on = self.sql(expression, "on") 1583 on = f" ON {on}" if on else "" 1584 1585 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1587 def index_sql(self, expression: exp.Index) -> str: 1588 unique = "UNIQUE " if expression.args.get("unique") else "" 1589 primary = "PRIMARY " if expression.args.get("primary") else "" 1590 amp = "AMP " if expression.args.get("amp") else "" 1591 name = self.sql(expression, "this") 1592 name = f"{name} " if name else "" 1593 table = self.sql(expression, "table") 1594 table = f"{self.INDEX_ON} {table}" if table else "" 1595 1596 index = "INDEX " if not table else "" 1597 1598 params = self.sql(expression, "params") 1599 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1601 def identifier_sql(self, expression: exp.Identifier) -> str: 1602 text = expression.name 1603 lower = text.lower() 1604 text = lower if self.normalize and not expression.quoted else text 1605 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1606 if ( 1607 expression.quoted 1608 or self.dialect.can_identify(text, self.identify) 1609 or lower in self.RESERVED_KEYWORDS 1610 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1611 ): 1612 text = f"{self._identifier_start}{text}{self._identifier_end}" 1613 return text
1628 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1629 input_format = self.sql(expression, "input_format") 1630 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1631 output_format = self.sql(expression, "output_format") 1632 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1633 return self.sep().join((input_format, output_format))
1643 def properties_sql(self, expression: exp.Properties) -> str: 1644 root_properties = [] 1645 with_properties = [] 1646 1647 for p in expression.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc == exp.Properties.Location.POST_WITH: 1650 with_properties.append(p) 1651 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1652 root_properties.append(p) 1653 1654 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1655 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1656 1657 if root_props and with_props and not self.pretty: 1658 with_props = " " + with_props 1659 1660 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1667 def properties( 1668 self, 1669 properties: exp.Properties, 1670 prefix: str = "", 1671 sep: str = ", ", 1672 suffix: str = "", 1673 wrapped: bool = True, 1674 ) -> str: 1675 if properties.expressions: 1676 expressions = self.expressions(properties, sep=sep, indent=False) 1677 if expressions: 1678 expressions = self.wrap(expressions) if wrapped else expressions 1679 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1680 return ""
1685 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1686 properties_locs = defaultdict(list) 1687 for p in properties.expressions: 1688 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1689 if p_loc != exp.Properties.Location.UNSUPPORTED: 1690 properties_locs[p_loc].append(p) 1691 else: 1692 self.unsupported(f"Unsupported property {p.key}") 1693 1694 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1701 def property_sql(self, expression: exp.Property) -> str: 1702 property_cls = expression.__class__ 1703 if property_cls == exp.Property: 1704 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1705 1706 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1707 if not property_name: 1708 self.unsupported(f"Unsupported property {expression.key}") 1709 1710 return f"{property_name}={self.sql(expression, 'this')}"
1712 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1713 if self.SUPPORTS_CREATE_TABLE_LIKE: 1714 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1715 options = f" {options}" if options else "" 1716 1717 like = f"LIKE {self.sql(expression, 'this')}{options}" 1718 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1719 like = f"({like})" 1720 1721 return like 1722 1723 if expression.expressions: 1724 self.unsupported("Transpilation of LIKE property options is unsupported") 1725 1726 select = exp.select("*").from_(expression.this).limit(0) 1727 return f"AS {self.sql(select)}"
1734 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1735 no = "NO " if expression.args.get("no") else "" 1736 local = expression.args.get("local") 1737 local = f"{local} " if local else "" 1738 dual = "DUAL " if expression.args.get("dual") else "" 1739 before = "BEFORE " if expression.args.get("before") else "" 1740 after = "AFTER " if expression.args.get("after") else "" 1741 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1757 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1758 if expression.args.get("no"): 1759 return "NO MERGEBLOCKRATIO" 1760 if expression.args.get("default"): 1761 return "DEFAULT MERGEBLOCKRATIO" 1762 1763 percent = " PERCENT" if expression.args.get("percent") else "" 1764 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1766 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1767 default = expression.args.get("default") 1768 minimum = expression.args.get("minimum") 1769 maximum = expression.args.get("maximum") 1770 if default or minimum or maximum: 1771 if default: 1772 prop = "DEFAULT" 1773 elif minimum: 1774 prop = "MINIMUM" 1775 else: 1776 prop = "MAXIMUM" 1777 return f"{prop} DATABLOCKSIZE" 1778 units = expression.args.get("units") 1779 units = f" {units}" if units else "" 1780 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1782 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1783 autotemp = expression.args.get("autotemp") 1784 always = expression.args.get("always") 1785 default = expression.args.get("default") 1786 manual = expression.args.get("manual") 1787 never = expression.args.get("never") 1788 1789 if autotemp is not None: 1790 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1791 elif always: 1792 prop = "ALWAYS" 1793 elif default: 1794 prop = "DEFAULT" 1795 elif manual: 1796 prop = "MANUAL" 1797 elif never: 1798 prop = "NEVER" 1799 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1801 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1802 no = expression.args.get("no") 1803 no = " NO" if no else "" 1804 concurrent = expression.args.get("concurrent") 1805 concurrent = " CONCURRENT" if concurrent else "" 1806 target = self.sql(expression, "target") 1807 target = f" {target}" if target else "" 1808 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1810 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1811 if isinstance(expression.this, list): 1812 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1813 if expression.this: 1814 modulus = self.sql(expression, "this") 1815 remainder = self.sql(expression, "expression") 1816 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1817 1818 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1819 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1820 return f"FROM ({from_expressions}) TO ({to_expressions})"
1822 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1823 this = self.sql(expression, "this") 1824 1825 for_values_or_default = expression.expression 1826 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1827 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1828 else: 1829 for_values_or_default = " DEFAULT" 1830 1831 return f"PARTITION OF {this}{for_values_or_default}"
1833 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1834 kind = expression.args.get("kind") 1835 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1836 for_or_in = expression.args.get("for_or_in") 1837 for_or_in = f" {for_or_in}" if for_or_in else "" 1838 lock_type = expression.args.get("lock_type") 1839 override = " OVERRIDE" if expression.args.get("override") else "" 1840 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1842 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1843 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1844 statistics = expression.args.get("statistics") 1845 statistics_sql = "" 1846 if statistics is not None: 1847 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1848 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1850 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1851 this = self.sql(expression, "this") 1852 this = f"HISTORY_TABLE={this}" if this else "" 1853 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1854 data_consistency = ( 1855 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1856 ) 1857 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1858 retention_period = ( 1859 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1860 ) 1861 1862 if this: 1863 on_sql = self.func("ON", this, data_consistency, retention_period) 1864 else: 1865 on_sql = "ON" if expression.args.get("on") else "OFF" 1866 1867 sql = f"SYSTEM_VERSIONING={on_sql}" 1868 1869 return f"WITH({sql})" if expression.args.get("with") else sql
1871 def insert_sql(self, expression: exp.Insert) -> str: 1872 hint = self.sql(expression, "hint") 1873 overwrite = expression.args.get("overwrite") 1874 1875 if isinstance(expression.this, exp.Directory): 1876 this = " OVERWRITE" if overwrite else " INTO" 1877 else: 1878 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1879 1880 stored = self.sql(expression, "stored") 1881 stored = f" {stored}" if stored else "" 1882 alternative = expression.args.get("alternative") 1883 alternative = f" OR {alternative}" if alternative else "" 1884 ignore = " IGNORE" if expression.args.get("ignore") else "" 1885 is_function = expression.args.get("is_function") 1886 if is_function: 1887 this = f"{this} FUNCTION" 1888 this = f"{this} {self.sql(expression, 'this')}" 1889 1890 exists = " IF EXISTS" if expression.args.get("exists") else "" 1891 where = self.sql(expression, "where") 1892 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1893 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1894 on_conflict = self.sql(expression, "conflict") 1895 on_conflict = f" {on_conflict}" if on_conflict else "" 1896 by_name = " BY NAME" if expression.args.get("by_name") else "" 1897 returning = self.sql(expression, "returning") 1898 1899 if self.RETURNING_END: 1900 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1901 else: 1902 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1903 1904 partition_by = self.sql(expression, "partition") 1905 partition_by = f" {partition_by}" if partition_by else "" 1906 settings = self.sql(expression, "settings") 1907 settings = f" {settings}" if settings else "" 1908 1909 source = self.sql(expression, "source") 1910 source = f"TABLE {source}" if source else "" 1911 1912 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1913 return self.prepend_ctes(expression, sql)
1931 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1932 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1933 1934 constraint = self.sql(expression, "constraint") 1935 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1936 1937 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1938 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1939 action = self.sql(expression, "action") 1940 1941 expressions = self.expressions(expression, flat=True) 1942 if expressions: 1943 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1944 expressions = f" {set_keyword}{expressions}" 1945 1946 where = self.sql(expression, "where") 1947 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1952 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1953 fields = self.sql(expression, "fields") 1954 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1955 escaped = self.sql(expression, "escaped") 1956 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1957 items = self.sql(expression, "collection_items") 1958 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1959 keys = self.sql(expression, "map_keys") 1960 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1961 lines = self.sql(expression, "lines") 1962 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1963 null = self.sql(expression, "null") 1964 null = f" NULL DEFINED AS {null}" if null else "" 1965 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1993 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1994 table = self.table_parts(expression) 1995 only = "ONLY " if expression.args.get("only") else "" 1996 partition = self.sql(expression, "partition") 1997 partition = f" {partition}" if partition else "" 1998 version = self.sql(expression, "version") 1999 version = f" {version}" if version else "" 2000 alias = self.sql(expression, "alias") 2001 alias = f"{sep}{alias}" if alias else "" 2002 2003 sample = self.sql(expression, "sample") 2004 if self.dialect.ALIAS_POST_TABLESAMPLE: 2005 sample_pre_alias = sample 2006 sample_post_alias = "" 2007 else: 2008 sample_pre_alias = "" 2009 sample_post_alias = sample 2010 2011 hints = self.expressions(expression, key="hints", sep=" ") 2012 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 2013 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2014 joins = self.indent( 2015 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2016 ) 2017 laterals = self.expressions(expression, key="laterals", sep="") 2018 2019 file_format = self.sql(expression, "format") 2020 if file_format: 2021 pattern = self.sql(expression, "pattern") 2022 pattern = f", PATTERN => {pattern}" if pattern else "" 2023 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 2024 2025 ordinality = expression.args.get("ordinality") or "" 2026 if ordinality: 2027 ordinality = f" WITH ORDINALITY{alias}" 2028 alias = "" 2029 2030 when = self.sql(expression, "when") 2031 if when: 2032 table = f"{table} {when}" 2033 2034 changes = self.sql(expression, "changes") 2035 changes = f" {changes}" if changes else "" 2036 2037 rows_from = self.expressions(expression, key="rows_from") 2038 if rows_from: 2039 table = f"ROWS FROM {self.wrap(rows_from)}" 2040 2041 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2043 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2044 table = self.func("TABLE", expression.this) 2045 alias = self.sql(expression, "alias") 2046 alias = f" AS {alias}" if alias else "" 2047 sample = self.sql(expression, "sample") 2048 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2049 joins = self.indent( 2050 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2051 ) 2052 return f"{table}{alias}{pivots}{sample}{joins}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2054 def tablesample_sql( 2055 self, 2056 expression: exp.TableSample, 2057 tablesample_keyword: t.Optional[str] = None, 2058 ) -> str: 2059 method = self.sql(expression, "method") 2060 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2061 numerator = self.sql(expression, "bucket_numerator") 2062 denominator = self.sql(expression, "bucket_denominator") 2063 field = self.sql(expression, "bucket_field") 2064 field = f" ON {field}" if field else "" 2065 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2066 seed = self.sql(expression, "seed") 2067 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2068 2069 size = self.sql(expression, "size") 2070 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2071 size = f"{size} ROWS" 2072 2073 percent = self.sql(expression, "percent") 2074 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2075 percent = f"{percent} PERCENT" 2076 2077 expr = f"{bucket}{percent}{size}" 2078 if self.TABLESAMPLE_REQUIRES_PARENS: 2079 expr = f"({expr})" 2080 2081 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2083 def pivot_sql(self, expression: exp.Pivot) -> str: 2084 expressions = self.expressions(expression, flat=True) 2085 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2086 2087 group = self.sql(expression, "group") 2088 2089 if expression.this: 2090 this = self.sql(expression, "this") 2091 if not expressions: 2092 return f"UNPIVOT {this}" 2093 2094 on = f"{self.seg('ON')} {expressions}" 2095 into = self.sql(expression, "into") 2096 into = f"{self.seg('INTO')} {into}" if into else "" 2097 using = self.expressions(expression, key="using", flat=True) 2098 using = f"{self.seg('USING')} {using}" if using else "" 2099 return f"{direction} {this}{on}{into}{using}{group}" 2100 2101 alias = self.sql(expression, "alias") 2102 alias = f" AS {alias}" if alias else "" 2103 2104 fields = self.expressions( 2105 expression, 2106 "fields", 2107 sep=" ", 2108 dynamic=True, 2109 new_line=True, 2110 skip_first=True, 2111 skip_last=True, 2112 ) 2113 2114 include_nulls = expression.args.get("include_nulls") 2115 if include_nulls is not None: 2116 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2117 else: 2118 nulls = "" 2119 2120 default_on_null = self.sql(expression, "default_on_null") 2121 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2122 return f"{self.seg(direction)}{nulls}({expressions} FOR {fields}{default_on_null}{group}){alias}"
2133 def update_sql(self, expression: exp.Update) -> str: 2134 this = self.sql(expression, "this") 2135 set_sql = self.expressions(expression, flat=True) 2136 from_sql = self.sql(expression, "from") 2137 where_sql = self.sql(expression, "where") 2138 returning = self.sql(expression, "returning") 2139 order = self.sql(expression, "order") 2140 limit = self.sql(expression, "limit") 2141 if self.RETURNING_END: 2142 expression_sql = f"{from_sql}{where_sql}{returning}" 2143 else: 2144 expression_sql = f"{returning}{from_sql}{where_sql}" 2145 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2146 return self.prepend_ctes(expression, sql)
2148 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2149 values_as_table = values_as_table and self.VALUES_AS_TABLE 2150 2151 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2152 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2153 args = self.expressions(expression) 2154 alias = self.sql(expression, "alias") 2155 values = f"VALUES{self.seg('')}{args}" 2156 values = ( 2157 f"({values})" 2158 if self.WRAP_DERIVED_VALUES 2159 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2160 else values 2161 ) 2162 return f"{values} AS {alias}" if alias else values 2163 2164 # Converts `VALUES...` expression into a series of select unions. 2165 alias_node = expression.args.get("alias") 2166 column_names = alias_node and alias_node.columns 2167 2168 selects: t.List[exp.Query] = [] 2169 2170 for i, tup in enumerate(expression.expressions): 2171 row = tup.expressions 2172 2173 if i == 0 and column_names: 2174 row = [ 2175 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2176 ] 2177 2178 selects.append(exp.Select(expressions=row)) 2179 2180 if self.pretty: 2181 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2182 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2183 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2184 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2185 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2186 2187 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2188 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2189 return f"({unions}){alias}"
2194 @unsupported_args("expressions") 2195 def into_sql(self, expression: exp.Into) -> str: 2196 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2197 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2198 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2215 def group_sql(self, expression: exp.Group) -> str: 2216 group_by_all = expression.args.get("all") 2217 if group_by_all is True: 2218 modifier = " ALL" 2219 elif group_by_all is False: 2220 modifier = " DISTINCT" 2221 else: 2222 modifier = "" 2223 2224 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2225 2226 grouping_sets = self.expressions(expression, key="grouping_sets") 2227 cube = self.expressions(expression, key="cube") 2228 rollup = self.expressions(expression, key="rollup") 2229 2230 groupings = csv( 2231 self.seg(grouping_sets) if grouping_sets else "", 2232 self.seg(cube) if cube else "", 2233 self.seg(rollup) if rollup else "", 2234 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2235 sep=self.GROUPINGS_SEP, 2236 ) 2237 2238 if ( 2239 expression.expressions 2240 and groupings 2241 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2242 ): 2243 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2244 2245 return f"{group_by}{groupings}"
2251 def connect_sql(self, expression: exp.Connect) -> str: 2252 start = self.sql(expression, "start") 2253 start = self.seg(f"START WITH {start}") if start else "" 2254 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2255 connect = self.sql(expression, "connect") 2256 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2257 return start + connect
2262 def join_sql(self, expression: exp.Join) -> str: 2263 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2264 side = None 2265 else: 2266 side = expression.side 2267 2268 op_sql = " ".join( 2269 op 2270 for op in ( 2271 expression.method, 2272 "GLOBAL" if expression.args.get("global") else None, 2273 side, 2274 expression.kind, 2275 expression.hint if self.JOIN_HINTS else None, 2276 ) 2277 if op 2278 ) 2279 match_cond = self.sql(expression, "match_condition") 2280 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2281 on_sql = self.sql(expression, "on") 2282 using = expression.args.get("using") 2283 2284 if not on_sql and using: 2285 on_sql = csv(*(self.sql(column) for column in using)) 2286 2287 this = expression.this 2288 this_sql = self.sql(this) 2289 2290 exprs = self.expressions(expression) 2291 if exprs: 2292 this_sql = f"{this_sql},{self.seg(exprs)}" 2293 2294 if on_sql: 2295 on_sql = self.indent(on_sql, skip_first=True) 2296 space = self.seg(" " * self.pad) if self.pretty else " " 2297 if using: 2298 on_sql = f"{space}USING ({on_sql})" 2299 else: 2300 on_sql = f"{space}ON {on_sql}" 2301 elif not op_sql: 2302 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2303 return f" {this_sql}" 2304 2305 return f", {this_sql}" 2306 2307 if op_sql != "STRAIGHT_JOIN": 2308 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2309 2310 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2311 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}{pivots}"
2318 def lateral_op(self, expression: exp.Lateral) -> str: 2319 cross_apply = expression.args.get("cross_apply") 2320 2321 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2322 if cross_apply is True: 2323 op = "INNER JOIN " 2324 elif cross_apply is False: 2325 op = "LEFT JOIN " 2326 else: 2327 op = "" 2328 2329 return f"{op}LATERAL"
2331 def lateral_sql(self, expression: exp.Lateral) -> str: 2332 this = self.sql(expression, "this") 2333 2334 if expression.args.get("view"): 2335 alias = expression.args["alias"] 2336 columns = self.expressions(alias, key="columns", flat=True) 2337 table = f" {alias.name}" if alias.name else "" 2338 columns = f" AS {columns}" if columns else "" 2339 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2340 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2341 2342 alias = self.sql(expression, "alias") 2343 alias = f" AS {alias}" if alias else "" 2344 2345 ordinality = expression.args.get("ordinality") or "" 2346 if ordinality: 2347 ordinality = f" WITH ORDINALITY{alias}" 2348 alias = "" 2349 2350 return f"{self.lateral_op(expression)} {this}{alias}{ordinality}"
2352 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2353 this = self.sql(expression, "this") 2354 2355 args = [ 2356 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2357 for e in (expression.args.get(k) for k in ("offset", "expression")) 2358 if e 2359 ] 2360 2361 args_sql = ", ".join(self.sql(e) for e in args) 2362 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2363 expressions = self.expressions(expression, flat=True) 2364 limit_options = self.sql(expression, "limit_options") 2365 expressions = f" BY {expressions}" if expressions else "" 2366 2367 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2369 def offset_sql(self, expression: exp.Offset) -> str: 2370 this = self.sql(expression, "this") 2371 value = expression.expression 2372 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2373 expressions = self.expressions(expression, flat=True) 2374 expressions = f" BY {expressions}" if expressions else "" 2375 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2377 def setitem_sql(self, expression: exp.SetItem) -> str: 2378 kind = self.sql(expression, "kind") 2379 kind = f"{kind} " if kind else "" 2380 this = self.sql(expression, "this") 2381 expressions = self.expressions(expression) 2382 collate = self.sql(expression, "collate") 2383 collate = f" COLLATE {collate}" if collate else "" 2384 global_ = "GLOBAL " if expression.args.get("global") else "" 2385 return f"{global_}{kind}{this}{expressions}{collate}"
2395 def lock_sql(self, expression: exp.Lock) -> str: 2396 if not self.LOCKING_READS_SUPPORTED: 2397 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2398 return "" 2399 2400 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2401 expressions = self.expressions(expression, flat=True) 2402 expressions = f" OF {expressions}" if expressions else "" 2403 wait = expression.args.get("wait") 2404 2405 if wait is not None: 2406 if isinstance(wait, exp.Literal): 2407 wait = f" WAIT {self.sql(wait)}" 2408 else: 2409 wait = " NOWAIT" if wait else " SKIP LOCKED" 2410 2411 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2419 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2420 if self.dialect.ESCAPED_SEQUENCES: 2421 to_escaped = self.dialect.ESCAPED_SEQUENCES 2422 text = "".join( 2423 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2424 ) 2425 2426 return self._replace_line_breaks(text).replace( 2427 self.dialect.QUOTE_END, self._escaped_quote_end 2428 )
2430 def loaddata_sql(self, expression: exp.LoadData) -> str: 2431 local = " LOCAL" if expression.args.get("local") else "" 2432 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2433 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2434 this = f" INTO TABLE {self.sql(expression, 'this')}" 2435 partition = self.sql(expression, "partition") 2436 partition = f" {partition}" if partition else "" 2437 input_format = self.sql(expression, "input_format") 2438 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2439 serde = self.sql(expression, "serde") 2440 serde = f" SERDE {serde}" if serde else "" 2441 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2449 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2450 this = self.sql(expression, "this") 2451 this = f"{this} " if this else this 2452 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2453 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2455 def withfill_sql(self, expression: exp.WithFill) -> str: 2456 from_sql = self.sql(expression, "from") 2457 from_sql = f" FROM {from_sql}" if from_sql else "" 2458 to_sql = self.sql(expression, "to") 2459 to_sql = f" TO {to_sql}" if to_sql else "" 2460 step_sql = self.sql(expression, "step") 2461 step_sql = f" STEP {step_sql}" if step_sql else "" 2462 interpolated_values = [ 2463 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2464 if isinstance(e, exp.Alias) 2465 else self.sql(e, "this") 2466 for e in expression.args.get("interpolate") or [] 2467 ] 2468 interpolate = ( 2469 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2470 ) 2471 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2482 def ordered_sql(self, expression: exp.Ordered) -> str: 2483 desc = expression.args.get("desc") 2484 asc = not desc 2485 2486 nulls_first = expression.args.get("nulls_first") 2487 nulls_last = not nulls_first 2488 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2489 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2490 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2491 2492 this = self.sql(expression, "this") 2493 2494 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2495 nulls_sort_change = "" 2496 if nulls_first and ( 2497 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2498 ): 2499 nulls_sort_change = " NULLS FIRST" 2500 elif ( 2501 nulls_last 2502 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2503 and not nulls_are_last 2504 ): 2505 nulls_sort_change = " NULLS LAST" 2506 2507 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2508 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2509 window = expression.find_ancestor(exp.Window, exp.Select) 2510 if isinstance(window, exp.Window) and window.args.get("spec"): 2511 self.unsupported( 2512 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2513 ) 2514 nulls_sort_change = "" 2515 elif self.NULL_ORDERING_SUPPORTED is False and ( 2516 (asc and nulls_sort_change == " NULLS LAST") 2517 or (desc and nulls_sort_change == " NULLS FIRST") 2518 ): 2519 # BigQuery does not allow these ordering/nulls combinations when used under 2520 # an aggregation func or under a window containing one 2521 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2522 2523 if isinstance(ancestor, exp.Window): 2524 ancestor = ancestor.this 2525 if isinstance(ancestor, exp.AggFunc): 2526 self.unsupported( 2527 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2528 ) 2529 nulls_sort_change = "" 2530 elif self.NULL_ORDERING_SUPPORTED is None: 2531 if expression.this.is_int: 2532 self.unsupported( 2533 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2534 ) 2535 elif not isinstance(expression.this, exp.Rand): 2536 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2537 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2538 nulls_sort_change = "" 2539 2540 with_fill = self.sql(expression, "with_fill") 2541 with_fill = f" {with_fill}" if with_fill else "" 2542 2543 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2553 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2554 partition = self.partition_by_sql(expression) 2555 order = self.sql(expression, "order") 2556 measures = self.expressions(expression, key="measures") 2557 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2558 rows = self.sql(expression, "rows") 2559 rows = self.seg(rows) if rows else "" 2560 after = self.sql(expression, "after") 2561 after = self.seg(after) if after else "" 2562 pattern = self.sql(expression, "pattern") 2563 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2564 definition_sqls = [ 2565 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2566 for definition in expression.args.get("define", []) 2567 ] 2568 definitions = self.expressions(sqls=definition_sqls) 2569 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2570 body = "".join( 2571 ( 2572 partition, 2573 order, 2574 measures, 2575 rows, 2576 after, 2577 pattern, 2578 define, 2579 ) 2580 ) 2581 alias = self.sql(expression, "alias") 2582 alias = f" {alias}" if alias else "" 2583 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2585 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2586 limit = expression.args.get("limit") 2587 2588 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2589 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2590 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2591 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2592 2593 return csv( 2594 *sqls, 2595 *[self.sql(join) for join in expression.args.get("joins") or []], 2596 self.sql(expression, "match"), 2597 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2598 self.sql(expression, "prewhere"), 2599 self.sql(expression, "where"), 2600 self.sql(expression, "connect"), 2601 self.sql(expression, "group"), 2602 self.sql(expression, "having"), 2603 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2604 self.sql(expression, "order"), 2605 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2606 *self.after_limit_modifiers(expression), 2607 self.options_modifier(expression), 2608 self.for_modifiers(expression), 2609 sep="", 2610 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2624 def offset_limit_modifiers( 2625 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2626 ) -> t.List[str]: 2627 return [ 2628 self.sql(expression, "offset") if fetch else self.sql(limit), 2629 self.sql(limit) if fetch else self.sql(expression, "offset"), 2630 ]
2637 def select_sql(self, expression: exp.Select) -> str: 2638 into = expression.args.get("into") 2639 if not self.SUPPORTS_SELECT_INTO and into: 2640 into.pop() 2641 2642 hint = self.sql(expression, "hint") 2643 distinct = self.sql(expression, "distinct") 2644 distinct = f" {distinct}" if distinct else "" 2645 kind = self.sql(expression, "kind") 2646 2647 limit = expression.args.get("limit") 2648 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2649 top = self.limit_sql(limit, top=True) 2650 limit.pop() 2651 else: 2652 top = "" 2653 2654 expressions = self.expressions(expression) 2655 2656 if kind: 2657 if kind in self.SELECT_KINDS: 2658 kind = f" AS {kind}" 2659 else: 2660 if kind == "STRUCT": 2661 expressions = self.expressions( 2662 sqls=[ 2663 self.sql( 2664 exp.Struct( 2665 expressions=[ 2666 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2667 if isinstance(e, exp.Alias) 2668 else e 2669 for e in expression.expressions 2670 ] 2671 ) 2672 ) 2673 ] 2674 ) 2675 kind = "" 2676 2677 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2678 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2679 2680 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2681 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2682 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2683 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2684 sql = self.query_modifiers( 2685 expression, 2686 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2687 self.sql(expression, "into", comment=False), 2688 self.sql(expression, "from", comment=False), 2689 ) 2690 2691 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2692 if expression.args.get("with"): 2693 sql = self.maybe_comment(sql, expression) 2694 expression.pop_comments() 2695 2696 sql = self.prepend_ctes(expression, sql) 2697 2698 if not self.SUPPORTS_SELECT_INTO and into: 2699 if into.args.get("temporary"): 2700 table_kind = " TEMPORARY" 2701 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2702 table_kind = " UNLOGGED" 2703 else: 2704 table_kind = "" 2705 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2706 2707 return sql
2719 def star_sql(self, expression: exp.Star) -> str: 2720 except_ = self.expressions(expression, key="except", flat=True) 2721 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2722 replace = self.expressions(expression, key="replace", flat=True) 2723 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2724 rename = self.expressions(expression, key="rename", flat=True) 2725 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2726 return f"*{except_}{replace}{rename}"
2742 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2743 alias = self.sql(expression, "alias") 2744 alias = f"{sep}{alias}" if alias else "" 2745 sample = self.sql(expression, "sample") 2746 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2747 alias = f"{sample}{alias}" 2748 2749 # Set to None so it's not generated again by self.query_modifiers() 2750 expression.set("sample", None) 2751 2752 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2753 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2754 return self.prepend_ctes(expression, sql)
2760 def unnest_sql(self, expression: exp.Unnest) -> str: 2761 args = self.expressions(expression, flat=True) 2762 2763 alias = expression.args.get("alias") 2764 offset = expression.args.get("offset") 2765 2766 if self.UNNEST_WITH_ORDINALITY: 2767 if alias and isinstance(offset, exp.Expression): 2768 alias.append("columns", offset) 2769 2770 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2771 columns = alias.columns 2772 alias = self.sql(columns[0]) if columns else "" 2773 else: 2774 alias = self.sql(alias) 2775 2776 alias = f" AS {alias}" if alias else alias 2777 if self.UNNEST_WITH_ORDINALITY: 2778 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2779 else: 2780 if isinstance(offset, exp.Expression): 2781 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2782 elif offset: 2783 suffix = f"{alias} WITH OFFSET" 2784 else: 2785 suffix = alias 2786 2787 return f"UNNEST({args}){suffix}"
2796 def window_sql(self, expression: exp.Window) -> str: 2797 this = self.sql(expression, "this") 2798 partition = self.partition_by_sql(expression) 2799 order = expression.args.get("order") 2800 order = self.order_sql(order, flat=True) if order else "" 2801 spec = self.sql(expression, "spec") 2802 alias = self.sql(expression, "alias") 2803 over = self.sql(expression, "over") or "OVER" 2804 2805 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2806 2807 first = expression.args.get("first") 2808 if first is None: 2809 first = "" 2810 else: 2811 first = "FIRST" if first else "LAST" 2812 2813 if not partition and not order and not spec and alias: 2814 return f"{this} {alias}" 2815 2816 args = self.format_args( 2817 *[arg for arg in (alias, first, partition, order, spec) if arg], sep=" " 2818 ) 2819 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2825 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2826 kind = self.sql(expression, "kind") 2827 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2828 end = ( 2829 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2830 or "CURRENT ROW" 2831 ) 2832 2833 window_spec = f"{kind} BETWEEN {start} AND {end}" 2834 2835 exclude = self.sql(expression, "exclude") 2836 if exclude: 2837 if self.SUPPORTS_WINDOW_EXCLUDE: 2838 window_spec += f" EXCLUDE {exclude}" 2839 else: 2840 self.unsupported("EXCLUDE clause is not supported in the WINDOW clause") 2841 2842 return window_spec
def
bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]:
2855 def bracket_offset_expressions( 2856 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2857 ) -> t.List[exp.Expression]: 2858 return apply_index_offset( 2859 expression.this, 2860 expression.expressions, 2861 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2862 dialect=self.dialect, 2863 )
2873 def any_sql(self, expression: exp.Any) -> str: 2874 this = self.sql(expression, "this") 2875 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2876 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2877 this = self.wrap(this) 2878 return f"ANY{this}" 2879 return f"ANY {this}"
2884 def case_sql(self, expression: exp.Case) -> str: 2885 this = self.sql(expression, "this") 2886 statements = [f"CASE {this}" if this else "CASE"] 2887 2888 for e in expression.args["ifs"]: 2889 statements.append(f"WHEN {self.sql(e, 'this')}") 2890 statements.append(f"THEN {self.sql(e, 'true')}") 2891 2892 default = self.sql(expression, "default") 2893 2894 if default: 2895 statements.append(f"ELSE {default}") 2896 2897 statements.append("END") 2898 2899 if self.pretty and self.too_wide(statements): 2900 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2901 2902 return " ".join(statements)
2919 def trim_sql(self, expression: exp.Trim) -> str: 2920 trim_type = self.sql(expression, "position") 2921 2922 if trim_type == "LEADING": 2923 func_name = "LTRIM" 2924 elif trim_type == "TRAILING": 2925 func_name = "RTRIM" 2926 else: 2927 func_name = "TRIM" 2928 2929 return self.func(func_name, expression.this, expression.expression)
def
convert_concat_args( self, expression: sqlglot.expressions.Concat | sqlglot.expressions.ConcatWs) -> List[sqlglot.expressions.Expression]:
2931 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2932 args = expression.expressions 2933 if isinstance(expression, exp.ConcatWs): 2934 args = args[1:] # Skip the delimiter 2935 2936 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2937 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2938 2939 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2940 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2941 2942 return args
2944 def concat_sql(self, expression: exp.Concat) -> str: 2945 expressions = self.convert_concat_args(expression) 2946 2947 # Some dialects don't allow a single-argument CONCAT call 2948 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2949 return self.sql(expressions[0]) 2950 2951 return self.func("CONCAT", *expressions)
2962 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2963 expressions = self.expressions(expression, flat=True) 2964 expressions = f" ({expressions})" if expressions else "" 2965 reference = self.sql(expression, "reference") 2966 reference = f" {reference}" if reference else "" 2967 delete = self.sql(expression, "delete") 2968 delete = f" ON DELETE {delete}" if delete else "" 2969 update = self.sql(expression, "update") 2970 update = f" ON UPDATE {update}" if update else "" 2971 options = self.expressions(expression, key="options", flat=True, sep=" ") 2972 options = f" {options}" if options else "" 2973 return f"FOREIGN KEY{expressions}{reference}{delete}{update}{options}"
2975 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2976 expressions = self.expressions(expression, flat=True) 2977 options = self.expressions(expression, key="options", flat=True, sep=" ") 2978 options = f" {options}" if options else "" 2979 return f"PRIMARY KEY ({expressions}){options}"
2992 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2993 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2994 2995 if expression.args.get("escape"): 2996 path = self.escape_str(path) 2997 2998 if self.QUOTE_JSON_PATH: 2999 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 3000 3001 return path
3003 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 3004 if isinstance(expression, exp.JSONPathPart): 3005 transform = self.TRANSFORMS.get(expression.__class__) 3006 if not callable(transform): 3007 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 3008 return "" 3009 3010 return transform(self, expression) 3011 3012 if isinstance(expression, int): 3013 return str(expression) 3014 3015 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 3016 escaped = expression.replace("'", "\\'") 3017 escaped = f"\\'{expression}\\'" 3018 else: 3019 escaped = expression.replace('"', '\\"') 3020 escaped = f'"{escaped}"' 3021 3022 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
3027 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 3028 null_handling = expression.args.get("null_handling") 3029 null_handling = f" {null_handling}" if null_handling else "" 3030 3031 unique_keys = expression.args.get("unique_keys") 3032 if unique_keys is not None: 3033 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 3034 else: 3035 unique_keys = "" 3036 3037 return_type = self.sql(expression, "return_type") 3038 return_type = f" RETURNING {return_type}" if return_type else "" 3039 encoding = self.sql(expression, "encoding") 3040 encoding = f" ENCODING {encoding}" if encoding else "" 3041 3042 return self.func( 3043 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 3044 *expression.expressions, 3045 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 3046 )
3051 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 3052 null_handling = expression.args.get("null_handling") 3053 null_handling = f" {null_handling}" if null_handling else "" 3054 return_type = self.sql(expression, "return_type") 3055 return_type = f" RETURNING {return_type}" if return_type else "" 3056 strict = " STRICT" if expression.args.get("strict") else "" 3057 return self.func( 3058 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 3059 )
3061 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 3062 this = self.sql(expression, "this") 3063 order = self.sql(expression, "order") 3064 null_handling = expression.args.get("null_handling") 3065 null_handling = f" {null_handling}" if null_handling else "" 3066 return_type = self.sql(expression, "return_type") 3067 return_type = f" RETURNING {return_type}" if return_type else "" 3068 strict = " STRICT" if expression.args.get("strict") else "" 3069 return self.func( 3070 "JSON_ARRAYAGG", 3071 this, 3072 suffix=f"{order}{null_handling}{return_type}{strict})", 3073 )
3075 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3076 path = self.sql(expression, "path") 3077 path = f" PATH {path}" if path else "" 3078 nested_schema = self.sql(expression, "nested_schema") 3079 3080 if nested_schema: 3081 return f"NESTED{path} {nested_schema}" 3082 3083 this = self.sql(expression, "this") 3084 kind = self.sql(expression, "kind") 3085 kind = f" {kind}" if kind else "" 3086 return f"{this}{kind}{path}"
3091 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3092 this = self.sql(expression, "this") 3093 path = self.sql(expression, "path") 3094 path = f", {path}" if path else "" 3095 error_handling = expression.args.get("error_handling") 3096 error_handling = f" {error_handling}" if error_handling else "" 3097 empty_handling = expression.args.get("empty_handling") 3098 empty_handling = f" {empty_handling}" if empty_handling else "" 3099 schema = self.sql(expression, "schema") 3100 return self.func( 3101 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3102 )
3104 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3105 this = self.sql(expression, "this") 3106 kind = self.sql(expression, "kind") 3107 path = self.sql(expression, "path") 3108 path = f" {path}" if path else "" 3109 as_json = " AS JSON" if expression.args.get("as_json") else "" 3110 return f"{this} {kind}{path}{as_json}"
3112 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3113 this = self.sql(expression, "this") 3114 path = self.sql(expression, "path") 3115 path = f", {path}" if path else "" 3116 expressions = self.expressions(expression) 3117 with_ = ( 3118 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3119 if expressions 3120 else "" 3121 ) 3122 return f"OPENJSON({this}{path}){with_}"
3124 def in_sql(self, expression: exp.In) -> str: 3125 query = expression.args.get("query") 3126 unnest = expression.args.get("unnest") 3127 field = expression.args.get("field") 3128 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3129 3130 if query: 3131 in_sql = self.sql(query) 3132 elif unnest: 3133 in_sql = self.in_unnest_op(unnest) 3134 elif field: 3135 in_sql = self.sql(field) 3136 else: 3137 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3138 3139 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3144 def interval_sql(self, expression: exp.Interval) -> str: 3145 unit = self.sql(expression, "unit") 3146 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3147 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3148 unit = f" {unit}" if unit else "" 3149 3150 if self.SINGLE_STRING_INTERVAL: 3151 this = expression.this.name if expression.this else "" 3152 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3153 3154 this = self.sql(expression, "this") 3155 if this: 3156 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3157 this = f" {this}" if unwrapped else f" ({this})" 3158 3159 return f"INTERVAL{this}{unit}"
3164 def reference_sql(self, expression: exp.Reference) -> str: 3165 this = self.sql(expression, "this") 3166 expressions = self.expressions(expression, flat=True) 3167 expressions = f"({expressions})" if expressions else "" 3168 options = self.expressions(expression, key="options", flat=True, sep=" ") 3169 options = f" {options}" if options else "" 3170 return f"REFERENCES {this}{expressions}{options}"
3172 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3173 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3174 parent = expression.parent 3175 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3176 return self.func( 3177 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3178 )
3198 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3199 alias = expression.args["alias"] 3200 3201 parent = expression.parent 3202 pivot = parent and parent.parent 3203 3204 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3205 identifier_alias = isinstance(alias, exp.Identifier) 3206 literal_alias = isinstance(alias, exp.Literal) 3207 3208 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3209 alias.replace(exp.Literal.string(alias.output_name)) 3210 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3211 alias.replace(exp.to_identifier(alias.output_name)) 3212 3213 return self.alias_sql(expression)
def
and_sql( self, expression: sqlglot.expressions.And, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
or_sql( self, expression: sqlglot.expressions.Or, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
xor_sql( self, expression: sqlglot.expressions.Xor, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
def
connector_sql( self, expression: sqlglot.expressions.Connector, op: str, stack: Optional[List[str | sqlglot.expressions.Expression]] = None) -> str:
3251 def connector_sql( 3252 self, 3253 expression: exp.Connector, 3254 op: str, 3255 stack: t.Optional[t.List[str | exp.Expression]] = None, 3256 ) -> str: 3257 if stack is not None: 3258 if expression.expressions: 3259 stack.append(self.expressions(expression, sep=f" {op} ")) 3260 else: 3261 stack.append(expression.right) 3262 if expression.comments and self.comments: 3263 for comment in expression.comments: 3264 if comment: 3265 op += f" /*{self.sanitize_comment(comment)}*/" 3266 stack.extend((op, expression.left)) 3267 return op 3268 3269 stack = [expression] 3270 sqls: t.List[str] = [] 3271 ops = set() 3272 3273 while stack: 3274 node = stack.pop() 3275 if isinstance(node, exp.Connector): 3276 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3277 else: 3278 sql = self.sql(node) 3279 if sqls and sqls[-1] in ops: 3280 sqls[-1] += f" {sql}" 3281 else: 3282 sqls.append(sql) 3283 3284 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3285 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3305 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3306 format_sql = self.sql(expression, "format") 3307 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3308 to_sql = self.sql(expression, "to") 3309 to_sql = f" {to_sql}" if to_sql else "" 3310 action = self.sql(expression, "action") 3311 action = f" {action}" if action else "" 3312 default = self.sql(expression, "default") 3313 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3314 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3328 def comment_sql(self, expression: exp.Comment) -> str: 3329 this = self.sql(expression, "this") 3330 kind = expression.args["kind"] 3331 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3332 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3333 expression_sql = self.sql(expression, "expression") 3334 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3336 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3337 this = self.sql(expression, "this") 3338 delete = " DELETE" if expression.args.get("delete") else "" 3339 recompress = self.sql(expression, "recompress") 3340 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3341 to_disk = self.sql(expression, "to_disk") 3342 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3343 to_volume = self.sql(expression, "to_volume") 3344 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3345 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3347 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3348 where = self.sql(expression, "where") 3349 group = self.sql(expression, "group") 3350 aggregates = self.expressions(expression, key="aggregates") 3351 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3352 3353 if not (where or group or aggregates) and len(expression.expressions) == 1: 3354 return f"TTL {self.expressions(expression, flat=True)}" 3355 3356 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3373 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3374 this = self.sql(expression, "this") 3375 3376 dtype = self.sql(expression, "dtype") 3377 if dtype: 3378 collate = self.sql(expression, "collate") 3379 collate = f" COLLATE {collate}" if collate else "" 3380 using = self.sql(expression, "using") 3381 using = f" USING {using}" if using else "" 3382 alter_set_type = self.ALTER_SET_TYPE + " " if self.ALTER_SET_TYPE else "" 3383 return f"ALTER COLUMN {this} {alter_set_type}{dtype}{collate}{using}" 3384 3385 default = self.sql(expression, "default") 3386 if default: 3387 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3388 3389 comment = self.sql(expression, "comment") 3390 if comment: 3391 return f"ALTER COLUMN {this} COMMENT {comment}" 3392 3393 visible = expression.args.get("visible") 3394 if visible: 3395 return f"ALTER COLUMN {this} SET {visible}" 3396 3397 allow_null = expression.args.get("allow_null") 3398 drop = expression.args.get("drop") 3399 3400 if not drop and not allow_null: 3401 self.unsupported("Unsupported ALTER COLUMN syntax") 3402 3403 if allow_null is not None: 3404 keyword = "DROP" if drop else "SET" 3405 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3406 3407 return f"ALTER COLUMN {this} DROP DEFAULT"
3423 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3424 compound = " COMPOUND" if expression.args.get("compound") else "" 3425 this = self.sql(expression, "this") 3426 expressions = self.expressions(expression, flat=True) 3427 expressions = f"({expressions})" if expressions else "" 3428 return f"ALTER{compound} SORTKEY {this or expressions}"
3430 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3431 if not self.RENAME_TABLE_WITH_DB: 3432 # Remove db from tables 3433 expression = expression.transform( 3434 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3435 ).assert_is(exp.AlterRename) 3436 this = self.sql(expression, "this") 3437 return f"RENAME TO {this}"
3452 def alter_sql(self, expression: exp.Alter) -> str: 3453 actions = expression.args["actions"] 3454 3455 if not self.dialect.ALTER_TABLE_ADD_REQUIRED_FOR_EACH_COLUMN and isinstance( 3456 actions[0], exp.ColumnDef 3457 ): 3458 actions_sql = self.expressions(expression, key="actions", flat=True) 3459 actions_sql = f"ADD {actions_sql}" 3460 else: 3461 actions_list = [] 3462 for action in actions: 3463 if isinstance(action, (exp.ColumnDef, exp.Schema)): 3464 action_sql = self.add_column_sql(action) 3465 else: 3466 action_sql = self.sql(action) 3467 if isinstance(action, exp.Query): 3468 action_sql = f"AS {action_sql}" 3469 3470 actions_list.append(action_sql) 3471 3472 actions_sql = self.format_args(*actions_list) 3473 3474 exists = " IF EXISTS" if expression.args.get("exists") else "" 3475 on_cluster = self.sql(expression, "cluster") 3476 on_cluster = f" {on_cluster}" if on_cluster else "" 3477 only = " ONLY" if expression.args.get("only") else "" 3478 options = self.expressions(expression, key="options") 3479 options = f", {options}" if options else "" 3480 kind = self.sql(expression, "kind") 3481 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3482 3483 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions_sql}{not_valid}{options}"
3485 def add_column_sql(self, expression: exp.Expression) -> str: 3486 sql = self.sql(expression) 3487 if isinstance(expression, exp.Schema): 3488 column_text = " COLUMNS" 3489 elif isinstance(expression, exp.ColumnDef) and self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3490 column_text = " COLUMN" 3491 else: 3492 column_text = "" 3493 3494 return f"ADD{column_text} {sql}"
3504 def distinct_sql(self, expression: exp.Distinct) -> str: 3505 this = self.expressions(expression, flat=True) 3506 3507 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3508 case = exp.case() 3509 for arg in expression.expressions: 3510 case = case.when(arg.is_(exp.null()), exp.null()) 3511 this = self.sql(case.else_(f"({this})")) 3512 3513 this = f" {this}" if this else "" 3514 3515 on = self.sql(expression, "on") 3516 on = f" ON {on}" if on else "" 3517 return f"DISTINCT{this}{on}"
3546 def div_sql(self, expression: exp.Div) -> str: 3547 l, r = expression.left, expression.right 3548 3549 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3550 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3551 3552 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3553 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3554 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3555 3556 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3557 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3558 return self.sql( 3559 exp.cast( 3560 l / r, 3561 to=exp.DataType.Type.BIGINT, 3562 ) 3563 ) 3564 3565 return self.binary(expression, "/")
3661 def log_sql(self, expression: exp.Log) -> str: 3662 this = expression.this 3663 expr = expression.expression 3664 3665 if self.dialect.LOG_BASE_FIRST is False: 3666 this, expr = expr, this 3667 elif self.dialect.LOG_BASE_FIRST is None and expr: 3668 if this.name in ("2", "10"): 3669 return self.func(f"LOG{this.name}", expr) 3670 3671 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3672 3673 return self.func("LOG", this, expr)
3682 def binary(self, expression: exp.Binary, op: str) -> str: 3683 sqls: t.List[str] = [] 3684 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3685 binary_type = type(expression) 3686 3687 while stack: 3688 node = stack.pop() 3689 3690 if type(node) is binary_type: 3691 op_func = node.args.get("operator") 3692 if op_func: 3693 op = f"OPERATOR({self.sql(op_func)})" 3694 3695 stack.append(node.right) 3696 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3697 stack.append(node.left) 3698 else: 3699 sqls.append(self.sql(node)) 3700 3701 return "".join(sqls)
3710 def function_fallback_sql(self, expression: exp.Func) -> str: 3711 args = [] 3712 3713 for key in expression.arg_types: 3714 arg_value = expression.args.get(key) 3715 3716 if isinstance(arg_value, list): 3717 for value in arg_value: 3718 args.append(value) 3719 elif arg_value is not None: 3720 args.append(arg_value) 3721 3722 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3723 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3724 else: 3725 name = expression.sql_name() 3726 3727 return self.func(name, *args)
def
func( self, name: str, *args: Union[str, sqlglot.expressions.Expression, NoneType], prefix: str = '(', suffix: str = ')', normalize: bool = True) -> str:
3729 def func( 3730 self, 3731 name: str, 3732 *args: t.Optional[exp.Expression | str], 3733 prefix: str = "(", 3734 suffix: str = ")", 3735 normalize: bool = True, 3736 ) -> str: 3737 name = self.normalize_func(name) if normalize else name 3738 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3740 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3741 arg_sqls = tuple( 3742 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3743 ) 3744 if self.pretty and self.too_wide(arg_sqls): 3745 return self.indent( 3746 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3747 ) 3748 return sep.join(arg_sqls)
def
format_time( self, expression: sqlglot.expressions.Expression, inverse_time_mapping: Optional[Dict[str, str]] = None, inverse_time_trie: Optional[Dict] = None) -> Optional[str]:
3753 def format_time( 3754 self, 3755 expression: exp.Expression, 3756 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3757 inverse_time_trie: t.Optional[t.Dict] = None, 3758 ) -> t.Optional[str]: 3759 return format_time( 3760 self.sql(expression, "format"), 3761 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3762 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3763 )
def
expressions( self, expression: Optional[sqlglot.expressions.Expression] = None, key: Optional[str] = None, sqls: Optional[Collection[Union[str, sqlglot.expressions.Expression]]] = 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:
3765 def expressions( 3766 self, 3767 expression: t.Optional[exp.Expression] = None, 3768 key: t.Optional[str] = None, 3769 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3770 flat: bool = False, 3771 indent: bool = True, 3772 skip_first: bool = False, 3773 skip_last: bool = False, 3774 sep: str = ", ", 3775 prefix: str = "", 3776 dynamic: bool = False, 3777 new_line: bool = False, 3778 ) -> str: 3779 expressions = expression.args.get(key or "expressions") if expression else sqls 3780 3781 if not expressions: 3782 return "" 3783 3784 if flat: 3785 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3786 3787 num_sqls = len(expressions) 3788 result_sqls = [] 3789 3790 for i, e in enumerate(expressions): 3791 sql = self.sql(e, comment=False) 3792 if not sql: 3793 continue 3794 3795 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3796 3797 if self.pretty: 3798 if self.leading_comma: 3799 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3800 else: 3801 result_sqls.append( 3802 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3803 ) 3804 else: 3805 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3806 3807 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3808 if new_line: 3809 result_sqls.insert(0, "") 3810 result_sqls.append("") 3811 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3812 else: 3813 result_sql = "".join(result_sqls) 3814 3815 return ( 3816 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3817 if indent 3818 else result_sql 3819 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3821 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3822 flat = flat or isinstance(expression.parent, exp.Properties) 3823 expressions_sql = self.expressions(expression, flat=flat) 3824 if flat: 3825 return f"{op} {expressions_sql}" 3826 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3828 def naked_property(self, expression: exp.Property) -> str: 3829 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3830 if not property_name: 3831 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3832 return f"{property_name} {self.sql(expression, 'this')}"
3840 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3841 this = self.sql(expression, "this") 3842 expressions = self.no_identify(self.expressions, expression) 3843 expressions = ( 3844 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3845 ) 3846 return f"{this}{expressions}" if expressions.strip() != "" else this
3856 def when_sql(self, expression: exp.When) -> str: 3857 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3858 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3859 condition = self.sql(expression, "condition") 3860 condition = f" AND {condition}" if condition else "" 3861 3862 then_expression = expression.args.get("then") 3863 if isinstance(then_expression, exp.Insert): 3864 this = self.sql(then_expression, "this") 3865 this = f"INSERT {this}" if this else "INSERT" 3866 then = self.sql(then_expression, "expression") 3867 then = f"{this} VALUES {then}" if then else this 3868 elif isinstance(then_expression, exp.Update): 3869 if isinstance(then_expression.args.get("expressions"), exp.Star): 3870 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3871 else: 3872 then = f"UPDATE SET{self.sep()}{self.expressions(then_expression)}" 3873 else: 3874 then = self.sql(then_expression) 3875 return f"WHEN {matched}{source}{condition} THEN {then}"
3880 def merge_sql(self, expression: exp.Merge) -> str: 3881 table = expression.this 3882 table_alias = "" 3883 3884 hints = table.args.get("hints") 3885 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3886 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3887 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3888 3889 this = self.sql(table) 3890 using = f"USING {self.sql(expression, 'using')}" 3891 on = f"ON {self.sql(expression, 'on')}" 3892 whens = self.sql(expression, "whens") 3893 3894 returning = self.sql(expression, "returning") 3895 if returning: 3896 whens = f"{whens}{returning}" 3897 3898 sep = self.sep() 3899 3900 return self.prepend_ctes( 3901 expression, 3902 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3903 )
3909 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3910 if not self.SUPPORTS_TO_NUMBER: 3911 self.unsupported("Unsupported TO_NUMBER function") 3912 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3913 3914 fmt = expression.args.get("format") 3915 if not fmt: 3916 self.unsupported("Conversion format is required for TO_NUMBER") 3917 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3918 3919 return self.func("TO_NUMBER", expression.this, fmt)
3921 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3922 this = self.sql(expression, "this") 3923 kind = self.sql(expression, "kind") 3924 settings_sql = self.expressions(expression, key="settings", sep=" ") 3925 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3926 return f"{this}({kind}{args})"
3945 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3946 expressions = self.expressions(expression, flat=True) 3947 expressions = f" {self.wrap(expressions)}" if expressions else "" 3948 buckets = self.sql(expression, "buckets") 3949 kind = self.sql(expression, "kind") 3950 buckets = f" BUCKETS {buckets}" if buckets else "" 3951 order = self.sql(expression, "order") 3952 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3957 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3958 expressions = self.expressions(expression, key="expressions", flat=True) 3959 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3960 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3961 buckets = self.sql(expression, "buckets") 3962 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3964 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3965 this = self.sql(expression, "this") 3966 having = self.sql(expression, "having") 3967 3968 if having: 3969 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3970 3971 return self.func("ANY_VALUE", this)
3973 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3974 transform = self.func("TRANSFORM", *expression.expressions) 3975 row_format_before = self.sql(expression, "row_format_before") 3976 row_format_before = f" {row_format_before}" if row_format_before else "" 3977 record_writer = self.sql(expression, "record_writer") 3978 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3979 using = f" USING {self.sql(expression, 'command_script')}" 3980 schema = self.sql(expression, "schema") 3981 schema = f" AS {schema}" if schema else "" 3982 row_format_after = self.sql(expression, "row_format_after") 3983 row_format_after = f" {row_format_after}" if row_format_after else "" 3984 record_reader = self.sql(expression, "record_reader") 3985 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3986 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3988 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3989 key_block_size = self.sql(expression, "key_block_size") 3990 if key_block_size: 3991 return f"KEY_BLOCK_SIZE = {key_block_size}" 3992 3993 using = self.sql(expression, "using") 3994 if using: 3995 return f"USING {using}" 3996 3997 parser = self.sql(expression, "parser") 3998 if parser: 3999 return f"WITH PARSER {parser}" 4000 4001 comment = self.sql(expression, "comment") 4002 if comment: 4003 return f"COMMENT {comment}" 4004 4005 visible = expression.args.get("visible") 4006 if visible is not None: 4007 return "VISIBLE" if visible else "INVISIBLE" 4008 4009 engine_attr = self.sql(expression, "engine_attr") 4010 if engine_attr: 4011 return f"ENGINE_ATTRIBUTE = {engine_attr}" 4012 4013 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 4014 if secondary_engine_attr: 4015 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 4016 4017 self.unsupported("Unsupported index constraint option.") 4018 return ""
4024 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 4025 kind = self.sql(expression, "kind") 4026 kind = f"{kind} INDEX" if kind else "INDEX" 4027 this = self.sql(expression, "this") 4028 this = f" {this}" if this else "" 4029 index_type = self.sql(expression, "index_type") 4030 index_type = f" USING {index_type}" if index_type else "" 4031 expressions = self.expressions(expression, flat=True) 4032 expressions = f" ({expressions})" if expressions else "" 4033 options = self.expressions(expression, key="options", sep=" ") 4034 options = f" {options}" if options else "" 4035 return f"{kind}{this}{index_type}{expressions}{options}"
4037 def nvl2_sql(self, expression: exp.Nvl2) -> str: 4038 if self.NVL2_SUPPORTED: 4039 return self.function_fallback_sql(expression) 4040 4041 case = exp.Case().when( 4042 expression.this.is_(exp.null()).not_(copy=False), 4043 expression.args["true"], 4044 copy=False, 4045 ) 4046 else_cond = expression.args.get("false") 4047 if else_cond: 4048 case.else_(else_cond, copy=False) 4049 4050 return self.sql(case)
4052 def comprehension_sql(self, expression: exp.Comprehension) -> str: 4053 this = self.sql(expression, "this") 4054 expr = self.sql(expression, "expression") 4055 iterator = self.sql(expression, "iterator") 4056 condition = self.sql(expression, "condition") 4057 condition = f" IF {condition}" if condition else "" 4058 return f"{this} FOR {expr} IN {iterator}{condition}"
4066 def predict_sql(self, expression: exp.Predict) -> str: 4067 model = self.sql(expression, "this") 4068 model = f"MODEL {model}" 4069 table = self.sql(expression, "expression") 4070 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 4071 parameters = self.sql(expression, "params_struct") 4072 return self.func("PREDICT", model, table, parameters or None)
4084 def toarray_sql(self, expression: exp.ToArray) -> str: 4085 arg = expression.this 4086 if not arg.type: 4087 from sqlglot.optimizer.annotate_types import annotate_types 4088 4089 arg = annotate_types(arg, dialect=self.dialect) 4090 4091 if arg.is_type(exp.DataType.Type.ARRAY): 4092 return self.sql(arg) 4093 4094 cond_for_null = arg.is_(exp.null()) 4095 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4097 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4098 this = expression.this 4099 time_format = self.format_time(expression) 4100 4101 if time_format: 4102 return self.sql( 4103 exp.cast( 4104 exp.StrToTime(this=this, format=expression.args["format"]), 4105 exp.DataType.Type.TIME, 4106 ) 4107 ) 4108 4109 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4110 return self.sql(this) 4111 4112 return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4114 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4115 this = expression.this 4116 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4117 return self.sql(this) 4118 4119 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4121 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4122 this = expression.this 4123 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4124 return self.sql(this) 4125 4126 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4128 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4129 this = expression.this 4130 time_format = self.format_time(expression) 4131 4132 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4133 return self.sql( 4134 exp.cast( 4135 exp.StrToTime(this=this, format=expression.args["format"]), 4136 exp.DataType.Type.DATE, 4137 ) 4138 ) 4139 4140 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4141 return self.sql(this) 4142 4143 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4155 def lastday_sql(self, expression: exp.LastDay) -> str: 4156 if self.LAST_DAY_SUPPORTS_DATE_PART: 4157 return self.function_fallback_sql(expression) 4158 4159 unit = expression.text("unit") 4160 if unit and unit != "MONTH": 4161 self.unsupported("Date parts are not supported in LAST_DAY.") 4162 4163 return self.func("LAST_DAY", expression.this)
4172 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4173 if self.CAN_IMPLEMENT_ARRAY_ANY: 4174 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4175 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4176 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4177 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4178 4179 from sqlglot.dialects import Dialect 4180 4181 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4182 if self.dialect.__class__ != Dialect: 4183 self.unsupported("ARRAY_ANY is unsupported") 4184 4185 return self.function_fallback_sql(expression)
4187 def struct_sql(self, expression: exp.Struct) -> str: 4188 expression.set( 4189 "expressions", 4190 [ 4191 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4192 if isinstance(e, exp.PropertyEQ) 4193 else e 4194 for e in expression.expressions 4195 ], 4196 ) 4197 4198 return self.function_fallback_sql(expression)
4206 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4207 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4208 tables = f" {self.expressions(expression)}" 4209 4210 exists = " IF EXISTS" if expression.args.get("exists") else "" 4211 4212 on_cluster = self.sql(expression, "cluster") 4213 on_cluster = f" {on_cluster}" if on_cluster else "" 4214 4215 identity = self.sql(expression, "identity") 4216 identity = f" {identity} IDENTITY" if identity else "" 4217 4218 option = self.sql(expression, "option") 4219 option = f" {option}" if option else "" 4220 4221 partition = self.sql(expression, "partition") 4222 partition = f" {partition}" if partition else "" 4223 4224 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4228 def convert_sql(self, expression: exp.Convert) -> str: 4229 to = expression.this 4230 value = expression.expression 4231 style = expression.args.get("style") 4232 safe = expression.args.get("safe") 4233 strict = expression.args.get("strict") 4234 4235 if not to or not value: 4236 return "" 4237 4238 # Retrieve length of datatype and override to default if not specified 4239 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4240 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4241 4242 transformed: t.Optional[exp.Expression] = None 4243 cast = exp.Cast if strict else exp.TryCast 4244 4245 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4246 if isinstance(style, exp.Literal) and style.is_int: 4247 from sqlglot.dialects.tsql import TSQL 4248 4249 style_value = style.name 4250 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4251 if not converted_style: 4252 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4253 4254 fmt = exp.Literal.string(converted_style) 4255 4256 if to.this == exp.DataType.Type.DATE: 4257 transformed = exp.StrToDate(this=value, format=fmt) 4258 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4259 transformed = exp.StrToTime(this=value, format=fmt) 4260 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4261 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4262 elif to.this == exp.DataType.Type.TEXT: 4263 transformed = exp.TimeToStr(this=value, format=fmt) 4264 4265 if not transformed: 4266 transformed = cast(this=value, to=to, safe=safe) 4267 4268 return self.sql(transformed)
4336 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4337 option = self.sql(expression, "this") 4338 4339 if expression.expressions: 4340 upper = option.upper() 4341 4342 # Snowflake FILE_FORMAT options are separated by whitespace 4343 sep = " " if upper == "FILE_FORMAT" else ", " 4344 4345 # Databricks copy/format options do not set their list of values with EQ 4346 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4347 values = self.expressions(expression, flat=True, sep=sep) 4348 return f"{option}{op}({values})" 4349 4350 value = self.sql(expression, "expression") 4351 4352 if not value: 4353 return option 4354 4355 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4356 4357 return f"{option}{op}{value}"
4359 def credentials_sql(self, expression: exp.Credentials) -> str: 4360 cred_expr = expression.args.get("credentials") 4361 if isinstance(cred_expr, exp.Literal): 4362 # Redshift case: CREDENTIALS <string> 4363 credentials = self.sql(expression, "credentials") 4364 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4365 else: 4366 # Snowflake case: CREDENTIALS = (...) 4367 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4368 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4369 4370 storage = self.sql(expression, "storage") 4371 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4372 4373 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4374 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4375 4376 iam_role = self.sql(expression, "iam_role") 4377 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4378 4379 region = self.sql(expression, "region") 4380 region = f" REGION {region}" if region else "" 4381 4382 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4384 def copy_sql(self, expression: exp.Copy) -> str: 4385 this = self.sql(expression, "this") 4386 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4387 4388 credentials = self.sql(expression, "credentials") 4389 credentials = self.seg(credentials) if credentials else "" 4390 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4391 files = self.expressions(expression, key="files", flat=True) 4392 4393 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4394 params = self.expressions( 4395 expression, 4396 key="params", 4397 sep=sep, 4398 new_line=True, 4399 skip_last=True, 4400 skip_first=True, 4401 indent=self.COPY_PARAMS_ARE_WRAPPED, 4402 ) 4403 4404 if params: 4405 if self.COPY_PARAMS_ARE_WRAPPED: 4406 params = f" WITH ({params})" 4407 elif not self.pretty: 4408 params = f" {params}" 4409 4410 return f"COPY{this}{kind} {files}{credentials}{params}"
4415 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4416 on_sql = "ON" if expression.args.get("on") else "OFF" 4417 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4418 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4419 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4420 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4421 4422 if filter_col or retention_period: 4423 on_sql = self.func("ON", filter_col, retention_period) 4424 4425 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4427 def maskingpolicycolumnconstraint_sql( 4428 self, expression: exp.MaskingPolicyColumnConstraint 4429 ) -> str: 4430 this = self.sql(expression, "this") 4431 expressions = self.expressions(expression, flat=True) 4432 expressions = f" USING ({expressions})" if expressions else "" 4433 return f"MASKING POLICY {this}{expressions}"
4443 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4444 this = self.sql(expression, "this") 4445 expr = expression.expression 4446 4447 if isinstance(expr, exp.Func): 4448 # T-SQL's CLR functions are case sensitive 4449 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4450 else: 4451 expr = self.sql(expression, "expression") 4452 4453 return self.scope_resolution(expr, this)
4461 def rand_sql(self, expression: exp.Rand) -> str: 4462 lower = self.sql(expression, "lower") 4463 upper = self.sql(expression, "upper") 4464 4465 if lower and upper: 4466 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4467 return self.func("RAND", expression.this)
4469 def changes_sql(self, expression: exp.Changes) -> str: 4470 information = self.sql(expression, "information") 4471 information = f"INFORMATION => {information}" 4472 at_before = self.sql(expression, "at_before") 4473 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4474 end = self.sql(expression, "end") 4475 end = f"{self.seg('')}{end}" if end else "" 4476 4477 return f"CHANGES ({information}){at_before}{end}"
4479 def pad_sql(self, expression: exp.Pad) -> str: 4480 prefix = "L" if expression.args.get("is_left") else "R" 4481 4482 fill_pattern = self.sql(expression, "fill_pattern") or None 4483 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4484 fill_pattern = "' '" 4485 4486 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4492 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4493 generate_series = exp.GenerateSeries(**expression.args) 4494 4495 parent = expression.parent 4496 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4497 parent = parent.parent 4498 4499 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4500 return self.sql(exp.Unnest(expressions=[generate_series])) 4501 4502 if isinstance(parent, exp.Select): 4503 self.unsupported("GenerateSeries projection unnesting is not supported.") 4504 4505 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4507 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4508 exprs = expression.expressions 4509 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4510 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4511 else: 4512 rhs = self.expressions(expression) 4513 4514 return self.func(name, expression.this, rhs or None)
4516 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4517 if self.SUPPORTS_CONVERT_TIMEZONE: 4518 return self.function_fallback_sql(expression) 4519 4520 source_tz = expression.args.get("source_tz") 4521 target_tz = expression.args.get("target_tz") 4522 timestamp = expression.args.get("timestamp") 4523 4524 if source_tz and timestamp: 4525 timestamp = exp.AtTimeZone( 4526 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4527 ) 4528 4529 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4530 4531 return self.sql(expr)
4533 def json_sql(self, expression: exp.JSON) -> str: 4534 this = self.sql(expression, "this") 4535 this = f" {this}" if this else "" 4536 4537 _with = expression.args.get("with") 4538 4539 if _with is None: 4540 with_sql = "" 4541 elif not _with: 4542 with_sql = " WITHOUT" 4543 else: 4544 with_sql = " WITH" 4545 4546 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4547 4548 return f"JSON{this}{with_sql}{unique_sql}"
4550 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4551 def _generate_on_options(arg: t.Any) -> str: 4552 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4553 4554 path = self.sql(expression, "path") 4555 returning = self.sql(expression, "returning") 4556 returning = f" RETURNING {returning}" if returning else "" 4557 4558 on_condition = self.sql(expression, "on_condition") 4559 on_condition = f" {on_condition}" if on_condition else "" 4560 4561 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4563 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4564 else_ = "ELSE " if expression.args.get("else_") else "" 4565 condition = self.sql(expression, "expression") 4566 condition = f"WHEN {condition} THEN " if condition else else_ 4567 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4568 return f"{condition}{insert}"
4576 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4577 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4578 empty = expression.args.get("empty") 4579 empty = ( 4580 f"DEFAULT {empty} ON EMPTY" 4581 if isinstance(empty, exp.Expression) 4582 else self.sql(expression, "empty") 4583 ) 4584 4585 error = expression.args.get("error") 4586 error = ( 4587 f"DEFAULT {error} ON ERROR" 4588 if isinstance(error, exp.Expression) 4589 else self.sql(expression, "error") 4590 ) 4591 4592 if error and empty: 4593 error = ( 4594 f"{empty} {error}" 4595 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4596 else f"{error} {empty}" 4597 ) 4598 empty = "" 4599 4600 null = self.sql(expression, "null") 4601 4602 return f"{empty}{error}{null}"
4608 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4609 this = self.sql(expression, "this") 4610 path = self.sql(expression, "path") 4611 4612 passing = self.expressions(expression, "passing") 4613 passing = f" PASSING {passing}" if passing else "" 4614 4615 on_condition = self.sql(expression, "on_condition") 4616 on_condition = f" {on_condition}" if on_condition else "" 4617 4618 path = f"{path}{passing}{on_condition}" 4619 4620 return self.func("JSON_EXISTS", this, path)
4622 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4623 array_agg = self.function_fallback_sql(expression) 4624 4625 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4626 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4627 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4628 parent = expression.parent 4629 if isinstance(parent, exp.Filter): 4630 parent_cond = parent.expression.this 4631 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4632 else: 4633 this = expression.this 4634 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4635 if this.find(exp.Column): 4636 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4637 this_sql = ( 4638 self.expressions(this) 4639 if isinstance(this, exp.Distinct) 4640 else self.sql(expression, "this") 4641 ) 4642 4643 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4644 4645 return array_agg
4653 def grant_sql(self, expression: exp.Grant) -> str: 4654 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4655 4656 kind = self.sql(expression, "kind") 4657 kind = f" {kind}" if kind else "" 4658 4659 securable = self.sql(expression, "securable") 4660 securable = f" {securable}" if securable else "" 4661 4662 principals = self.expressions(expression, key="principals", flat=True) 4663 4664 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4665 4666 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4690 def overlay_sql(self, expression: exp.Overlay): 4691 this = self.sql(expression, "this") 4692 expr = self.sql(expression, "expression") 4693 from_sql = self.sql(expression, "from") 4694 for_sql = self.sql(expression, "for") 4695 for_sql = f" FOR {for_sql}" if for_sql else "" 4696 4697 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4703 def string_sql(self, expression: exp.String) -> str: 4704 this = expression.this 4705 zone = expression.args.get("zone") 4706 4707 if zone: 4708 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4709 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4710 # set for source_tz to transpile the time conversion before the STRING cast 4711 this = exp.ConvertTimezone( 4712 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4713 ) 4714 4715 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4725 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4726 filler = self.sql(expression, "this") 4727 filler = f" {filler}" if filler else "" 4728 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4729 return f"TRUNCATE{filler} {with_count}"
4731 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4732 if self.SUPPORTS_UNIX_SECONDS: 4733 return self.function_fallback_sql(expression) 4734 4735 start_ts = exp.cast( 4736 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4737 ) 4738 4739 return self.sql( 4740 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4741 )
4743 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4744 dim = expression.expression 4745 4746 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4747 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4748 if not (dim.is_int and dim.name == "1"): 4749 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4750 dim = None 4751 4752 # If dimension is required but not specified, default initialize it 4753 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4754 dim = exp.Literal.number(1) 4755 4756 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4758 def attach_sql(self, expression: exp.Attach) -> str: 4759 this = self.sql(expression, "this") 4760 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4761 expressions = self.expressions(expression) 4762 expressions = f" ({expressions})" if expressions else "" 4763 4764 return f"ATTACH{exists_sql} {this}{expressions}"
4778 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4779 this_sql = self.sql(expression, "this") 4780 if isinstance(expression.this, exp.Table): 4781 this_sql = f"TABLE {this_sql}" 4782 4783 return self.func( 4784 "FEATURES_AT_TIME", 4785 this_sql, 4786 expression.args.get("time"), 4787 expression.args.get("num_rows"), 4788 expression.args.get("ignore_feature_nulls"), 4789 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4796 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4797 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4798 encode = f"{encode} {self.sql(expression, 'this')}" 4799 4800 properties = expression.args.get("properties") 4801 if properties: 4802 encode = f"{encode} {self.properties(properties)}" 4803 4804 return encode
4806 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4807 this = self.sql(expression, "this") 4808 include = f"INCLUDE {this}" 4809 4810 column_def = self.sql(expression, "column_def") 4811 if column_def: 4812 include = f"{include} {column_def}" 4813 4814 alias = self.sql(expression, "alias") 4815 if alias: 4816 include = f"{include} AS {alias}" 4817 4818 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4830 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4831 partitions = self.expressions(expression, "partition_expressions") 4832 create = self.expressions(expression, "create_expressions") 4833 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4835 def partitionbyrangepropertydynamic_sql( 4836 self, expression: exp.PartitionByRangePropertyDynamic 4837 ) -> str: 4838 start = self.sql(expression, "start") 4839 end = self.sql(expression, "end") 4840 4841 every = expression.args["every"] 4842 if isinstance(every, exp.Interval) and every.this.is_string: 4843 every.this.replace(exp.Literal.number(every.name)) 4844 4845 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4858 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4859 kind = self.sql(expression, "kind") 4860 option = self.sql(expression, "option") 4861 option = f" {option}" if option else "" 4862 this = self.sql(expression, "this") 4863 this = f" {this}" if this else "" 4864 columns = self.expressions(expression) 4865 columns = f" {columns}" if columns else "" 4866 return f"{kind}{option} STATISTICS{this}{columns}"
4868 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4869 this = self.sql(expression, "this") 4870 columns = self.expressions(expression) 4871 inner_expression = self.sql(expression, "expression") 4872 inner_expression = f" {inner_expression}" if inner_expression else "" 4873 update_options = self.sql(expression, "update_options") 4874 update_options = f" {update_options} UPDATE" if update_options else "" 4875 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4886 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4887 kind = self.sql(expression, "kind") 4888 this = self.sql(expression, "this") 4889 this = f" {this}" if this else "" 4890 inner_expression = self.sql(expression, "expression") 4891 return f"VALIDATE {kind}{this}{inner_expression}"
4893 def analyze_sql(self, expression: exp.Analyze) -> str: 4894 options = self.expressions(expression, key="options", sep=" ") 4895 options = f" {options}" if options else "" 4896 kind = self.sql(expression, "kind") 4897 kind = f" {kind}" if kind else "" 4898 this = self.sql(expression, "this") 4899 this = f" {this}" if this else "" 4900 mode = self.sql(expression, "mode") 4901 mode = f" {mode}" if mode else "" 4902 properties = self.sql(expression, "properties") 4903 properties = f" {properties}" if properties else "" 4904 partition = self.sql(expression, "partition") 4905 partition = f" {partition}" if partition else "" 4906 inner_expression = self.sql(expression, "expression") 4907 inner_expression = f" {inner_expression}" if inner_expression else "" 4908 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4910 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4911 this = self.sql(expression, "this") 4912 namespaces = self.expressions(expression, key="namespaces") 4913 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4914 passing = self.expressions(expression, key="passing") 4915 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4916 columns = self.expressions(expression, key="columns") 4917 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4918 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4919 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4925 def export_sql(self, expression: exp.Export) -> str: 4926 this = self.sql(expression, "this") 4927 connection = self.sql(expression, "connection") 4928 connection = f"WITH CONNECTION {connection} " if connection else "" 4929 options = self.sql(expression, "options") 4930 return f"EXPORT DATA {connection}{options} AS {this}"
4935 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4936 variable = self.sql(expression, "this") 4937 default = self.sql(expression, "default") 4938 default = f" = {default}" if default else "" 4939 4940 kind = self.sql(expression, "kind") 4941 if isinstance(expression.args.get("kind"), exp.Schema): 4942 kind = f"TABLE {kind}" 4943 4944 return f"{variable} AS {kind}{default}"
4946 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4947 kind = self.sql(expression, "kind") 4948 this = self.sql(expression, "this") 4949 set = self.sql(expression, "expression") 4950 using = self.sql(expression, "using") 4951 using = f" USING {using}" if using else "" 4952 4953 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4954 4955 return f"{kind_sql} {this} SET {set}{using}"
def
combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4974 def get_put_sql(self, expression: exp.Put | exp.Get) -> str: 4975 # Snowflake GET/PUT statements: 4976 # PUT <file> <internalStage> <properties> 4977 # GET <internalStage> <file> <properties> 4978 props = expression.args.get("properties") 4979 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4980 this = self.sql(expression, "this") 4981 target = self.sql(expression, "target") 4982 4983 if isinstance(expression, exp.Put): 4984 return f"PUT {this} {target}{props_sql}" 4985 else: 4986 return f"GET {target} {this}{props_sql}"