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.CopyGrantsProperty: lambda *_: "COPY GRANTS", 135 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 136 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 137 exp.DynamicProperty: lambda *_: "DYNAMIC", 138 exp.EmptyProperty: lambda *_: "EMPTY", 139 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 140 exp.EphemeralColumnConstraint: lambda self, 141 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 142 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 143 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 144 exp.Except: lambda self, e: self.set_operations(e), 145 exp.ExternalProperty: lambda *_: "EXTERNAL", 146 exp.Floor: lambda self, e: self.ceil_floor(e), 147 exp.GlobalProperty: lambda *_: "GLOBAL", 148 exp.HeapProperty: lambda *_: "HEAP", 149 exp.IcebergProperty: lambda *_: "ICEBERG", 150 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 151 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 152 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 153 exp.Intersect: lambda self, e: self.set_operations(e), 154 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 155 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 156 exp.LanguageProperty: lambda self, e: self.naked_property(e), 157 exp.LocationProperty: lambda self, e: self.naked_property(e), 158 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 159 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 160 exp.NonClusteredColumnConstraint: lambda self, 161 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 162 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 163 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 164 exp.OnCommitProperty: lambda _, 165 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 166 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 167 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 168 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 169 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 170 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 171 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 172 exp.ProjectionPolicyColumnConstraint: lambda self, 173 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 174 exp.RemoteWithConnectionModelProperty: lambda self, 175 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 176 exp.ReturnsProperty: lambda self, e: ( 177 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 178 ), 179 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 180 exp.SecureProperty: lambda *_: "SECURE", 181 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 182 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 183 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 184 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 185 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 186 exp.SqlReadWriteProperty: lambda _, e: e.name, 187 exp.SqlSecurityProperty: lambda _, 188 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 189 exp.StabilityProperty: lambda _, e: e.name, 190 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 191 exp.StreamingTableProperty: lambda *_: "STREAMING", 192 exp.StrictProperty: lambda *_: "STRICT", 193 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 194 exp.TemporaryProperty: lambda *_: "TEMPORARY", 195 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 196 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 197 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 198 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 199 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 200 exp.TransientProperty: lambda *_: "TRANSIENT", 201 exp.Union: lambda self, e: self.set_operations(e), 202 exp.UnloggedProperty: lambda *_: "UNLOGGED", 203 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 204 exp.Uuid: lambda *_: "UUID()", 205 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 206 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 207 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 208 exp.VolatileProperty: lambda *_: "VOLATILE", 209 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 210 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 211 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 212 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 213 } 214 215 # Whether null ordering is supported in order by 216 # True: Full Support, None: No support, False: No support for certain cases 217 # such as window specifications, aggregate functions etc 218 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 219 220 # Whether ignore nulls is inside the agg or outside. 221 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 222 IGNORE_NULLS_IN_FUNC = False 223 224 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 225 LOCKING_READS_SUPPORTED = False 226 227 # Whether the EXCEPT and INTERSECT operations can return duplicates 228 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 229 230 # Wrap derived values in parens, usually standard but spark doesn't support it 231 WRAP_DERIVED_VALUES = True 232 233 # Whether create function uses an AS before the RETURN 234 CREATE_FUNCTION_RETURN_AS = True 235 236 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 237 MATCHED_BY_SOURCE = True 238 239 # Whether the INTERVAL expression works only with values like '1 day' 240 SINGLE_STRING_INTERVAL = False 241 242 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 243 INTERVAL_ALLOWS_PLURAL_FORM = True 244 245 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 246 LIMIT_FETCH = "ALL" 247 248 # Whether limit and fetch allows expresions or just limits 249 LIMIT_ONLY_LITERALS = False 250 251 # Whether a table is allowed to be renamed with a db 252 RENAME_TABLE_WITH_DB = True 253 254 # The separator for grouping sets and rollups 255 GROUPINGS_SEP = "," 256 257 # The string used for creating an index on a table 258 INDEX_ON = "ON" 259 260 # Whether join hints should be generated 261 JOIN_HINTS = True 262 263 # Whether table hints should be generated 264 TABLE_HINTS = True 265 266 # Whether query hints should be generated 267 QUERY_HINTS = True 268 269 # What kind of separator to use for query hints 270 QUERY_HINT_SEP = ", " 271 272 # Whether comparing against booleans (e.g. x IS TRUE) is supported 273 IS_BOOL_ALLOWED = True 274 275 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 276 DUPLICATE_KEY_UPDATE_WITH_SET = True 277 278 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 279 LIMIT_IS_TOP = False 280 281 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 282 RETURNING_END = True 283 284 # Whether to generate an unquoted value for EXTRACT's date part argument 285 EXTRACT_ALLOWS_QUOTES = True 286 287 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 288 TZ_TO_WITH_TIME_ZONE = False 289 290 # Whether the NVL2 function is supported 291 NVL2_SUPPORTED = True 292 293 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 294 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 295 296 # Whether VALUES statements can be used as derived tables. 297 # MySQL 5 and Redshift do not allow this, so when False, it will convert 298 # SELECT * VALUES into SELECT UNION 299 VALUES_AS_TABLE = True 300 301 # Whether the word COLUMN is included when adding a column with ALTER TABLE 302 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 303 304 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 305 UNNEST_WITH_ORDINALITY = True 306 307 # Whether FILTER (WHERE cond) can be used for conditional aggregation 308 AGGREGATE_FILTER_SUPPORTED = True 309 310 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 311 SEMI_ANTI_JOIN_WITH_SIDE = True 312 313 # Whether to include the type of a computed column in the CREATE DDL 314 COMPUTED_COLUMN_WITH_TYPE = True 315 316 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 317 SUPPORTS_TABLE_COPY = True 318 319 # Whether parentheses are required around the table sample's expression 320 TABLESAMPLE_REQUIRES_PARENS = True 321 322 # Whether a table sample clause's size needs to be followed by the ROWS keyword 323 TABLESAMPLE_SIZE_IS_ROWS = True 324 325 # The keyword(s) to use when generating a sample clause 326 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 327 328 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 329 TABLESAMPLE_WITH_METHOD = True 330 331 # The keyword to use when specifying the seed of a sample clause 332 TABLESAMPLE_SEED_KEYWORD = "SEED" 333 334 # Whether COLLATE is a function instead of a binary operator 335 COLLATE_IS_FUNC = False 336 337 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 338 DATA_TYPE_SPECIFIERS_ALLOWED = False 339 340 # Whether conditions require booleans WHERE x = 0 vs WHERE x 341 ENSURE_BOOLS = False 342 343 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 344 CTE_RECURSIVE_KEYWORD_REQUIRED = True 345 346 # Whether CONCAT requires >1 arguments 347 SUPPORTS_SINGLE_ARG_CONCAT = True 348 349 # Whether LAST_DAY function supports a date part argument 350 LAST_DAY_SUPPORTS_DATE_PART = True 351 352 # Whether named columns are allowed in table aliases 353 SUPPORTS_TABLE_ALIAS_COLUMNS = True 354 355 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 356 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 357 358 # What delimiter to use for separating JSON key/value pairs 359 JSON_KEY_VALUE_PAIR_SEP = ":" 360 361 # INSERT OVERWRITE TABLE x override 362 INSERT_OVERWRITE = " OVERWRITE TABLE" 363 364 # Whether the SELECT .. INTO syntax is used instead of CTAS 365 SUPPORTS_SELECT_INTO = False 366 367 # Whether UNLOGGED tables can be created 368 SUPPORTS_UNLOGGED_TABLES = False 369 370 # Whether the CREATE TABLE LIKE statement is supported 371 SUPPORTS_CREATE_TABLE_LIKE = True 372 373 # Whether the LikeProperty needs to be specified inside of the schema clause 374 LIKE_PROPERTY_INSIDE_SCHEMA = False 375 376 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 377 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 378 MULTI_ARG_DISTINCT = True 379 380 # Whether the JSON extraction operators expect a value of type JSON 381 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 382 383 # Whether bracketed keys like ["foo"] are supported in JSON paths 384 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 385 386 # Whether to escape keys using single quotes in JSON paths 387 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 388 389 # The JSONPathPart expressions supported by this dialect 390 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 391 392 # Whether any(f(x) for x in array) can be implemented by this dialect 393 CAN_IMPLEMENT_ARRAY_ANY = False 394 395 # Whether the function TO_NUMBER is supported 396 SUPPORTS_TO_NUMBER = True 397 398 # Whether or not set op modifiers apply to the outer set op or select. 399 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 400 # True means limit 1 happens after the set op, False means it it happens on y. 401 SET_OP_MODIFIERS = True 402 403 # Whether parameters from COPY statement are wrapped in parentheses 404 COPY_PARAMS_ARE_WRAPPED = True 405 406 # Whether values of params are set with "=" token or empty space 407 COPY_PARAMS_EQ_REQUIRED = False 408 409 # Whether COPY statement has INTO keyword 410 COPY_HAS_INTO_KEYWORD = True 411 412 # Whether the conditional TRY(expression) function is supported 413 TRY_SUPPORTED = True 414 415 # Whether the UESCAPE syntax in unicode strings is supported 416 SUPPORTS_UESCAPE = True 417 418 # The keyword to use when generating a star projection with excluded columns 419 STAR_EXCEPT = "EXCEPT" 420 421 # The HEX function name 422 HEX_FUNC = "HEX" 423 424 # The keywords to use when prefixing & separating WITH based properties 425 WITH_PROPERTIES_PREFIX = "WITH" 426 427 # Whether to quote the generated expression of exp.JsonPath 428 QUOTE_JSON_PATH = True 429 430 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 431 PAD_FILL_PATTERN_IS_REQUIRED = False 432 433 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 434 SUPPORTS_EXPLODING_PROJECTIONS = True 435 436 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 437 ARRAY_CONCAT_IS_VAR_LEN = True 438 439 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 440 SUPPORTS_CONVERT_TIMEZONE = False 441 442 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 443 SUPPORTS_MEDIAN = True 444 445 # Whether UNIX_SECONDS(timestamp) is supported 446 SUPPORTS_UNIX_SECONDS = False 447 448 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 449 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 450 451 # The function name of the exp.ArraySize expression 452 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 453 454 # The syntax to use when altering the type of a column 455 ALTER_SET_TYPE = "SET DATA TYPE" 456 457 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 458 # None -> Doesn't support it at all 459 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 460 # True (Postgres) -> Explicitly requires it 461 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 462 463 TYPE_MAPPING = { 464 exp.DataType.Type.DATETIME2: "TIMESTAMP", 465 exp.DataType.Type.NCHAR: "CHAR", 466 exp.DataType.Type.NVARCHAR: "VARCHAR", 467 exp.DataType.Type.MEDIUMTEXT: "TEXT", 468 exp.DataType.Type.LONGTEXT: "TEXT", 469 exp.DataType.Type.TINYTEXT: "TEXT", 470 exp.DataType.Type.MEDIUMBLOB: "BLOB", 471 exp.DataType.Type.LONGBLOB: "BLOB", 472 exp.DataType.Type.TINYBLOB: "BLOB", 473 exp.DataType.Type.INET: "INET", 474 exp.DataType.Type.ROWVERSION: "VARBINARY", 475 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 476 } 477 478 TIME_PART_SINGULARS = { 479 "MICROSECONDS": "MICROSECOND", 480 "SECONDS": "SECOND", 481 "MINUTES": "MINUTE", 482 "HOURS": "HOUR", 483 "DAYS": "DAY", 484 "WEEKS": "WEEK", 485 "MONTHS": "MONTH", 486 "QUARTERS": "QUARTER", 487 "YEARS": "YEAR", 488 } 489 490 AFTER_HAVING_MODIFIER_TRANSFORMS = { 491 "cluster": lambda self, e: self.sql(e, "cluster"), 492 "distribute": lambda self, e: self.sql(e, "distribute"), 493 "sort": lambda self, e: self.sql(e, "sort"), 494 "windows": lambda self, e: ( 495 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 496 if e.args.get("windows") 497 else "" 498 ), 499 "qualify": lambda self, e: self.sql(e, "qualify"), 500 } 501 502 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 503 504 STRUCT_DELIMITER = ("<", ">") 505 506 PARAMETER_TOKEN = "@" 507 NAMED_PLACEHOLDER_TOKEN = ":" 508 509 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 510 511 PROPERTIES_LOCATION = { 512 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 513 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 514 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 515 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 518 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 520 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 523 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 527 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 529 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 530 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 532 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 536 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 539 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 540 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 541 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 542 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 543 exp.HeapProperty: exp.Properties.Location.POST_WITH, 544 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 546 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 547 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 549 exp.JournalProperty: exp.Properties.Location.POST_NAME, 550 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 555 exp.LogProperty: exp.Properties.Location.POST_NAME, 556 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 557 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 558 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 559 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 560 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 561 exp.Order: exp.Properties.Location.POST_SCHEMA, 562 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 563 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 564 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 565 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 566 exp.Property: exp.Properties.Location.POST_WITH, 567 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 575 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 577 exp.Set: exp.Properties.Location.POST_SCHEMA, 578 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 579 exp.SetProperty: exp.Properties.Location.POST_CREATE, 580 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 581 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 582 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 583 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 584 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 585 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 586 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 588 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.Tags: exp.Properties.Location.POST_WITH, 590 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 591 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 593 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 594 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 595 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 596 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 597 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 598 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 599 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 600 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 601 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 602 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 603 } 604 605 # Keywords that can't be used as unquoted identifier names 606 RESERVED_KEYWORDS: t.Set[str] = set() 607 608 # Expressions whose comments are separated from them for better formatting 609 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 610 exp.Command, 611 exp.Create, 612 exp.Describe, 613 exp.Delete, 614 exp.Drop, 615 exp.From, 616 exp.Insert, 617 exp.Join, 618 exp.MultitableInserts, 619 exp.Select, 620 exp.SetOperation, 621 exp.Update, 622 exp.Where, 623 exp.With, 624 ) 625 626 # Expressions that should not have their comments generated in maybe_comment 627 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 628 exp.Binary, 629 exp.SetOperation, 630 ) 631 632 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 633 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 634 exp.Column, 635 exp.Literal, 636 exp.Neg, 637 exp.Paren, 638 ) 639 640 PARAMETERIZABLE_TEXT_TYPES = { 641 exp.DataType.Type.NVARCHAR, 642 exp.DataType.Type.VARCHAR, 643 exp.DataType.Type.CHAR, 644 exp.DataType.Type.NCHAR, 645 } 646 647 # Expressions that need to have all CTEs under them bubbled up to them 648 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 649 650 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 651 652 __slots__ = ( 653 "pretty", 654 "identify", 655 "normalize", 656 "pad", 657 "_indent", 658 "normalize_functions", 659 "unsupported_level", 660 "max_unsupported", 661 "leading_comma", 662 "max_text_width", 663 "comments", 664 "dialect", 665 "unsupported_messages", 666 "_escaped_quote_end", 667 "_escaped_identifier_end", 668 "_next_name", 669 "_identifier_start", 670 "_identifier_end", 671 "_quote_json_path_key_using_brackets", 672 ) 673 674 def __init__( 675 self, 676 pretty: t.Optional[bool] = None, 677 identify: str | bool = False, 678 normalize: bool = False, 679 pad: int = 2, 680 indent: int = 2, 681 normalize_functions: t.Optional[str | bool] = None, 682 unsupported_level: ErrorLevel = ErrorLevel.WARN, 683 max_unsupported: int = 3, 684 leading_comma: bool = False, 685 max_text_width: int = 80, 686 comments: bool = True, 687 dialect: DialectType = None, 688 ): 689 import sqlglot 690 from sqlglot.dialects import Dialect 691 692 self.pretty = pretty if pretty is not None else sqlglot.pretty 693 self.identify = identify 694 self.normalize = normalize 695 self.pad = pad 696 self._indent = indent 697 self.unsupported_level = unsupported_level 698 self.max_unsupported = max_unsupported 699 self.leading_comma = leading_comma 700 self.max_text_width = max_text_width 701 self.comments = comments 702 self.dialect = Dialect.get_or_raise(dialect) 703 704 # This is both a Dialect property and a Generator argument, so we prioritize the latter 705 self.normalize_functions = ( 706 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 707 ) 708 709 self.unsupported_messages: t.List[str] = [] 710 self._escaped_quote_end: str = ( 711 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 712 ) 713 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 714 715 self._next_name = name_sequence("_t") 716 717 self._identifier_start = self.dialect.IDENTIFIER_START 718 self._identifier_end = self.dialect.IDENTIFIER_END 719 720 self._quote_json_path_key_using_brackets = True 721 722 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 723 """ 724 Generates the SQL string corresponding to the given syntax tree. 725 726 Args: 727 expression: The syntax tree. 728 copy: Whether to copy the expression. The generator performs mutations so 729 it is safer to copy. 730 731 Returns: 732 The SQL string corresponding to `expression`. 733 """ 734 if copy: 735 expression = expression.copy() 736 737 expression = self.preprocess(expression) 738 739 self.unsupported_messages = [] 740 sql = self.sql(expression).strip() 741 742 if self.pretty: 743 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 744 745 if self.unsupported_level == ErrorLevel.IGNORE: 746 return sql 747 748 if self.unsupported_level == ErrorLevel.WARN: 749 for msg in self.unsupported_messages: 750 logger.warning(msg) 751 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 752 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 753 754 return sql 755 756 def preprocess(self, expression: exp.Expression) -> exp.Expression: 757 """Apply generic preprocessing transformations to a given expression.""" 758 expression = self._move_ctes_to_top_level(expression) 759 760 if self.ENSURE_BOOLS: 761 from sqlglot.transforms import ensure_bools 762 763 expression = ensure_bools(expression) 764 765 return expression 766 767 def _move_ctes_to_top_level(self, expression: E) -> E: 768 if ( 769 not expression.parent 770 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 771 and any(node.parent is not expression for node in expression.find_all(exp.With)) 772 ): 773 from sqlglot.transforms import move_ctes_to_top_level 774 775 expression = move_ctes_to_top_level(expression) 776 return expression 777 778 def unsupported(self, message: str) -> None: 779 if self.unsupported_level == ErrorLevel.IMMEDIATE: 780 raise UnsupportedError(message) 781 self.unsupported_messages.append(message) 782 783 def sep(self, sep: str = " ") -> str: 784 return f"{sep.strip()}\n" if self.pretty else sep 785 786 def seg(self, sql: str, sep: str = " ") -> str: 787 return f"{self.sep(sep)}{sql}" 788 789 def pad_comment(self, comment: str) -> str: 790 comment = " " + comment if comment[0].strip() else comment 791 comment = comment + " " if comment[-1].strip() else comment 792 return comment 793 794 def maybe_comment( 795 self, 796 sql: str, 797 expression: t.Optional[exp.Expression] = None, 798 comments: t.Optional[t.List[str]] = None, 799 separated: bool = False, 800 ) -> str: 801 comments = ( 802 ((expression and expression.comments) if comments is None else comments) # type: ignore 803 if self.comments 804 else None 805 ) 806 807 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 808 return sql 809 810 comments_sql = " ".join( 811 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 812 ) 813 814 if not comments_sql: 815 return sql 816 817 comments_sql = self._replace_line_breaks(comments_sql) 818 819 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 820 return ( 821 f"{self.sep()}{comments_sql}{sql}" 822 if not sql or sql[0].isspace() 823 else f"{comments_sql}{self.sep()}{sql}" 824 ) 825 826 return f"{sql} {comments_sql}" 827 828 def wrap(self, expression: exp.Expression | str) -> str: 829 this_sql = ( 830 self.sql(expression) 831 if isinstance(expression, exp.UNWRAPPED_QUERIES) 832 else self.sql(expression, "this") 833 ) 834 if not this_sql: 835 return "()" 836 837 this_sql = self.indent(this_sql, level=1, pad=0) 838 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 839 840 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 841 original = self.identify 842 self.identify = False 843 result = func(*args, **kwargs) 844 self.identify = original 845 return result 846 847 def normalize_func(self, name: str) -> str: 848 if self.normalize_functions == "upper" or self.normalize_functions is True: 849 return name.upper() 850 if self.normalize_functions == "lower": 851 return name.lower() 852 return name 853 854 def indent( 855 self, 856 sql: str, 857 level: int = 0, 858 pad: t.Optional[int] = None, 859 skip_first: bool = False, 860 skip_last: bool = False, 861 ) -> str: 862 if not self.pretty or not sql: 863 return sql 864 865 pad = self.pad if pad is None else pad 866 lines = sql.split("\n") 867 868 return "\n".join( 869 ( 870 line 871 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 872 else f"{' ' * (level * self._indent + pad)}{line}" 873 ) 874 for i, line in enumerate(lines) 875 ) 876 877 def sql( 878 self, 879 expression: t.Optional[str | exp.Expression], 880 key: t.Optional[str] = None, 881 comment: bool = True, 882 ) -> str: 883 if not expression: 884 return "" 885 886 if isinstance(expression, str): 887 return expression 888 889 if key: 890 value = expression.args.get(key) 891 if value: 892 return self.sql(value) 893 return "" 894 895 transform = self.TRANSFORMS.get(expression.__class__) 896 897 if callable(transform): 898 sql = transform(self, expression) 899 elif isinstance(expression, exp.Expression): 900 exp_handler_name = f"{expression.key}_sql" 901 902 if hasattr(self, exp_handler_name): 903 sql = getattr(self, exp_handler_name)(expression) 904 elif isinstance(expression, exp.Func): 905 sql = self.function_fallback_sql(expression) 906 elif isinstance(expression, exp.Property): 907 sql = self.property_sql(expression) 908 else: 909 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 910 else: 911 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 912 913 return self.maybe_comment(sql, expression) if self.comments and comment else sql 914 915 def uncache_sql(self, expression: exp.Uncache) -> str: 916 table = self.sql(expression, "this") 917 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 918 return f"UNCACHE TABLE{exists_sql} {table}" 919 920 def cache_sql(self, expression: exp.Cache) -> str: 921 lazy = " LAZY" if expression.args.get("lazy") else "" 922 table = self.sql(expression, "this") 923 options = expression.args.get("options") 924 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 925 sql = self.sql(expression, "expression") 926 sql = f" AS{self.sep()}{sql}" if sql else "" 927 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 928 return self.prepend_ctes(expression, sql) 929 930 def characterset_sql(self, expression: exp.CharacterSet) -> str: 931 if isinstance(expression.parent, exp.Cast): 932 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 933 default = "DEFAULT " if expression.args.get("default") else "" 934 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 935 936 def column_parts(self, expression: exp.Column) -> str: 937 return ".".join( 938 self.sql(part) 939 for part in ( 940 expression.args.get("catalog"), 941 expression.args.get("db"), 942 expression.args.get("table"), 943 expression.args.get("this"), 944 ) 945 if part 946 ) 947 948 def column_sql(self, expression: exp.Column) -> str: 949 join_mark = " (+)" if expression.args.get("join_mark") else "" 950 951 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 952 join_mark = "" 953 self.unsupported("Outer join syntax using the (+) operator is not supported.") 954 955 return f"{self.column_parts(expression)}{join_mark}" 956 957 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 958 this = self.sql(expression, "this") 959 this = f" {this}" if this else "" 960 position = self.sql(expression, "position") 961 return f"{position}{this}" 962 963 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 964 column = self.sql(expression, "this") 965 kind = self.sql(expression, "kind") 966 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 967 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 968 kind = f"{sep}{kind}" if kind else "" 969 constraints = f" {constraints}" if constraints else "" 970 position = self.sql(expression, "position") 971 position = f" {position}" if position else "" 972 973 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 974 kind = "" 975 976 return f"{exists}{column}{kind}{constraints}{position}" 977 978 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 979 this = self.sql(expression, "this") 980 kind_sql = self.sql(expression, "kind").strip() 981 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 982 983 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 984 this = self.sql(expression, "this") 985 if expression.args.get("not_null"): 986 persisted = " PERSISTED NOT NULL" 987 elif expression.args.get("persisted"): 988 persisted = " PERSISTED" 989 else: 990 persisted = "" 991 return f"AS {this}{persisted}" 992 993 def autoincrementcolumnconstraint_sql(self, _) -> str: 994 return self.token_sql(TokenType.AUTO_INCREMENT) 995 996 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 997 if isinstance(expression.this, list): 998 this = self.wrap(self.expressions(expression, key="this", flat=True)) 999 else: 1000 this = self.sql(expression, "this") 1001 1002 return f"COMPRESS {this}" 1003 1004 def generatedasidentitycolumnconstraint_sql( 1005 self, expression: exp.GeneratedAsIdentityColumnConstraint 1006 ) -> str: 1007 this = "" 1008 if expression.this is not None: 1009 on_null = " ON NULL" if expression.args.get("on_null") else "" 1010 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1011 1012 start = expression.args.get("start") 1013 start = f"START WITH {start}" if start else "" 1014 increment = expression.args.get("increment") 1015 increment = f" INCREMENT BY {increment}" if increment else "" 1016 minvalue = expression.args.get("minvalue") 1017 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1018 maxvalue = expression.args.get("maxvalue") 1019 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1020 cycle = expression.args.get("cycle") 1021 cycle_sql = "" 1022 1023 if cycle is not None: 1024 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1025 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1026 1027 sequence_opts = "" 1028 if start or increment or cycle_sql: 1029 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1030 sequence_opts = f" ({sequence_opts.strip()})" 1031 1032 expr = self.sql(expression, "expression") 1033 expr = f"({expr})" if expr else "IDENTITY" 1034 1035 return f"GENERATED{this} AS {expr}{sequence_opts}" 1036 1037 def generatedasrowcolumnconstraint_sql( 1038 self, expression: exp.GeneratedAsRowColumnConstraint 1039 ) -> str: 1040 start = "START" if expression.args.get("start") else "END" 1041 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1042 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1043 1044 def periodforsystemtimeconstraint_sql( 1045 self, expression: exp.PeriodForSystemTimeConstraint 1046 ) -> str: 1047 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1048 1049 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1050 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1051 1052 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1053 return f"AS {self.sql(expression, 'this')}" 1054 1055 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1056 desc = expression.args.get("desc") 1057 if desc is not None: 1058 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1059 return "PRIMARY KEY" 1060 1061 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1062 this = self.sql(expression, "this") 1063 this = f" {this}" if this else "" 1064 index_type = expression.args.get("index_type") 1065 index_type = f" USING {index_type}" if index_type else "" 1066 on_conflict = self.sql(expression, "on_conflict") 1067 on_conflict = f" {on_conflict}" if on_conflict else "" 1068 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1069 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1070 1071 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1072 return self.sql(expression, "this") 1073 1074 def create_sql(self, expression: exp.Create) -> str: 1075 kind = self.sql(expression, "kind") 1076 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1077 properties = expression.args.get("properties") 1078 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1079 1080 this = self.createable_sql(expression, properties_locs) 1081 1082 properties_sql = "" 1083 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1084 exp.Properties.Location.POST_WITH 1085 ): 1086 properties_sql = self.sql( 1087 exp.Properties( 1088 expressions=[ 1089 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1090 *properties_locs[exp.Properties.Location.POST_WITH], 1091 ] 1092 ) 1093 ) 1094 1095 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1096 properties_sql = self.sep() + properties_sql 1097 elif not self.pretty: 1098 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1099 properties_sql = f" {properties_sql}" 1100 1101 begin = " BEGIN" if expression.args.get("begin") else "" 1102 end = " END" if expression.args.get("end") else "" 1103 1104 expression_sql = self.sql(expression, "expression") 1105 if expression_sql: 1106 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1107 1108 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1109 postalias_props_sql = "" 1110 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1111 postalias_props_sql = self.properties( 1112 exp.Properties( 1113 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1114 ), 1115 wrapped=False, 1116 ) 1117 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1118 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1119 1120 postindex_props_sql = "" 1121 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1122 postindex_props_sql = self.properties( 1123 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1124 wrapped=False, 1125 prefix=" ", 1126 ) 1127 1128 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1129 indexes = f" {indexes}" if indexes else "" 1130 index_sql = indexes + postindex_props_sql 1131 1132 replace = " OR REPLACE" if expression.args.get("replace") else "" 1133 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1134 unique = " UNIQUE" if expression.args.get("unique") else "" 1135 1136 clustered = expression.args.get("clustered") 1137 if clustered is None: 1138 clustered_sql = "" 1139 elif clustered: 1140 clustered_sql = " CLUSTERED COLUMNSTORE" 1141 else: 1142 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1143 1144 postcreate_props_sql = "" 1145 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1146 postcreate_props_sql = self.properties( 1147 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1148 sep=" ", 1149 prefix=" ", 1150 wrapped=False, 1151 ) 1152 1153 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1154 1155 postexpression_props_sql = "" 1156 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1157 postexpression_props_sql = self.properties( 1158 exp.Properties( 1159 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1160 ), 1161 sep=" ", 1162 prefix=" ", 1163 wrapped=False, 1164 ) 1165 1166 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1167 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1168 no_schema_binding = ( 1169 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1170 ) 1171 1172 clone = self.sql(expression, "clone") 1173 clone = f" {clone}" if clone else "" 1174 1175 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1176 properties_expression = f"{expression_sql}{properties_sql}" 1177 else: 1178 properties_expression = f"{properties_sql}{expression_sql}" 1179 1180 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1181 return self.prepend_ctes(expression, expression_sql) 1182 1183 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1184 start = self.sql(expression, "start") 1185 start = f"START WITH {start}" if start else "" 1186 increment = self.sql(expression, "increment") 1187 increment = f" INCREMENT BY {increment}" if increment else "" 1188 minvalue = self.sql(expression, "minvalue") 1189 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1190 maxvalue = self.sql(expression, "maxvalue") 1191 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1192 owned = self.sql(expression, "owned") 1193 owned = f" OWNED BY {owned}" if owned else "" 1194 1195 cache = expression.args.get("cache") 1196 if cache is None: 1197 cache_str = "" 1198 elif cache is True: 1199 cache_str = " CACHE" 1200 else: 1201 cache_str = f" CACHE {cache}" 1202 1203 options = self.expressions(expression, key="options", flat=True, sep=" ") 1204 options = f" {options}" if options else "" 1205 1206 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1207 1208 def clone_sql(self, expression: exp.Clone) -> str: 1209 this = self.sql(expression, "this") 1210 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1211 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1212 return f"{shallow}{keyword} {this}" 1213 1214 def describe_sql(self, expression: exp.Describe) -> str: 1215 style = expression.args.get("style") 1216 style = f" {style}" if style else "" 1217 partition = self.sql(expression, "partition") 1218 partition = f" {partition}" if partition else "" 1219 format = self.sql(expression, "format") 1220 format = f" {format}" if format else "" 1221 1222 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1223 1224 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1225 tag = self.sql(expression, "tag") 1226 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1227 1228 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1229 with_ = self.sql(expression, "with") 1230 if with_: 1231 sql = f"{with_}{self.sep()}{sql}" 1232 return sql 1233 1234 def with_sql(self, expression: exp.With) -> str: 1235 sql = self.expressions(expression, flat=True) 1236 recursive = ( 1237 "RECURSIVE " 1238 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1239 else "" 1240 ) 1241 search = self.sql(expression, "search") 1242 search = f" {search}" if search else "" 1243 1244 return f"WITH {recursive}{sql}{search}" 1245 1246 def cte_sql(self, expression: exp.CTE) -> str: 1247 alias = expression.args.get("alias") 1248 if alias: 1249 alias.add_comments(expression.pop_comments()) 1250 1251 alias_sql = self.sql(expression, "alias") 1252 1253 materialized = expression.args.get("materialized") 1254 if materialized is False: 1255 materialized = "NOT MATERIALIZED " 1256 elif materialized: 1257 materialized = "MATERIALIZED " 1258 1259 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1260 1261 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1262 alias = self.sql(expression, "this") 1263 columns = self.expressions(expression, key="columns", flat=True) 1264 columns = f"({columns})" if columns else "" 1265 1266 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1267 columns = "" 1268 self.unsupported("Named columns are not supported in table alias.") 1269 1270 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1271 alias = self._next_name() 1272 1273 return f"{alias}{columns}" 1274 1275 def bitstring_sql(self, expression: exp.BitString) -> str: 1276 this = self.sql(expression, "this") 1277 if self.dialect.BIT_START: 1278 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1279 return f"{int(this, 2)}" 1280 1281 def hexstring_sql( 1282 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1283 ) -> str: 1284 this = self.sql(expression, "this") 1285 is_integer_type = expression.args.get("is_integer") 1286 1287 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1288 not self.dialect.HEX_START and not binary_function_repr 1289 ): 1290 # Integer representation will be returned if: 1291 # - The read dialect treats the hex value as integer literal but not the write 1292 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1293 return f"{int(this, 16)}" 1294 1295 if not is_integer_type: 1296 # Read dialect treats the hex value as BINARY/BLOB 1297 if binary_function_repr: 1298 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1299 return self.func(binary_function_repr, exp.Literal.string(this)) 1300 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1301 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1302 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1303 1304 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1305 1306 def bytestring_sql(self, expression: exp.ByteString) -> str: 1307 this = self.sql(expression, "this") 1308 if self.dialect.BYTE_START: 1309 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1310 return this 1311 1312 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1313 this = self.sql(expression, "this") 1314 escape = expression.args.get("escape") 1315 1316 if self.dialect.UNICODE_START: 1317 escape_substitute = r"\\\1" 1318 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1319 else: 1320 escape_substitute = r"\\u\1" 1321 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1322 1323 if escape: 1324 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1325 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1326 else: 1327 escape_pattern = ESCAPED_UNICODE_RE 1328 escape_sql = "" 1329 1330 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1331 this = escape_pattern.sub(escape_substitute, this) 1332 1333 return f"{left_quote}{this}{right_quote}{escape_sql}" 1334 1335 def rawstring_sql(self, expression: exp.RawString) -> str: 1336 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1337 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1338 1339 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1340 this = self.sql(expression, "this") 1341 specifier = self.sql(expression, "expression") 1342 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1343 return f"{this}{specifier}" 1344 1345 def datatype_sql(self, expression: exp.DataType) -> str: 1346 nested = "" 1347 values = "" 1348 interior = self.expressions(expression, flat=True) 1349 1350 type_value = expression.this 1351 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1352 type_sql = self.sql(expression, "kind") 1353 else: 1354 type_sql = ( 1355 self.TYPE_MAPPING.get(type_value, type_value.value) 1356 if isinstance(type_value, exp.DataType.Type) 1357 else type_value 1358 ) 1359 1360 if interior: 1361 if expression.args.get("nested"): 1362 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1363 if expression.args.get("values") is not None: 1364 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1365 values = self.expressions(expression, key="values", flat=True) 1366 values = f"{delimiters[0]}{values}{delimiters[1]}" 1367 elif type_value == exp.DataType.Type.INTERVAL: 1368 nested = f" {interior}" 1369 else: 1370 nested = f"({interior})" 1371 1372 type_sql = f"{type_sql}{nested}{values}" 1373 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1374 exp.DataType.Type.TIMETZ, 1375 exp.DataType.Type.TIMESTAMPTZ, 1376 ): 1377 type_sql = f"{type_sql} WITH TIME ZONE" 1378 1379 return type_sql 1380 1381 def directory_sql(self, expression: exp.Directory) -> str: 1382 local = "LOCAL " if expression.args.get("local") else "" 1383 row_format = self.sql(expression, "row_format") 1384 row_format = f" {row_format}" if row_format else "" 1385 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1386 1387 def delete_sql(self, expression: exp.Delete) -> str: 1388 this = self.sql(expression, "this") 1389 this = f" FROM {this}" if this else "" 1390 using = self.sql(expression, "using") 1391 using = f" USING {using}" if using else "" 1392 cluster = self.sql(expression, "cluster") 1393 cluster = f" {cluster}" if cluster else "" 1394 where = self.sql(expression, "where") 1395 returning = self.sql(expression, "returning") 1396 limit = self.sql(expression, "limit") 1397 tables = self.expressions(expression, key="tables") 1398 tables = f" {tables}" if tables else "" 1399 if self.RETURNING_END: 1400 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1401 else: 1402 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1403 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1404 1405 def drop_sql(self, expression: exp.Drop) -> str: 1406 this = self.sql(expression, "this") 1407 expressions = self.expressions(expression, flat=True) 1408 expressions = f" ({expressions})" if expressions else "" 1409 kind = expression.args["kind"] 1410 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1411 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1412 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1413 on_cluster = self.sql(expression, "cluster") 1414 on_cluster = f" {on_cluster}" if on_cluster else "" 1415 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1416 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1417 cascade = " CASCADE" if expression.args.get("cascade") else "" 1418 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1419 purge = " PURGE" if expression.args.get("purge") else "" 1420 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1421 1422 def set_operation(self, expression: exp.SetOperation) -> str: 1423 op_type = type(expression) 1424 op_name = op_type.key.upper() 1425 1426 distinct = expression.args.get("distinct") 1427 if ( 1428 distinct is False 1429 and op_type in (exp.Except, exp.Intersect) 1430 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1431 ): 1432 self.unsupported(f"{op_name} ALL is not supported") 1433 1434 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1435 1436 if distinct is None: 1437 distinct = default_distinct 1438 if distinct is None: 1439 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1440 1441 if distinct is default_distinct: 1442 kind = "" 1443 else: 1444 kind = " DISTINCT" if distinct else " ALL" 1445 1446 by_name = " BY NAME" if expression.args.get("by_name") else "" 1447 return f"{op_name}{kind}{by_name}" 1448 1449 def set_operations(self, expression: exp.SetOperation) -> str: 1450 if not self.SET_OP_MODIFIERS: 1451 limit = expression.args.get("limit") 1452 order = expression.args.get("order") 1453 1454 if limit or order: 1455 select = self._move_ctes_to_top_level( 1456 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1457 ) 1458 1459 if limit: 1460 select = select.limit(limit.pop(), copy=False) 1461 if order: 1462 select = select.order_by(order.pop(), copy=False) 1463 return self.sql(select) 1464 1465 sqls: t.List[str] = [] 1466 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1467 1468 while stack: 1469 node = stack.pop() 1470 1471 if isinstance(node, exp.SetOperation): 1472 stack.append(node.expression) 1473 stack.append( 1474 self.maybe_comment( 1475 self.set_operation(node), comments=node.comments, separated=True 1476 ) 1477 ) 1478 stack.append(node.this) 1479 else: 1480 sqls.append(self.sql(node)) 1481 1482 this = self.sep().join(sqls) 1483 this = self.query_modifiers(expression, this) 1484 return self.prepend_ctes(expression, this) 1485 1486 def fetch_sql(self, expression: exp.Fetch) -> str: 1487 direction = expression.args.get("direction") 1488 direction = f" {direction}" if direction else "" 1489 count = self.sql(expression, "count") 1490 count = f" {count}" if count else "" 1491 limit_options = self.sql(expression, "limit_options") 1492 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1493 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1494 1495 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1496 percent = " PERCENT" if expression.args.get("percent") else "" 1497 rows = " ROWS" if expression.args.get("rows") else "" 1498 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1499 if not with_ties and rows: 1500 with_ties = " ONLY" 1501 return f"{percent}{rows}{with_ties}" 1502 1503 def filter_sql(self, expression: exp.Filter) -> str: 1504 if self.AGGREGATE_FILTER_SUPPORTED: 1505 this = self.sql(expression, "this") 1506 where = self.sql(expression, "expression").strip() 1507 return f"{this} FILTER({where})" 1508 1509 agg = expression.this 1510 agg_arg = agg.this 1511 cond = expression.expression.this 1512 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1513 return self.sql(agg) 1514 1515 def hint_sql(self, expression: exp.Hint) -> str: 1516 if not self.QUERY_HINTS: 1517 self.unsupported("Hints are not supported") 1518 return "" 1519 1520 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1521 1522 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1523 using = self.sql(expression, "using") 1524 using = f" USING {using}" if using else "" 1525 columns = self.expressions(expression, key="columns", flat=True) 1526 columns = f"({columns})" if columns else "" 1527 partition_by = self.expressions(expression, key="partition_by", flat=True) 1528 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1529 where = self.sql(expression, "where") 1530 include = self.expressions(expression, key="include", flat=True) 1531 if include: 1532 include = f" INCLUDE ({include})" 1533 with_storage = self.expressions(expression, key="with_storage", flat=True) 1534 with_storage = f" WITH ({with_storage})" if with_storage else "" 1535 tablespace = self.sql(expression, "tablespace") 1536 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1537 on = self.sql(expression, "on") 1538 on = f" ON {on}" if on else "" 1539 1540 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1541 1542 def index_sql(self, expression: exp.Index) -> str: 1543 unique = "UNIQUE " if expression.args.get("unique") else "" 1544 primary = "PRIMARY " if expression.args.get("primary") else "" 1545 amp = "AMP " if expression.args.get("amp") else "" 1546 name = self.sql(expression, "this") 1547 name = f"{name} " if name else "" 1548 table = self.sql(expression, "table") 1549 table = f"{self.INDEX_ON} {table}" if table else "" 1550 1551 index = "INDEX " if not table else "" 1552 1553 params = self.sql(expression, "params") 1554 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1555 1556 def identifier_sql(self, expression: exp.Identifier) -> str: 1557 text = expression.name 1558 lower = text.lower() 1559 text = lower if self.normalize and not expression.quoted else text 1560 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1561 if ( 1562 expression.quoted 1563 or self.dialect.can_identify(text, self.identify) 1564 or lower in self.RESERVED_KEYWORDS 1565 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1566 ): 1567 text = f"{self._identifier_start}{text}{self._identifier_end}" 1568 return text 1569 1570 def hex_sql(self, expression: exp.Hex) -> str: 1571 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1572 if self.dialect.HEX_LOWERCASE: 1573 text = self.func("LOWER", text) 1574 1575 return text 1576 1577 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1578 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1579 if not self.dialect.HEX_LOWERCASE: 1580 text = self.func("LOWER", text) 1581 return text 1582 1583 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1584 input_format = self.sql(expression, "input_format") 1585 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1586 output_format = self.sql(expression, "output_format") 1587 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1588 return self.sep().join((input_format, output_format)) 1589 1590 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1591 string = self.sql(exp.Literal.string(expression.name)) 1592 return f"{prefix}{string}" 1593 1594 def partition_sql(self, expression: exp.Partition) -> str: 1595 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1596 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1597 1598 def properties_sql(self, expression: exp.Properties) -> str: 1599 root_properties = [] 1600 with_properties = [] 1601 1602 for p in expression.expressions: 1603 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1604 if p_loc == exp.Properties.Location.POST_WITH: 1605 with_properties.append(p) 1606 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1607 root_properties.append(p) 1608 1609 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1610 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1611 1612 if root_props and with_props and not self.pretty: 1613 with_props = " " + with_props 1614 1615 return root_props + with_props 1616 1617 def root_properties(self, properties: exp.Properties) -> str: 1618 if properties.expressions: 1619 return self.expressions(properties, indent=False, sep=" ") 1620 return "" 1621 1622 def properties( 1623 self, 1624 properties: exp.Properties, 1625 prefix: str = "", 1626 sep: str = ", ", 1627 suffix: str = "", 1628 wrapped: bool = True, 1629 ) -> str: 1630 if properties.expressions: 1631 expressions = self.expressions(properties, sep=sep, indent=False) 1632 if expressions: 1633 expressions = self.wrap(expressions) if wrapped else expressions 1634 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1635 return "" 1636 1637 def with_properties(self, properties: exp.Properties) -> str: 1638 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1639 1640 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1641 properties_locs = defaultdict(list) 1642 for p in properties.expressions: 1643 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1644 if p_loc != exp.Properties.Location.UNSUPPORTED: 1645 properties_locs[p_loc].append(p) 1646 else: 1647 self.unsupported(f"Unsupported property {p.key}") 1648 1649 return properties_locs 1650 1651 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1652 if isinstance(expression.this, exp.Dot): 1653 return self.sql(expression, "this") 1654 return f"'{expression.name}'" if string_key else expression.name 1655 1656 def property_sql(self, expression: exp.Property) -> str: 1657 property_cls = expression.__class__ 1658 if property_cls == exp.Property: 1659 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1660 1661 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1662 if not property_name: 1663 self.unsupported(f"Unsupported property {expression.key}") 1664 1665 return f"{property_name}={self.sql(expression, 'this')}" 1666 1667 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1668 if self.SUPPORTS_CREATE_TABLE_LIKE: 1669 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1670 options = f" {options}" if options else "" 1671 1672 like = f"LIKE {self.sql(expression, 'this')}{options}" 1673 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1674 like = f"({like})" 1675 1676 return like 1677 1678 if expression.expressions: 1679 self.unsupported("Transpilation of LIKE property options is unsupported") 1680 1681 select = exp.select("*").from_(expression.this).limit(0) 1682 return f"AS {self.sql(select)}" 1683 1684 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1685 no = "NO " if expression.args.get("no") else "" 1686 protection = " PROTECTION" if expression.args.get("protection") else "" 1687 return f"{no}FALLBACK{protection}" 1688 1689 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1690 no = "NO " if expression.args.get("no") else "" 1691 local = expression.args.get("local") 1692 local = f"{local} " if local else "" 1693 dual = "DUAL " if expression.args.get("dual") else "" 1694 before = "BEFORE " if expression.args.get("before") else "" 1695 after = "AFTER " if expression.args.get("after") else "" 1696 return f"{no}{local}{dual}{before}{after}JOURNAL" 1697 1698 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1699 freespace = self.sql(expression, "this") 1700 percent = " PERCENT" if expression.args.get("percent") else "" 1701 return f"FREESPACE={freespace}{percent}" 1702 1703 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1704 if expression.args.get("default"): 1705 property = "DEFAULT" 1706 elif expression.args.get("on"): 1707 property = "ON" 1708 else: 1709 property = "OFF" 1710 return f"CHECKSUM={property}" 1711 1712 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1713 if expression.args.get("no"): 1714 return "NO MERGEBLOCKRATIO" 1715 if expression.args.get("default"): 1716 return "DEFAULT MERGEBLOCKRATIO" 1717 1718 percent = " PERCENT" if expression.args.get("percent") else "" 1719 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1720 1721 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1722 default = expression.args.get("default") 1723 minimum = expression.args.get("minimum") 1724 maximum = expression.args.get("maximum") 1725 if default or minimum or maximum: 1726 if default: 1727 prop = "DEFAULT" 1728 elif minimum: 1729 prop = "MINIMUM" 1730 else: 1731 prop = "MAXIMUM" 1732 return f"{prop} DATABLOCKSIZE" 1733 units = expression.args.get("units") 1734 units = f" {units}" if units else "" 1735 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1736 1737 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1738 autotemp = expression.args.get("autotemp") 1739 always = expression.args.get("always") 1740 default = expression.args.get("default") 1741 manual = expression.args.get("manual") 1742 never = expression.args.get("never") 1743 1744 if autotemp is not None: 1745 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1746 elif always: 1747 prop = "ALWAYS" 1748 elif default: 1749 prop = "DEFAULT" 1750 elif manual: 1751 prop = "MANUAL" 1752 elif never: 1753 prop = "NEVER" 1754 return f"BLOCKCOMPRESSION={prop}" 1755 1756 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1757 no = expression.args.get("no") 1758 no = " NO" if no else "" 1759 concurrent = expression.args.get("concurrent") 1760 concurrent = " CONCURRENT" if concurrent else "" 1761 target = self.sql(expression, "target") 1762 target = f" {target}" if target else "" 1763 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1764 1765 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1766 if isinstance(expression.this, list): 1767 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1768 if expression.this: 1769 modulus = self.sql(expression, "this") 1770 remainder = self.sql(expression, "expression") 1771 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1772 1773 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1774 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1775 return f"FROM ({from_expressions}) TO ({to_expressions})" 1776 1777 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1778 this = self.sql(expression, "this") 1779 1780 for_values_or_default = expression.expression 1781 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1782 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1783 else: 1784 for_values_or_default = " DEFAULT" 1785 1786 return f"PARTITION OF {this}{for_values_or_default}" 1787 1788 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1789 kind = expression.args.get("kind") 1790 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1791 for_or_in = expression.args.get("for_or_in") 1792 for_or_in = f" {for_or_in}" if for_or_in else "" 1793 lock_type = expression.args.get("lock_type") 1794 override = " OVERRIDE" if expression.args.get("override") else "" 1795 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1796 1797 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1798 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1799 statistics = expression.args.get("statistics") 1800 statistics_sql = "" 1801 if statistics is not None: 1802 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1803 return f"{data_sql}{statistics_sql}" 1804 1805 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1806 this = self.sql(expression, "this") 1807 this = f"HISTORY_TABLE={this}" if this else "" 1808 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1809 data_consistency = ( 1810 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1811 ) 1812 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1813 retention_period = ( 1814 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1815 ) 1816 1817 if this: 1818 on_sql = self.func("ON", this, data_consistency, retention_period) 1819 else: 1820 on_sql = "ON" if expression.args.get("on") else "OFF" 1821 1822 sql = f"SYSTEM_VERSIONING={on_sql}" 1823 1824 return f"WITH({sql})" if expression.args.get("with") else sql 1825 1826 def insert_sql(self, expression: exp.Insert) -> str: 1827 hint = self.sql(expression, "hint") 1828 overwrite = expression.args.get("overwrite") 1829 1830 if isinstance(expression.this, exp.Directory): 1831 this = " OVERWRITE" if overwrite else " INTO" 1832 else: 1833 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1834 1835 stored = self.sql(expression, "stored") 1836 stored = f" {stored}" if stored else "" 1837 alternative = expression.args.get("alternative") 1838 alternative = f" OR {alternative}" if alternative else "" 1839 ignore = " IGNORE" if expression.args.get("ignore") else "" 1840 is_function = expression.args.get("is_function") 1841 if is_function: 1842 this = f"{this} FUNCTION" 1843 this = f"{this} {self.sql(expression, 'this')}" 1844 1845 exists = " IF EXISTS" if expression.args.get("exists") else "" 1846 where = self.sql(expression, "where") 1847 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1848 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1849 on_conflict = self.sql(expression, "conflict") 1850 on_conflict = f" {on_conflict}" if on_conflict else "" 1851 by_name = " BY NAME" if expression.args.get("by_name") else "" 1852 returning = self.sql(expression, "returning") 1853 1854 if self.RETURNING_END: 1855 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1856 else: 1857 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1858 1859 partition_by = self.sql(expression, "partition") 1860 partition_by = f" {partition_by}" if partition_by else "" 1861 settings = self.sql(expression, "settings") 1862 settings = f" {settings}" if settings else "" 1863 1864 source = self.sql(expression, "source") 1865 source = f"TABLE {source}" if source else "" 1866 1867 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1868 return self.prepend_ctes(expression, sql) 1869 1870 def introducer_sql(self, expression: exp.Introducer) -> str: 1871 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1872 1873 def kill_sql(self, expression: exp.Kill) -> str: 1874 kind = self.sql(expression, "kind") 1875 kind = f" {kind}" if kind else "" 1876 this = self.sql(expression, "this") 1877 this = f" {this}" if this else "" 1878 return f"KILL{kind}{this}" 1879 1880 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1881 return expression.name 1882 1883 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1884 return expression.name 1885 1886 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1887 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1888 1889 constraint = self.sql(expression, "constraint") 1890 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1891 1892 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1893 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1894 action = self.sql(expression, "action") 1895 1896 expressions = self.expressions(expression, flat=True) 1897 if expressions: 1898 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1899 expressions = f" {set_keyword}{expressions}" 1900 1901 where = self.sql(expression, "where") 1902 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1903 1904 def returning_sql(self, expression: exp.Returning) -> str: 1905 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1906 1907 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1908 fields = self.sql(expression, "fields") 1909 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1910 escaped = self.sql(expression, "escaped") 1911 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1912 items = self.sql(expression, "collection_items") 1913 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1914 keys = self.sql(expression, "map_keys") 1915 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1916 lines = self.sql(expression, "lines") 1917 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1918 null = self.sql(expression, "null") 1919 null = f" NULL DEFINED AS {null}" if null else "" 1920 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1921 1922 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1923 return f"WITH ({self.expressions(expression, flat=True)})" 1924 1925 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1926 this = f"{self.sql(expression, 'this')} INDEX" 1927 target = self.sql(expression, "target") 1928 target = f" FOR {target}" if target else "" 1929 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1930 1931 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1932 this = self.sql(expression, "this") 1933 kind = self.sql(expression, "kind") 1934 expr = self.sql(expression, "expression") 1935 return f"{this} ({kind} => {expr})" 1936 1937 def table_parts(self, expression: exp.Table) -> str: 1938 return ".".join( 1939 self.sql(part) 1940 for part in ( 1941 expression.args.get("catalog"), 1942 expression.args.get("db"), 1943 expression.args.get("this"), 1944 ) 1945 if part is not None 1946 ) 1947 1948 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1949 table = self.table_parts(expression) 1950 only = "ONLY " if expression.args.get("only") else "" 1951 partition = self.sql(expression, "partition") 1952 partition = f" {partition}" if partition else "" 1953 version = self.sql(expression, "version") 1954 version = f" {version}" if version else "" 1955 alias = self.sql(expression, "alias") 1956 alias = f"{sep}{alias}" if alias else "" 1957 1958 sample = self.sql(expression, "sample") 1959 if self.dialect.ALIAS_POST_TABLESAMPLE: 1960 sample_pre_alias = sample 1961 sample_post_alias = "" 1962 else: 1963 sample_pre_alias = "" 1964 sample_post_alias = sample 1965 1966 hints = self.expressions(expression, key="hints", sep=" ") 1967 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1968 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1969 joins = self.indent( 1970 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1971 ) 1972 laterals = self.expressions(expression, key="laterals", sep="") 1973 1974 file_format = self.sql(expression, "format") 1975 if file_format: 1976 pattern = self.sql(expression, "pattern") 1977 pattern = f", PATTERN => {pattern}" if pattern else "" 1978 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1979 1980 ordinality = expression.args.get("ordinality") or "" 1981 if ordinality: 1982 ordinality = f" WITH ORDINALITY{alias}" 1983 alias = "" 1984 1985 when = self.sql(expression, "when") 1986 if when: 1987 table = f"{table} {when}" 1988 1989 changes = self.sql(expression, "changes") 1990 changes = f" {changes}" if changes else "" 1991 1992 rows_from = self.expressions(expression, key="rows_from") 1993 if rows_from: 1994 table = f"ROWS FROM {self.wrap(rows_from)}" 1995 1996 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1997 1998 def tablesample_sql( 1999 self, 2000 expression: exp.TableSample, 2001 tablesample_keyword: t.Optional[str] = None, 2002 ) -> str: 2003 method = self.sql(expression, "method") 2004 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2005 numerator = self.sql(expression, "bucket_numerator") 2006 denominator = self.sql(expression, "bucket_denominator") 2007 field = self.sql(expression, "bucket_field") 2008 field = f" ON {field}" if field else "" 2009 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2010 seed = self.sql(expression, "seed") 2011 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2012 2013 size = self.sql(expression, "size") 2014 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2015 size = f"{size} ROWS" 2016 2017 percent = self.sql(expression, "percent") 2018 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2019 percent = f"{percent} PERCENT" 2020 2021 expr = f"{bucket}{percent}{size}" 2022 if self.TABLESAMPLE_REQUIRES_PARENS: 2023 expr = f"({expr})" 2024 2025 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2026 2027 def pivot_sql(self, expression: exp.Pivot) -> str: 2028 expressions = self.expressions(expression, flat=True) 2029 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2030 2031 if expression.this: 2032 this = self.sql(expression, "this") 2033 if not expressions: 2034 return f"UNPIVOT {this}" 2035 2036 on = f"{self.seg('ON')} {expressions}" 2037 into = self.sql(expression, "into") 2038 into = f"{self.seg('INTO')} {into}" if into else "" 2039 using = self.expressions(expression, key="using", flat=True) 2040 using = f"{self.seg('USING')} {using}" if using else "" 2041 group = self.sql(expression, "group") 2042 return f"{direction} {this}{on}{into}{using}{group}" 2043 2044 alias = self.sql(expression, "alias") 2045 alias = f" AS {alias}" if alias else "" 2046 2047 field = self.sql(expression, "field") 2048 2049 include_nulls = expression.args.get("include_nulls") 2050 if include_nulls is not None: 2051 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2052 else: 2053 nulls = "" 2054 2055 default_on_null = self.sql(expression, "default_on_null") 2056 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2057 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2058 2059 def version_sql(self, expression: exp.Version) -> str: 2060 this = f"FOR {expression.name}" 2061 kind = expression.text("kind") 2062 expr = self.sql(expression, "expression") 2063 return f"{this} {kind} {expr}" 2064 2065 def tuple_sql(self, expression: exp.Tuple) -> str: 2066 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2067 2068 def update_sql(self, expression: exp.Update) -> str: 2069 this = self.sql(expression, "this") 2070 set_sql = self.expressions(expression, flat=True) 2071 from_sql = self.sql(expression, "from") 2072 where_sql = self.sql(expression, "where") 2073 returning = self.sql(expression, "returning") 2074 order = self.sql(expression, "order") 2075 limit = self.sql(expression, "limit") 2076 if self.RETURNING_END: 2077 expression_sql = f"{from_sql}{where_sql}{returning}" 2078 else: 2079 expression_sql = f"{returning}{from_sql}{where_sql}" 2080 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2081 return self.prepend_ctes(expression, sql) 2082 2083 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2084 values_as_table = values_as_table and self.VALUES_AS_TABLE 2085 2086 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2087 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2088 args = self.expressions(expression) 2089 alias = self.sql(expression, "alias") 2090 values = f"VALUES{self.seg('')}{args}" 2091 values = ( 2092 f"({values})" 2093 if self.WRAP_DERIVED_VALUES 2094 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2095 else values 2096 ) 2097 return f"{values} AS {alias}" if alias else values 2098 2099 # Converts `VALUES...` expression into a series of select unions. 2100 alias_node = expression.args.get("alias") 2101 column_names = alias_node and alias_node.columns 2102 2103 selects: t.List[exp.Query] = [] 2104 2105 for i, tup in enumerate(expression.expressions): 2106 row = tup.expressions 2107 2108 if i == 0 and column_names: 2109 row = [ 2110 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2111 ] 2112 2113 selects.append(exp.Select(expressions=row)) 2114 2115 if self.pretty: 2116 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2117 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2118 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2119 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2120 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2121 2122 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2123 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2124 return f"({unions}){alias}" 2125 2126 def var_sql(self, expression: exp.Var) -> str: 2127 return self.sql(expression, "this") 2128 2129 @unsupported_args("expressions") 2130 def into_sql(self, expression: exp.Into) -> str: 2131 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2132 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2133 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2134 2135 def from_sql(self, expression: exp.From) -> str: 2136 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2137 2138 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2139 grouping_sets = self.expressions(expression, indent=False) 2140 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2141 2142 def rollup_sql(self, expression: exp.Rollup) -> str: 2143 expressions = self.expressions(expression, indent=False) 2144 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2145 2146 def cube_sql(self, expression: exp.Cube) -> str: 2147 expressions = self.expressions(expression, indent=False) 2148 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2149 2150 def group_sql(self, expression: exp.Group) -> str: 2151 group_by_all = expression.args.get("all") 2152 if group_by_all is True: 2153 modifier = " ALL" 2154 elif group_by_all is False: 2155 modifier = " DISTINCT" 2156 else: 2157 modifier = "" 2158 2159 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2160 2161 grouping_sets = self.expressions(expression, key="grouping_sets") 2162 cube = self.expressions(expression, key="cube") 2163 rollup = self.expressions(expression, key="rollup") 2164 2165 groupings = csv( 2166 self.seg(grouping_sets) if grouping_sets else "", 2167 self.seg(cube) if cube else "", 2168 self.seg(rollup) if rollup else "", 2169 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2170 sep=self.GROUPINGS_SEP, 2171 ) 2172 2173 if ( 2174 expression.expressions 2175 and groupings 2176 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2177 ): 2178 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2179 2180 return f"{group_by}{groupings}" 2181 2182 def having_sql(self, expression: exp.Having) -> str: 2183 this = self.indent(self.sql(expression, "this")) 2184 return f"{self.seg('HAVING')}{self.sep()}{this}" 2185 2186 def connect_sql(self, expression: exp.Connect) -> str: 2187 start = self.sql(expression, "start") 2188 start = self.seg(f"START WITH {start}") if start else "" 2189 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2190 connect = self.sql(expression, "connect") 2191 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2192 return start + connect 2193 2194 def prior_sql(self, expression: exp.Prior) -> str: 2195 return f"PRIOR {self.sql(expression, 'this')}" 2196 2197 def join_sql(self, expression: exp.Join) -> str: 2198 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2199 side = None 2200 else: 2201 side = expression.side 2202 2203 op_sql = " ".join( 2204 op 2205 for op in ( 2206 expression.method, 2207 "GLOBAL" if expression.args.get("global") else None, 2208 side, 2209 expression.kind, 2210 expression.hint if self.JOIN_HINTS else None, 2211 ) 2212 if op 2213 ) 2214 match_cond = self.sql(expression, "match_condition") 2215 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2216 on_sql = self.sql(expression, "on") 2217 using = expression.args.get("using") 2218 2219 if not on_sql and using: 2220 on_sql = csv(*(self.sql(column) for column in using)) 2221 2222 this = expression.this 2223 this_sql = self.sql(this) 2224 2225 exprs = self.expressions(expression) 2226 if exprs: 2227 this_sql = f"{this_sql},{self.seg(exprs)}" 2228 2229 if on_sql: 2230 on_sql = self.indent(on_sql, skip_first=True) 2231 space = self.seg(" " * self.pad) if self.pretty else " " 2232 if using: 2233 on_sql = f"{space}USING ({on_sql})" 2234 else: 2235 on_sql = f"{space}ON {on_sql}" 2236 elif not op_sql: 2237 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2238 return f" {this_sql}" 2239 2240 return f", {this_sql}" 2241 2242 if op_sql != "STRAIGHT_JOIN": 2243 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2244 2245 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2246 2247 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2248 args = self.expressions(expression, flat=True) 2249 args = f"({args})" if len(args.split(",")) > 1 else args 2250 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2251 2252 def lateral_op(self, expression: exp.Lateral) -> str: 2253 cross_apply = expression.args.get("cross_apply") 2254 2255 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2256 if cross_apply is True: 2257 op = "INNER JOIN " 2258 elif cross_apply is False: 2259 op = "LEFT JOIN " 2260 else: 2261 op = "" 2262 2263 return f"{op}LATERAL" 2264 2265 def lateral_sql(self, expression: exp.Lateral) -> str: 2266 this = self.sql(expression, "this") 2267 2268 if expression.args.get("view"): 2269 alias = expression.args["alias"] 2270 columns = self.expressions(alias, key="columns", flat=True) 2271 table = f" {alias.name}" if alias.name else "" 2272 columns = f" AS {columns}" if columns else "" 2273 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2274 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2275 2276 alias = self.sql(expression, "alias") 2277 alias = f" AS {alias}" if alias else "" 2278 return f"{self.lateral_op(expression)} {this}{alias}" 2279 2280 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2281 this = self.sql(expression, "this") 2282 2283 args = [ 2284 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2285 for e in (expression.args.get(k) for k in ("offset", "expression")) 2286 if e 2287 ] 2288 2289 args_sql = ", ".join(self.sql(e) for e in args) 2290 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2291 expressions = self.expressions(expression, flat=True) 2292 limit_options = self.sql(expression, "limit_options") 2293 expressions = f" BY {expressions}" if expressions else "" 2294 2295 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2296 2297 def offset_sql(self, expression: exp.Offset) -> str: 2298 this = self.sql(expression, "this") 2299 value = expression.expression 2300 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2301 expressions = self.expressions(expression, flat=True) 2302 expressions = f" BY {expressions}" if expressions else "" 2303 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2304 2305 def setitem_sql(self, expression: exp.SetItem) -> str: 2306 kind = self.sql(expression, "kind") 2307 kind = f"{kind} " if kind else "" 2308 this = self.sql(expression, "this") 2309 expressions = self.expressions(expression) 2310 collate = self.sql(expression, "collate") 2311 collate = f" COLLATE {collate}" if collate else "" 2312 global_ = "GLOBAL " if expression.args.get("global") else "" 2313 return f"{global_}{kind}{this}{expressions}{collate}" 2314 2315 def set_sql(self, expression: exp.Set) -> str: 2316 expressions = f" {self.expressions(expression, flat=True)}" 2317 tag = " TAG" if expression.args.get("tag") else "" 2318 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2319 2320 def pragma_sql(self, expression: exp.Pragma) -> str: 2321 return f"PRAGMA {self.sql(expression, 'this')}" 2322 2323 def lock_sql(self, expression: exp.Lock) -> str: 2324 if not self.LOCKING_READS_SUPPORTED: 2325 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2326 return "" 2327 2328 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2329 expressions = self.expressions(expression, flat=True) 2330 expressions = f" OF {expressions}" if expressions else "" 2331 wait = expression.args.get("wait") 2332 2333 if wait is not None: 2334 if isinstance(wait, exp.Literal): 2335 wait = f" WAIT {self.sql(wait)}" 2336 else: 2337 wait = " NOWAIT" if wait else " SKIP LOCKED" 2338 2339 return f"{lock_type}{expressions}{wait or ''}" 2340 2341 def literal_sql(self, expression: exp.Literal) -> str: 2342 text = expression.this or "" 2343 if expression.is_string: 2344 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2345 return text 2346 2347 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2348 if self.dialect.ESCAPED_SEQUENCES: 2349 to_escaped = self.dialect.ESCAPED_SEQUENCES 2350 text = "".join( 2351 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2352 ) 2353 2354 return self._replace_line_breaks(text).replace( 2355 self.dialect.QUOTE_END, self._escaped_quote_end 2356 ) 2357 2358 def loaddata_sql(self, expression: exp.LoadData) -> str: 2359 local = " LOCAL" if expression.args.get("local") else "" 2360 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2361 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2362 this = f" INTO TABLE {self.sql(expression, 'this')}" 2363 partition = self.sql(expression, "partition") 2364 partition = f" {partition}" if partition else "" 2365 input_format = self.sql(expression, "input_format") 2366 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2367 serde = self.sql(expression, "serde") 2368 serde = f" SERDE {serde}" if serde else "" 2369 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2370 2371 def null_sql(self, *_) -> str: 2372 return "NULL" 2373 2374 def boolean_sql(self, expression: exp.Boolean) -> str: 2375 return "TRUE" if expression.this else "FALSE" 2376 2377 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2378 this = self.sql(expression, "this") 2379 this = f"{this} " if this else this 2380 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2381 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2382 2383 def withfill_sql(self, expression: exp.WithFill) -> str: 2384 from_sql = self.sql(expression, "from") 2385 from_sql = f" FROM {from_sql}" if from_sql else "" 2386 to_sql = self.sql(expression, "to") 2387 to_sql = f" TO {to_sql}" if to_sql else "" 2388 step_sql = self.sql(expression, "step") 2389 step_sql = f" STEP {step_sql}" if step_sql else "" 2390 interpolated_values = [ 2391 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2392 if isinstance(e, exp.Alias) 2393 else self.sql(e, "this") 2394 for e in expression.args.get("interpolate") or [] 2395 ] 2396 interpolate = ( 2397 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2398 ) 2399 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2400 2401 def cluster_sql(self, expression: exp.Cluster) -> str: 2402 return self.op_expressions("CLUSTER BY", expression) 2403 2404 def distribute_sql(self, expression: exp.Distribute) -> str: 2405 return self.op_expressions("DISTRIBUTE BY", expression) 2406 2407 def sort_sql(self, expression: exp.Sort) -> str: 2408 return self.op_expressions("SORT BY", expression) 2409 2410 def ordered_sql(self, expression: exp.Ordered) -> str: 2411 desc = expression.args.get("desc") 2412 asc = not desc 2413 2414 nulls_first = expression.args.get("nulls_first") 2415 nulls_last = not nulls_first 2416 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2417 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2418 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2419 2420 this = self.sql(expression, "this") 2421 2422 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2423 nulls_sort_change = "" 2424 if nulls_first and ( 2425 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2426 ): 2427 nulls_sort_change = " NULLS FIRST" 2428 elif ( 2429 nulls_last 2430 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2431 and not nulls_are_last 2432 ): 2433 nulls_sort_change = " NULLS LAST" 2434 2435 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2436 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2437 window = expression.find_ancestor(exp.Window, exp.Select) 2438 if isinstance(window, exp.Window) and window.args.get("spec"): 2439 self.unsupported( 2440 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2441 ) 2442 nulls_sort_change = "" 2443 elif self.NULL_ORDERING_SUPPORTED is False and ( 2444 (asc and nulls_sort_change == " NULLS LAST") 2445 or (desc and nulls_sort_change == " NULLS FIRST") 2446 ): 2447 # BigQuery does not allow these ordering/nulls combinations when used under 2448 # an aggregation func or under a window containing one 2449 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2450 2451 if isinstance(ancestor, exp.Window): 2452 ancestor = ancestor.this 2453 if isinstance(ancestor, exp.AggFunc): 2454 self.unsupported( 2455 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2456 ) 2457 nulls_sort_change = "" 2458 elif self.NULL_ORDERING_SUPPORTED is None: 2459 if expression.this.is_int: 2460 self.unsupported( 2461 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2462 ) 2463 elif not isinstance(expression.this, exp.Rand): 2464 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2465 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2466 nulls_sort_change = "" 2467 2468 with_fill = self.sql(expression, "with_fill") 2469 with_fill = f" {with_fill}" if with_fill else "" 2470 2471 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2472 2473 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2474 window_frame = self.sql(expression, "window_frame") 2475 window_frame = f"{window_frame} " if window_frame else "" 2476 2477 this = self.sql(expression, "this") 2478 2479 return f"{window_frame}{this}" 2480 2481 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2482 partition = self.partition_by_sql(expression) 2483 order = self.sql(expression, "order") 2484 measures = self.expressions(expression, key="measures") 2485 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2486 rows = self.sql(expression, "rows") 2487 rows = self.seg(rows) if rows else "" 2488 after = self.sql(expression, "after") 2489 after = self.seg(after) if after else "" 2490 pattern = self.sql(expression, "pattern") 2491 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2492 definition_sqls = [ 2493 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2494 for definition in expression.args.get("define", []) 2495 ] 2496 definitions = self.expressions(sqls=definition_sqls) 2497 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2498 body = "".join( 2499 ( 2500 partition, 2501 order, 2502 measures, 2503 rows, 2504 after, 2505 pattern, 2506 define, 2507 ) 2508 ) 2509 alias = self.sql(expression, "alias") 2510 alias = f" {alias}" if alias else "" 2511 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2512 2513 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2514 limit = expression.args.get("limit") 2515 2516 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2517 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2518 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2519 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2520 2521 return csv( 2522 *sqls, 2523 *[self.sql(join) for join in expression.args.get("joins") or []], 2524 self.sql(expression, "match"), 2525 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2526 self.sql(expression, "prewhere"), 2527 self.sql(expression, "where"), 2528 self.sql(expression, "connect"), 2529 self.sql(expression, "group"), 2530 self.sql(expression, "having"), 2531 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2532 self.sql(expression, "order"), 2533 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2534 *self.after_limit_modifiers(expression), 2535 self.options_modifier(expression), 2536 sep="", 2537 ) 2538 2539 def options_modifier(self, expression: exp.Expression) -> str: 2540 options = self.expressions(expression, key="options") 2541 return f" {options}" if options else "" 2542 2543 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2544 return "" 2545 2546 def offset_limit_modifiers( 2547 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2548 ) -> t.List[str]: 2549 return [ 2550 self.sql(expression, "offset") if fetch else self.sql(limit), 2551 self.sql(limit) if fetch else self.sql(expression, "offset"), 2552 ] 2553 2554 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2555 locks = self.expressions(expression, key="locks", sep=" ") 2556 locks = f" {locks}" if locks else "" 2557 return [locks, self.sql(expression, "sample")] 2558 2559 def select_sql(self, expression: exp.Select) -> str: 2560 into = expression.args.get("into") 2561 if not self.SUPPORTS_SELECT_INTO and into: 2562 into.pop() 2563 2564 hint = self.sql(expression, "hint") 2565 distinct = self.sql(expression, "distinct") 2566 distinct = f" {distinct}" if distinct else "" 2567 kind = self.sql(expression, "kind") 2568 2569 limit = expression.args.get("limit") 2570 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2571 top = self.limit_sql(limit, top=True) 2572 limit.pop() 2573 else: 2574 top = "" 2575 2576 expressions = self.expressions(expression) 2577 2578 if kind: 2579 if kind in self.SELECT_KINDS: 2580 kind = f" AS {kind}" 2581 else: 2582 if kind == "STRUCT": 2583 expressions = self.expressions( 2584 sqls=[ 2585 self.sql( 2586 exp.Struct( 2587 expressions=[ 2588 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2589 if isinstance(e, exp.Alias) 2590 else e 2591 for e in expression.expressions 2592 ] 2593 ) 2594 ) 2595 ] 2596 ) 2597 kind = "" 2598 2599 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2600 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2601 2602 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2603 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2604 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2605 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2606 sql = self.query_modifiers( 2607 expression, 2608 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2609 self.sql(expression, "into", comment=False), 2610 self.sql(expression, "from", comment=False), 2611 ) 2612 2613 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2614 if expression.args.get("with"): 2615 sql = self.maybe_comment(sql, expression) 2616 expression.pop_comments() 2617 2618 sql = self.prepend_ctes(expression, sql) 2619 2620 if not self.SUPPORTS_SELECT_INTO and into: 2621 if into.args.get("temporary"): 2622 table_kind = " TEMPORARY" 2623 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2624 table_kind = " UNLOGGED" 2625 else: 2626 table_kind = "" 2627 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2628 2629 return sql 2630 2631 def schema_sql(self, expression: exp.Schema) -> str: 2632 this = self.sql(expression, "this") 2633 sql = self.schema_columns_sql(expression) 2634 return f"{this} {sql}" if this and sql else this or sql 2635 2636 def schema_columns_sql(self, expression: exp.Schema) -> str: 2637 if expression.expressions: 2638 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2639 return "" 2640 2641 def star_sql(self, expression: exp.Star) -> str: 2642 except_ = self.expressions(expression, key="except", flat=True) 2643 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2644 replace = self.expressions(expression, key="replace", flat=True) 2645 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2646 rename = self.expressions(expression, key="rename", flat=True) 2647 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2648 return f"*{except_}{replace}{rename}" 2649 2650 def parameter_sql(self, expression: exp.Parameter) -> str: 2651 this = self.sql(expression, "this") 2652 return f"{self.PARAMETER_TOKEN}{this}" 2653 2654 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2655 this = self.sql(expression, "this") 2656 kind = expression.text("kind") 2657 if kind: 2658 kind = f"{kind}." 2659 return f"@@{kind}{this}" 2660 2661 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2662 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2663 2664 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2665 alias = self.sql(expression, "alias") 2666 alias = f"{sep}{alias}" if alias else "" 2667 sample = self.sql(expression, "sample") 2668 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2669 alias = f"{sample}{alias}" 2670 2671 # Set to None so it's not generated again by self.query_modifiers() 2672 expression.set("sample", None) 2673 2674 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2675 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2676 return self.prepend_ctes(expression, sql) 2677 2678 def qualify_sql(self, expression: exp.Qualify) -> str: 2679 this = self.indent(self.sql(expression, "this")) 2680 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2681 2682 def unnest_sql(self, expression: exp.Unnest) -> str: 2683 args = self.expressions(expression, flat=True) 2684 2685 alias = expression.args.get("alias") 2686 offset = expression.args.get("offset") 2687 2688 if self.UNNEST_WITH_ORDINALITY: 2689 if alias and isinstance(offset, exp.Expression): 2690 alias.append("columns", offset) 2691 2692 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2693 columns = alias.columns 2694 alias = self.sql(columns[0]) if columns else "" 2695 else: 2696 alias = self.sql(alias) 2697 2698 alias = f" AS {alias}" if alias else alias 2699 if self.UNNEST_WITH_ORDINALITY: 2700 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2701 else: 2702 if isinstance(offset, exp.Expression): 2703 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2704 elif offset: 2705 suffix = f"{alias} WITH OFFSET" 2706 else: 2707 suffix = alias 2708 2709 return f"UNNEST({args}){suffix}" 2710 2711 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2712 return "" 2713 2714 def where_sql(self, expression: exp.Where) -> str: 2715 this = self.indent(self.sql(expression, "this")) 2716 return f"{self.seg('WHERE')}{self.sep()}{this}" 2717 2718 def window_sql(self, expression: exp.Window) -> str: 2719 this = self.sql(expression, "this") 2720 partition = self.partition_by_sql(expression) 2721 order = expression.args.get("order") 2722 order = self.order_sql(order, flat=True) if order else "" 2723 spec = self.sql(expression, "spec") 2724 alias = self.sql(expression, "alias") 2725 over = self.sql(expression, "over") or "OVER" 2726 2727 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2728 2729 first = expression.args.get("first") 2730 if first is None: 2731 first = "" 2732 else: 2733 first = "FIRST" if first else "LAST" 2734 2735 if not partition and not order and not spec and alias: 2736 return f"{this} {alias}" 2737 2738 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2739 return f"{this} ({args})" 2740 2741 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2742 partition = self.expressions(expression, key="partition_by", flat=True) 2743 return f"PARTITION BY {partition}" if partition else "" 2744 2745 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2746 kind = self.sql(expression, "kind") 2747 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2748 end = ( 2749 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2750 or "CURRENT ROW" 2751 ) 2752 return f"{kind} BETWEEN {start} AND {end}" 2753 2754 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2755 this = self.sql(expression, "this") 2756 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2757 return f"{this} WITHIN GROUP ({expression_sql})" 2758 2759 def between_sql(self, expression: exp.Between) -> str: 2760 this = self.sql(expression, "this") 2761 low = self.sql(expression, "low") 2762 high = self.sql(expression, "high") 2763 return f"{this} BETWEEN {low} AND {high}" 2764 2765 def bracket_offset_expressions( 2766 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2767 ) -> t.List[exp.Expression]: 2768 return apply_index_offset( 2769 expression.this, 2770 expression.expressions, 2771 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2772 ) 2773 2774 def bracket_sql(self, expression: exp.Bracket) -> str: 2775 expressions = self.bracket_offset_expressions(expression) 2776 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2777 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2778 2779 def all_sql(self, expression: exp.All) -> str: 2780 return f"ALL {self.wrap(expression)}" 2781 2782 def any_sql(self, expression: exp.Any) -> str: 2783 this = self.sql(expression, "this") 2784 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2785 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2786 this = self.wrap(this) 2787 return f"ANY{this}" 2788 return f"ANY {this}" 2789 2790 def exists_sql(self, expression: exp.Exists) -> str: 2791 return f"EXISTS{self.wrap(expression)}" 2792 2793 def case_sql(self, expression: exp.Case) -> str: 2794 this = self.sql(expression, "this") 2795 statements = [f"CASE {this}" if this else "CASE"] 2796 2797 for e in expression.args["ifs"]: 2798 statements.append(f"WHEN {self.sql(e, 'this')}") 2799 statements.append(f"THEN {self.sql(e, 'true')}") 2800 2801 default = self.sql(expression, "default") 2802 2803 if default: 2804 statements.append(f"ELSE {default}") 2805 2806 statements.append("END") 2807 2808 if self.pretty and self.too_wide(statements): 2809 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2810 2811 return " ".join(statements) 2812 2813 def constraint_sql(self, expression: exp.Constraint) -> str: 2814 this = self.sql(expression, "this") 2815 expressions = self.expressions(expression, flat=True) 2816 return f"CONSTRAINT {this} {expressions}" 2817 2818 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2819 order = expression.args.get("order") 2820 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2821 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2822 2823 def extract_sql(self, expression: exp.Extract) -> str: 2824 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2825 expression_sql = self.sql(expression, "expression") 2826 return f"EXTRACT({this} FROM {expression_sql})" 2827 2828 def trim_sql(self, expression: exp.Trim) -> str: 2829 trim_type = self.sql(expression, "position") 2830 2831 if trim_type == "LEADING": 2832 func_name = "LTRIM" 2833 elif trim_type == "TRAILING": 2834 func_name = "RTRIM" 2835 else: 2836 func_name = "TRIM" 2837 2838 return self.func(func_name, expression.this, expression.expression) 2839 2840 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2841 args = expression.expressions 2842 if isinstance(expression, exp.ConcatWs): 2843 args = args[1:] # Skip the delimiter 2844 2845 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2846 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2847 2848 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2849 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2850 2851 return args 2852 2853 def concat_sql(self, expression: exp.Concat) -> str: 2854 expressions = self.convert_concat_args(expression) 2855 2856 # Some dialects don't allow a single-argument CONCAT call 2857 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2858 return self.sql(expressions[0]) 2859 2860 return self.func("CONCAT", *expressions) 2861 2862 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2863 return self.func( 2864 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2865 ) 2866 2867 def check_sql(self, expression: exp.Check) -> str: 2868 this = self.sql(expression, key="this") 2869 return f"CHECK ({this})" 2870 2871 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2872 expressions = self.expressions(expression, flat=True) 2873 expressions = f" ({expressions})" if expressions else "" 2874 reference = self.sql(expression, "reference") 2875 reference = f" {reference}" if reference else "" 2876 delete = self.sql(expression, "delete") 2877 delete = f" ON DELETE {delete}" if delete else "" 2878 update = self.sql(expression, "update") 2879 update = f" ON UPDATE {update}" if update else "" 2880 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2881 2882 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2883 expressions = self.expressions(expression, flat=True) 2884 options = self.expressions(expression, key="options", flat=True, sep=" ") 2885 options = f" {options}" if options else "" 2886 return f"PRIMARY KEY ({expressions}){options}" 2887 2888 def if_sql(self, expression: exp.If) -> str: 2889 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2890 2891 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2892 modifier = expression.args.get("modifier") 2893 modifier = f" {modifier}" if modifier else "" 2894 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2895 2896 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2897 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2898 2899 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2900 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2901 2902 if expression.args.get("escape"): 2903 path = self.escape_str(path) 2904 2905 if self.QUOTE_JSON_PATH: 2906 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2907 2908 return path 2909 2910 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2911 if isinstance(expression, exp.JSONPathPart): 2912 transform = self.TRANSFORMS.get(expression.__class__) 2913 if not callable(transform): 2914 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2915 return "" 2916 2917 return transform(self, expression) 2918 2919 if isinstance(expression, int): 2920 return str(expression) 2921 2922 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2923 escaped = expression.replace("'", "\\'") 2924 escaped = f"\\'{expression}\\'" 2925 else: 2926 escaped = expression.replace('"', '\\"') 2927 escaped = f'"{escaped}"' 2928 2929 return escaped 2930 2931 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2932 return f"{self.sql(expression, 'this')} FORMAT JSON" 2933 2934 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2935 null_handling = expression.args.get("null_handling") 2936 null_handling = f" {null_handling}" if null_handling else "" 2937 2938 unique_keys = expression.args.get("unique_keys") 2939 if unique_keys is not None: 2940 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2941 else: 2942 unique_keys = "" 2943 2944 return_type = self.sql(expression, "return_type") 2945 return_type = f" RETURNING {return_type}" if return_type else "" 2946 encoding = self.sql(expression, "encoding") 2947 encoding = f" ENCODING {encoding}" if encoding else "" 2948 2949 return self.func( 2950 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2951 *expression.expressions, 2952 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2953 ) 2954 2955 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2956 return self.jsonobject_sql(expression) 2957 2958 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2959 null_handling = expression.args.get("null_handling") 2960 null_handling = f" {null_handling}" if null_handling else "" 2961 return_type = self.sql(expression, "return_type") 2962 return_type = f" RETURNING {return_type}" if return_type else "" 2963 strict = " STRICT" if expression.args.get("strict") else "" 2964 return self.func( 2965 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2966 ) 2967 2968 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2969 this = self.sql(expression, "this") 2970 order = self.sql(expression, "order") 2971 null_handling = expression.args.get("null_handling") 2972 null_handling = f" {null_handling}" if null_handling else "" 2973 return_type = self.sql(expression, "return_type") 2974 return_type = f" RETURNING {return_type}" if return_type else "" 2975 strict = " STRICT" if expression.args.get("strict") else "" 2976 return self.func( 2977 "JSON_ARRAYAGG", 2978 this, 2979 suffix=f"{order}{null_handling}{return_type}{strict})", 2980 ) 2981 2982 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2983 path = self.sql(expression, "path") 2984 path = f" PATH {path}" if path else "" 2985 nested_schema = self.sql(expression, "nested_schema") 2986 2987 if nested_schema: 2988 return f"NESTED{path} {nested_schema}" 2989 2990 this = self.sql(expression, "this") 2991 kind = self.sql(expression, "kind") 2992 kind = f" {kind}" if kind else "" 2993 return f"{this}{kind}{path}" 2994 2995 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2996 return self.func("COLUMNS", *expression.expressions) 2997 2998 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2999 this = self.sql(expression, "this") 3000 path = self.sql(expression, "path") 3001 path = f", {path}" if path else "" 3002 error_handling = expression.args.get("error_handling") 3003 error_handling = f" {error_handling}" if error_handling else "" 3004 empty_handling = expression.args.get("empty_handling") 3005 empty_handling = f" {empty_handling}" if empty_handling else "" 3006 schema = self.sql(expression, "schema") 3007 return self.func( 3008 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3009 ) 3010 3011 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3012 this = self.sql(expression, "this") 3013 kind = self.sql(expression, "kind") 3014 path = self.sql(expression, "path") 3015 path = f" {path}" if path else "" 3016 as_json = " AS JSON" if expression.args.get("as_json") else "" 3017 return f"{this} {kind}{path}{as_json}" 3018 3019 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3020 this = self.sql(expression, "this") 3021 path = self.sql(expression, "path") 3022 path = f", {path}" if path else "" 3023 expressions = self.expressions(expression) 3024 with_ = ( 3025 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3026 if expressions 3027 else "" 3028 ) 3029 return f"OPENJSON({this}{path}){with_}" 3030 3031 def in_sql(self, expression: exp.In) -> str: 3032 query = expression.args.get("query") 3033 unnest = expression.args.get("unnest") 3034 field = expression.args.get("field") 3035 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3036 3037 if query: 3038 in_sql = self.sql(query) 3039 elif unnest: 3040 in_sql = self.in_unnest_op(unnest) 3041 elif field: 3042 in_sql = self.sql(field) 3043 else: 3044 in_sql = f"({self.expressions(expression, flat=True)})" 3045 3046 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3047 3048 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3049 return f"(SELECT {self.sql(unnest)})" 3050 3051 def interval_sql(self, expression: exp.Interval) -> str: 3052 unit = self.sql(expression, "unit") 3053 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3054 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3055 unit = f" {unit}" if unit else "" 3056 3057 if self.SINGLE_STRING_INTERVAL: 3058 this = expression.this.name if expression.this else "" 3059 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3060 3061 this = self.sql(expression, "this") 3062 if this: 3063 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3064 this = f" {this}" if unwrapped else f" ({this})" 3065 3066 return f"INTERVAL{this}{unit}" 3067 3068 def return_sql(self, expression: exp.Return) -> str: 3069 return f"RETURN {self.sql(expression, 'this')}" 3070 3071 def reference_sql(self, expression: exp.Reference) -> str: 3072 this = self.sql(expression, "this") 3073 expressions = self.expressions(expression, flat=True) 3074 expressions = f"({expressions})" if expressions else "" 3075 options = self.expressions(expression, key="options", flat=True, sep=" ") 3076 options = f" {options}" if options else "" 3077 return f"REFERENCES {this}{expressions}{options}" 3078 3079 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3080 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3081 parent = expression.parent 3082 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3083 return self.func( 3084 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3085 ) 3086 3087 def paren_sql(self, expression: exp.Paren) -> str: 3088 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3089 return f"({sql}{self.seg(')', sep='')}" 3090 3091 def neg_sql(self, expression: exp.Neg) -> str: 3092 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3093 this_sql = self.sql(expression, "this") 3094 sep = " " if this_sql[0] == "-" else "" 3095 return f"-{sep}{this_sql}" 3096 3097 def not_sql(self, expression: exp.Not) -> str: 3098 return f"NOT {self.sql(expression, 'this')}" 3099 3100 def alias_sql(self, expression: exp.Alias) -> str: 3101 alias = self.sql(expression, "alias") 3102 alias = f" AS {alias}" if alias else "" 3103 return f"{self.sql(expression, 'this')}{alias}" 3104 3105 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3106 alias = expression.args["alias"] 3107 3108 identifier_alias = isinstance(alias, exp.Identifier) 3109 literal_alias = isinstance(alias, exp.Literal) 3110 3111 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3112 alias.replace(exp.Literal.string(alias.output_name)) 3113 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3114 alias.replace(exp.to_identifier(alias.output_name)) 3115 3116 return self.alias_sql(expression) 3117 3118 def aliases_sql(self, expression: exp.Aliases) -> str: 3119 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3120 3121 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3122 this = self.sql(expression, "this") 3123 index = self.sql(expression, "expression") 3124 return f"{this} AT {index}" 3125 3126 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3127 this = self.sql(expression, "this") 3128 zone = self.sql(expression, "zone") 3129 return f"{this} AT TIME ZONE {zone}" 3130 3131 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3132 this = self.sql(expression, "this") 3133 zone = self.sql(expression, "zone") 3134 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3135 3136 def add_sql(self, expression: exp.Add) -> str: 3137 return self.binary(expression, "+") 3138 3139 def and_sql( 3140 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3141 ) -> str: 3142 return self.connector_sql(expression, "AND", stack) 3143 3144 def or_sql( 3145 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3146 ) -> str: 3147 return self.connector_sql(expression, "OR", stack) 3148 3149 def xor_sql( 3150 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3151 ) -> str: 3152 return self.connector_sql(expression, "XOR", stack) 3153 3154 def connector_sql( 3155 self, 3156 expression: exp.Connector, 3157 op: str, 3158 stack: t.Optional[t.List[str | exp.Expression]] = None, 3159 ) -> str: 3160 if stack is not None: 3161 if expression.expressions: 3162 stack.append(self.expressions(expression, sep=f" {op} ")) 3163 else: 3164 stack.append(expression.right) 3165 if expression.comments and self.comments: 3166 for comment in expression.comments: 3167 if comment: 3168 op += f" /*{self.pad_comment(comment)}*/" 3169 stack.extend((op, expression.left)) 3170 return op 3171 3172 stack = [expression] 3173 sqls: t.List[str] = [] 3174 ops = set() 3175 3176 while stack: 3177 node = stack.pop() 3178 if isinstance(node, exp.Connector): 3179 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3180 else: 3181 sql = self.sql(node) 3182 if sqls and sqls[-1] in ops: 3183 sqls[-1] += f" {sql}" 3184 else: 3185 sqls.append(sql) 3186 3187 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3188 return sep.join(sqls) 3189 3190 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3191 return self.binary(expression, "&") 3192 3193 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3194 return self.binary(expression, "<<") 3195 3196 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3197 return f"~{self.sql(expression, 'this')}" 3198 3199 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3200 return self.binary(expression, "|") 3201 3202 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3203 return self.binary(expression, ">>") 3204 3205 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3206 return self.binary(expression, "^") 3207 3208 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3209 format_sql = self.sql(expression, "format") 3210 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3211 to_sql = self.sql(expression, "to") 3212 to_sql = f" {to_sql}" if to_sql else "" 3213 action = self.sql(expression, "action") 3214 action = f" {action}" if action else "" 3215 default = self.sql(expression, "default") 3216 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3217 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3218 3219 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3220 zone = self.sql(expression, "this") 3221 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3222 3223 def collate_sql(self, expression: exp.Collate) -> str: 3224 if self.COLLATE_IS_FUNC: 3225 return self.function_fallback_sql(expression) 3226 return self.binary(expression, "COLLATE") 3227 3228 def command_sql(self, expression: exp.Command) -> str: 3229 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3230 3231 def comment_sql(self, expression: exp.Comment) -> str: 3232 this = self.sql(expression, "this") 3233 kind = expression.args["kind"] 3234 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3235 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3236 expression_sql = self.sql(expression, "expression") 3237 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3238 3239 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3240 this = self.sql(expression, "this") 3241 delete = " DELETE" if expression.args.get("delete") else "" 3242 recompress = self.sql(expression, "recompress") 3243 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3244 to_disk = self.sql(expression, "to_disk") 3245 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3246 to_volume = self.sql(expression, "to_volume") 3247 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3248 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3249 3250 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3251 where = self.sql(expression, "where") 3252 group = self.sql(expression, "group") 3253 aggregates = self.expressions(expression, key="aggregates") 3254 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3255 3256 if not (where or group or aggregates) and len(expression.expressions) == 1: 3257 return f"TTL {self.expressions(expression, flat=True)}" 3258 3259 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3260 3261 def transaction_sql(self, expression: exp.Transaction) -> str: 3262 return "BEGIN" 3263 3264 def commit_sql(self, expression: exp.Commit) -> str: 3265 chain = expression.args.get("chain") 3266 if chain is not None: 3267 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3268 3269 return f"COMMIT{chain or ''}" 3270 3271 def rollback_sql(self, expression: exp.Rollback) -> str: 3272 savepoint = expression.args.get("savepoint") 3273 savepoint = f" TO {savepoint}" if savepoint else "" 3274 return f"ROLLBACK{savepoint}" 3275 3276 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3277 this = self.sql(expression, "this") 3278 3279 dtype = self.sql(expression, "dtype") 3280 if dtype: 3281 collate = self.sql(expression, "collate") 3282 collate = f" COLLATE {collate}" if collate else "" 3283 using = self.sql(expression, "using") 3284 using = f" USING {using}" if using else "" 3285 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3286 3287 default = self.sql(expression, "default") 3288 if default: 3289 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3290 3291 comment = self.sql(expression, "comment") 3292 if comment: 3293 return f"ALTER COLUMN {this} COMMENT {comment}" 3294 3295 allow_null = expression.args.get("allow_null") 3296 drop = expression.args.get("drop") 3297 3298 if not drop and not allow_null: 3299 self.unsupported("Unsupported ALTER COLUMN syntax") 3300 3301 if allow_null is not None: 3302 keyword = "DROP" if drop else "SET" 3303 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3304 3305 return f"ALTER COLUMN {this} DROP DEFAULT" 3306 3307 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3308 this = self.sql(expression, "this") 3309 3310 visible = expression.args.get("visible") 3311 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3312 3313 return f"ALTER INDEX {this} {visible_sql}" 3314 3315 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3316 this = self.sql(expression, "this") 3317 if not isinstance(expression.this, exp.Var): 3318 this = f"KEY DISTKEY {this}" 3319 return f"ALTER DISTSTYLE {this}" 3320 3321 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3322 compound = " COMPOUND" if expression.args.get("compound") else "" 3323 this = self.sql(expression, "this") 3324 expressions = self.expressions(expression, flat=True) 3325 expressions = f"({expressions})" if expressions else "" 3326 return f"ALTER{compound} SORTKEY {this or expressions}" 3327 3328 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3329 if not self.RENAME_TABLE_WITH_DB: 3330 # Remove db from tables 3331 expression = expression.transform( 3332 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3333 ).assert_is(exp.AlterRename) 3334 this = self.sql(expression, "this") 3335 return f"RENAME TO {this}" 3336 3337 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3338 exists = " IF EXISTS" if expression.args.get("exists") else "" 3339 old_column = self.sql(expression, "this") 3340 new_column = self.sql(expression, "to") 3341 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3342 3343 def alterset_sql(self, expression: exp.AlterSet) -> str: 3344 exprs = self.expressions(expression, flat=True) 3345 return f"SET {exprs}" 3346 3347 def alter_sql(self, expression: exp.Alter) -> str: 3348 actions = expression.args["actions"] 3349 3350 if isinstance(actions[0], exp.ColumnDef): 3351 actions = self.add_column_sql(expression) 3352 elif isinstance(actions[0], exp.Schema): 3353 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3354 elif isinstance(actions[0], exp.Delete): 3355 actions = self.expressions(expression, key="actions", flat=True) 3356 elif isinstance(actions[0], exp.Query): 3357 actions = "AS " + self.expressions(expression, key="actions") 3358 else: 3359 actions = self.expressions(expression, key="actions", flat=True) 3360 3361 exists = " IF EXISTS" if expression.args.get("exists") else "" 3362 on_cluster = self.sql(expression, "cluster") 3363 on_cluster = f" {on_cluster}" if on_cluster else "" 3364 only = " ONLY" if expression.args.get("only") else "" 3365 options = self.expressions(expression, key="options") 3366 options = f", {options}" if options else "" 3367 kind = self.sql(expression, "kind") 3368 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3369 3370 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3371 3372 def add_column_sql(self, expression: exp.Alter) -> str: 3373 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3374 return self.expressions( 3375 expression, 3376 key="actions", 3377 prefix="ADD COLUMN ", 3378 skip_first=True, 3379 ) 3380 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3381 3382 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3383 expressions = self.expressions(expression) 3384 exists = " IF EXISTS " if expression.args.get("exists") else " " 3385 return f"DROP{exists}{expressions}" 3386 3387 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3388 return f"ADD {self.expressions(expression)}" 3389 3390 def distinct_sql(self, expression: exp.Distinct) -> str: 3391 this = self.expressions(expression, flat=True) 3392 3393 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3394 case = exp.case() 3395 for arg in expression.expressions: 3396 case = case.when(arg.is_(exp.null()), exp.null()) 3397 this = self.sql(case.else_(f"({this})")) 3398 3399 this = f" {this}" if this else "" 3400 3401 on = self.sql(expression, "on") 3402 on = f" ON {on}" if on else "" 3403 return f"DISTINCT{this}{on}" 3404 3405 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3406 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3407 3408 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3409 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3410 3411 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3412 this_sql = self.sql(expression, "this") 3413 expression_sql = self.sql(expression, "expression") 3414 kind = "MAX" if expression.args.get("max") else "MIN" 3415 return f"{this_sql} HAVING {kind} {expression_sql}" 3416 3417 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3418 return self.sql( 3419 exp.Cast( 3420 this=exp.Div(this=expression.this, expression=expression.expression), 3421 to=exp.DataType(this=exp.DataType.Type.INT), 3422 ) 3423 ) 3424 3425 def dpipe_sql(self, expression: exp.DPipe) -> str: 3426 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3427 return self.func( 3428 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3429 ) 3430 return self.binary(expression, "||") 3431 3432 def div_sql(self, expression: exp.Div) -> str: 3433 l, r = expression.left, expression.right 3434 3435 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3436 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3437 3438 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3439 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3440 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3441 3442 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3443 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3444 return self.sql( 3445 exp.cast( 3446 l / r, 3447 to=exp.DataType.Type.BIGINT, 3448 ) 3449 ) 3450 3451 return self.binary(expression, "/") 3452 3453 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3454 n = exp._wrap(expression.this, exp.Binary) 3455 d = exp._wrap(expression.expression, exp.Binary) 3456 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3457 3458 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3459 return self.binary(expression, "OVERLAPS") 3460 3461 def distance_sql(self, expression: exp.Distance) -> str: 3462 return self.binary(expression, "<->") 3463 3464 def dot_sql(self, expression: exp.Dot) -> str: 3465 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3466 3467 def eq_sql(self, expression: exp.EQ) -> str: 3468 return self.binary(expression, "=") 3469 3470 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3471 return self.binary(expression, ":=") 3472 3473 def escape_sql(self, expression: exp.Escape) -> str: 3474 return self.binary(expression, "ESCAPE") 3475 3476 def glob_sql(self, expression: exp.Glob) -> str: 3477 return self.binary(expression, "GLOB") 3478 3479 def gt_sql(self, expression: exp.GT) -> str: 3480 return self.binary(expression, ">") 3481 3482 def gte_sql(self, expression: exp.GTE) -> str: 3483 return self.binary(expression, ">=") 3484 3485 def ilike_sql(self, expression: exp.ILike) -> str: 3486 return self.binary(expression, "ILIKE") 3487 3488 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3489 return self.binary(expression, "ILIKE ANY") 3490 3491 def is_sql(self, expression: exp.Is) -> str: 3492 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3493 return self.sql( 3494 expression.this if expression.expression.this else exp.not_(expression.this) 3495 ) 3496 return self.binary(expression, "IS") 3497 3498 def like_sql(self, expression: exp.Like) -> str: 3499 return self.binary(expression, "LIKE") 3500 3501 def likeany_sql(self, expression: exp.LikeAny) -> str: 3502 return self.binary(expression, "LIKE ANY") 3503 3504 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3505 return self.binary(expression, "SIMILAR TO") 3506 3507 def lt_sql(self, expression: exp.LT) -> str: 3508 return self.binary(expression, "<") 3509 3510 def lte_sql(self, expression: exp.LTE) -> str: 3511 return self.binary(expression, "<=") 3512 3513 def mod_sql(self, expression: exp.Mod) -> str: 3514 return self.binary(expression, "%") 3515 3516 def mul_sql(self, expression: exp.Mul) -> str: 3517 return self.binary(expression, "*") 3518 3519 def neq_sql(self, expression: exp.NEQ) -> str: 3520 return self.binary(expression, "<>") 3521 3522 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3523 return self.binary(expression, "IS NOT DISTINCT FROM") 3524 3525 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3526 return self.binary(expression, "IS DISTINCT FROM") 3527 3528 def slice_sql(self, expression: exp.Slice) -> str: 3529 return self.binary(expression, ":") 3530 3531 def sub_sql(self, expression: exp.Sub) -> str: 3532 return self.binary(expression, "-") 3533 3534 def trycast_sql(self, expression: exp.TryCast) -> str: 3535 return self.cast_sql(expression, safe_prefix="TRY_") 3536 3537 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3538 return self.cast_sql(expression) 3539 3540 def try_sql(self, expression: exp.Try) -> str: 3541 if not self.TRY_SUPPORTED: 3542 self.unsupported("Unsupported TRY function") 3543 return self.sql(expression, "this") 3544 3545 return self.func("TRY", expression.this) 3546 3547 def log_sql(self, expression: exp.Log) -> str: 3548 this = expression.this 3549 expr = expression.expression 3550 3551 if self.dialect.LOG_BASE_FIRST is False: 3552 this, expr = expr, this 3553 elif self.dialect.LOG_BASE_FIRST is None and expr: 3554 if this.name in ("2", "10"): 3555 return self.func(f"LOG{this.name}", expr) 3556 3557 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3558 3559 return self.func("LOG", this, expr) 3560 3561 def use_sql(self, expression: exp.Use) -> str: 3562 kind = self.sql(expression, "kind") 3563 kind = f" {kind}" if kind else "" 3564 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3565 this = f" {this}" if this else "" 3566 return f"USE{kind}{this}" 3567 3568 def binary(self, expression: exp.Binary, op: str) -> str: 3569 sqls: t.List[str] = [] 3570 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3571 binary_type = type(expression) 3572 3573 while stack: 3574 node = stack.pop() 3575 3576 if type(node) is binary_type: 3577 op_func = node.args.get("operator") 3578 if op_func: 3579 op = f"OPERATOR({self.sql(op_func)})" 3580 3581 stack.append(node.right) 3582 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3583 stack.append(node.left) 3584 else: 3585 sqls.append(self.sql(node)) 3586 3587 return "".join(sqls) 3588 3589 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3590 to_clause = self.sql(expression, "to") 3591 if to_clause: 3592 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3593 3594 return self.function_fallback_sql(expression) 3595 3596 def function_fallback_sql(self, expression: exp.Func) -> str: 3597 args = [] 3598 3599 for key in expression.arg_types: 3600 arg_value = expression.args.get(key) 3601 3602 if isinstance(arg_value, list): 3603 for value in arg_value: 3604 args.append(value) 3605 elif arg_value is not None: 3606 args.append(arg_value) 3607 3608 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3609 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3610 else: 3611 name = expression.sql_name() 3612 3613 return self.func(name, *args) 3614 3615 def func( 3616 self, 3617 name: str, 3618 *args: t.Optional[exp.Expression | str], 3619 prefix: str = "(", 3620 suffix: str = ")", 3621 normalize: bool = True, 3622 ) -> str: 3623 name = self.normalize_func(name) if normalize else name 3624 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3625 3626 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3627 arg_sqls = tuple( 3628 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3629 ) 3630 if self.pretty and self.too_wide(arg_sqls): 3631 return self.indent( 3632 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3633 ) 3634 return sep.join(arg_sqls) 3635 3636 def too_wide(self, args: t.Iterable) -> bool: 3637 return sum(len(arg) for arg in args) > self.max_text_width 3638 3639 def format_time( 3640 self, 3641 expression: exp.Expression, 3642 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3643 inverse_time_trie: t.Optional[t.Dict] = None, 3644 ) -> t.Optional[str]: 3645 return format_time( 3646 self.sql(expression, "format"), 3647 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3648 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3649 ) 3650 3651 def expressions( 3652 self, 3653 expression: t.Optional[exp.Expression] = None, 3654 key: t.Optional[str] = None, 3655 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3656 flat: bool = False, 3657 indent: bool = True, 3658 skip_first: bool = False, 3659 skip_last: bool = False, 3660 sep: str = ", ", 3661 prefix: str = "", 3662 dynamic: bool = False, 3663 new_line: bool = False, 3664 ) -> str: 3665 expressions = expression.args.get(key or "expressions") if expression else sqls 3666 3667 if not expressions: 3668 return "" 3669 3670 if flat: 3671 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3672 3673 num_sqls = len(expressions) 3674 result_sqls = [] 3675 3676 for i, e in enumerate(expressions): 3677 sql = self.sql(e, comment=False) 3678 if not sql: 3679 continue 3680 3681 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3682 3683 if self.pretty: 3684 if self.leading_comma: 3685 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3686 else: 3687 result_sqls.append( 3688 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3689 ) 3690 else: 3691 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3692 3693 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3694 if new_line: 3695 result_sqls.insert(0, "") 3696 result_sqls.append("") 3697 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3698 else: 3699 result_sql = "".join(result_sqls) 3700 3701 return ( 3702 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3703 if indent 3704 else result_sql 3705 ) 3706 3707 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3708 flat = flat or isinstance(expression.parent, exp.Properties) 3709 expressions_sql = self.expressions(expression, flat=flat) 3710 if flat: 3711 return f"{op} {expressions_sql}" 3712 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3713 3714 def naked_property(self, expression: exp.Property) -> str: 3715 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3716 if not property_name: 3717 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3718 return f"{property_name} {self.sql(expression, 'this')}" 3719 3720 def tag_sql(self, expression: exp.Tag) -> str: 3721 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3722 3723 def token_sql(self, token_type: TokenType) -> str: 3724 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3725 3726 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3727 this = self.sql(expression, "this") 3728 expressions = self.no_identify(self.expressions, expression) 3729 expressions = ( 3730 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3731 ) 3732 return f"{this}{expressions}" if expressions.strip() != "" else this 3733 3734 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3735 this = self.sql(expression, "this") 3736 expressions = self.expressions(expression, flat=True) 3737 return f"{this}({expressions})" 3738 3739 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3740 return self.binary(expression, "=>") 3741 3742 def when_sql(self, expression: exp.When) -> str: 3743 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3744 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3745 condition = self.sql(expression, "condition") 3746 condition = f" AND {condition}" if condition else "" 3747 3748 then_expression = expression.args.get("then") 3749 if isinstance(then_expression, exp.Insert): 3750 this = self.sql(then_expression, "this") 3751 this = f"INSERT {this}" if this else "INSERT" 3752 then = self.sql(then_expression, "expression") 3753 then = f"{this} VALUES {then}" if then else this 3754 elif isinstance(then_expression, exp.Update): 3755 if isinstance(then_expression.args.get("expressions"), exp.Star): 3756 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3757 else: 3758 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3759 else: 3760 then = self.sql(then_expression) 3761 return f"WHEN {matched}{source}{condition} THEN {then}" 3762 3763 def whens_sql(self, expression: exp.Whens) -> str: 3764 return self.expressions(expression, sep=" ", indent=False) 3765 3766 def merge_sql(self, expression: exp.Merge) -> str: 3767 table = expression.this 3768 table_alias = "" 3769 3770 hints = table.args.get("hints") 3771 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3772 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3773 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3774 3775 this = self.sql(table) 3776 using = f"USING {self.sql(expression, 'using')}" 3777 on = f"ON {self.sql(expression, 'on')}" 3778 whens = self.sql(expression, "whens") 3779 3780 returning = self.sql(expression, "returning") 3781 if returning: 3782 whens = f"{whens}{returning}" 3783 3784 sep = self.sep() 3785 3786 return self.prepend_ctes( 3787 expression, 3788 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3789 ) 3790 3791 @unsupported_args("format") 3792 def tochar_sql(self, expression: exp.ToChar) -> str: 3793 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3794 3795 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3796 if not self.SUPPORTS_TO_NUMBER: 3797 self.unsupported("Unsupported TO_NUMBER function") 3798 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3799 3800 fmt = expression.args.get("format") 3801 if not fmt: 3802 self.unsupported("Conversion format is required for TO_NUMBER") 3803 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3804 3805 return self.func("TO_NUMBER", expression.this, fmt) 3806 3807 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3808 this = self.sql(expression, "this") 3809 kind = self.sql(expression, "kind") 3810 settings_sql = self.expressions(expression, key="settings", sep=" ") 3811 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3812 return f"{this}({kind}{args})" 3813 3814 def dictrange_sql(self, expression: exp.DictRange) -> str: 3815 this = self.sql(expression, "this") 3816 max = self.sql(expression, "max") 3817 min = self.sql(expression, "min") 3818 return f"{this}(MIN {min} MAX {max})" 3819 3820 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3821 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3822 3823 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3824 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3825 3826 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3827 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3828 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3829 3830 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3831 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3832 expressions = self.expressions(expression, flat=True) 3833 expressions = f" {self.wrap(expressions)}" if expressions else "" 3834 buckets = self.sql(expression, "buckets") 3835 kind = self.sql(expression, "kind") 3836 buckets = f" BUCKETS {buckets}" if buckets else "" 3837 order = self.sql(expression, "order") 3838 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3839 3840 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3841 return "" 3842 3843 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3844 expressions = self.expressions(expression, key="expressions", flat=True) 3845 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3846 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3847 buckets = self.sql(expression, "buckets") 3848 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3849 3850 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3851 this = self.sql(expression, "this") 3852 having = self.sql(expression, "having") 3853 3854 if having: 3855 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3856 3857 return self.func("ANY_VALUE", this) 3858 3859 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3860 transform = self.func("TRANSFORM", *expression.expressions) 3861 row_format_before = self.sql(expression, "row_format_before") 3862 row_format_before = f" {row_format_before}" if row_format_before else "" 3863 record_writer = self.sql(expression, "record_writer") 3864 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3865 using = f" USING {self.sql(expression, 'command_script')}" 3866 schema = self.sql(expression, "schema") 3867 schema = f" AS {schema}" if schema else "" 3868 row_format_after = self.sql(expression, "row_format_after") 3869 row_format_after = f" {row_format_after}" if row_format_after else "" 3870 record_reader = self.sql(expression, "record_reader") 3871 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3872 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3873 3874 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3875 key_block_size = self.sql(expression, "key_block_size") 3876 if key_block_size: 3877 return f"KEY_BLOCK_SIZE = {key_block_size}" 3878 3879 using = self.sql(expression, "using") 3880 if using: 3881 return f"USING {using}" 3882 3883 parser = self.sql(expression, "parser") 3884 if parser: 3885 return f"WITH PARSER {parser}" 3886 3887 comment = self.sql(expression, "comment") 3888 if comment: 3889 return f"COMMENT {comment}" 3890 3891 visible = expression.args.get("visible") 3892 if visible is not None: 3893 return "VISIBLE" if visible else "INVISIBLE" 3894 3895 engine_attr = self.sql(expression, "engine_attr") 3896 if engine_attr: 3897 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3898 3899 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3900 if secondary_engine_attr: 3901 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3902 3903 self.unsupported("Unsupported index constraint option.") 3904 return "" 3905 3906 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3907 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3908 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3909 3910 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3911 kind = self.sql(expression, "kind") 3912 kind = f"{kind} INDEX" if kind else "INDEX" 3913 this = self.sql(expression, "this") 3914 this = f" {this}" if this else "" 3915 index_type = self.sql(expression, "index_type") 3916 index_type = f" USING {index_type}" if index_type else "" 3917 expressions = self.expressions(expression, flat=True) 3918 expressions = f" ({expressions})" if expressions else "" 3919 options = self.expressions(expression, key="options", sep=" ") 3920 options = f" {options}" if options else "" 3921 return f"{kind}{this}{index_type}{expressions}{options}" 3922 3923 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3924 if self.NVL2_SUPPORTED: 3925 return self.function_fallback_sql(expression) 3926 3927 case = exp.Case().when( 3928 expression.this.is_(exp.null()).not_(copy=False), 3929 expression.args["true"], 3930 copy=False, 3931 ) 3932 else_cond = expression.args.get("false") 3933 if else_cond: 3934 case.else_(else_cond, copy=False) 3935 3936 return self.sql(case) 3937 3938 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3939 this = self.sql(expression, "this") 3940 expr = self.sql(expression, "expression") 3941 iterator = self.sql(expression, "iterator") 3942 condition = self.sql(expression, "condition") 3943 condition = f" IF {condition}" if condition else "" 3944 return f"{this} FOR {expr} IN {iterator}{condition}" 3945 3946 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3947 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3948 3949 def opclass_sql(self, expression: exp.Opclass) -> str: 3950 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3951 3952 def predict_sql(self, expression: exp.Predict) -> str: 3953 model = self.sql(expression, "this") 3954 model = f"MODEL {model}" 3955 table = self.sql(expression, "expression") 3956 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3957 parameters = self.sql(expression, "params_struct") 3958 return self.func("PREDICT", model, table, parameters or None) 3959 3960 def forin_sql(self, expression: exp.ForIn) -> str: 3961 this = self.sql(expression, "this") 3962 expression_sql = self.sql(expression, "expression") 3963 return f"FOR {this} DO {expression_sql}" 3964 3965 def refresh_sql(self, expression: exp.Refresh) -> str: 3966 this = self.sql(expression, "this") 3967 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3968 return f"REFRESH {table}{this}" 3969 3970 def toarray_sql(self, expression: exp.ToArray) -> str: 3971 arg = expression.this 3972 if not arg.type: 3973 from sqlglot.optimizer.annotate_types import annotate_types 3974 3975 arg = annotate_types(arg) 3976 3977 if arg.is_type(exp.DataType.Type.ARRAY): 3978 return self.sql(arg) 3979 3980 cond_for_null = arg.is_(exp.null()) 3981 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3982 3983 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3984 this = expression.this 3985 time_format = self.format_time(expression) 3986 3987 if time_format: 3988 return self.sql( 3989 exp.cast( 3990 exp.StrToTime(this=this, format=expression.args["format"]), 3991 exp.DataType.Type.TIME, 3992 ) 3993 ) 3994 3995 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3996 return self.sql(this) 3997 3998 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 3999 4000 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4001 this = expression.this 4002 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4003 return self.sql(this) 4004 4005 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4006 4007 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4008 this = expression.this 4009 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4010 return self.sql(this) 4011 4012 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4013 4014 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4015 this = expression.this 4016 time_format = self.format_time(expression) 4017 4018 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4019 return self.sql( 4020 exp.cast( 4021 exp.StrToTime(this=this, format=expression.args["format"]), 4022 exp.DataType.Type.DATE, 4023 ) 4024 ) 4025 4026 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4027 return self.sql(this) 4028 4029 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4030 4031 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4032 return self.sql( 4033 exp.func( 4034 "DATEDIFF", 4035 expression.this, 4036 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4037 "day", 4038 ) 4039 ) 4040 4041 def lastday_sql(self, expression: exp.LastDay) -> str: 4042 if self.LAST_DAY_SUPPORTS_DATE_PART: 4043 return self.function_fallback_sql(expression) 4044 4045 unit = expression.text("unit") 4046 if unit and unit != "MONTH": 4047 self.unsupported("Date parts are not supported in LAST_DAY.") 4048 4049 return self.func("LAST_DAY", expression.this) 4050 4051 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4052 from sqlglot.dialects.dialect import unit_to_str 4053 4054 return self.func( 4055 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4056 ) 4057 4058 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4059 if self.CAN_IMPLEMENT_ARRAY_ANY: 4060 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4061 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4062 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4063 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4064 4065 from sqlglot.dialects import Dialect 4066 4067 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4068 if self.dialect.__class__ != Dialect: 4069 self.unsupported("ARRAY_ANY is unsupported") 4070 4071 return self.function_fallback_sql(expression) 4072 4073 def struct_sql(self, expression: exp.Struct) -> str: 4074 expression.set( 4075 "expressions", 4076 [ 4077 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4078 if isinstance(e, exp.PropertyEQ) 4079 else e 4080 for e in expression.expressions 4081 ], 4082 ) 4083 4084 return self.function_fallback_sql(expression) 4085 4086 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4087 low = self.sql(expression, "this") 4088 high = self.sql(expression, "expression") 4089 4090 return f"{low} TO {high}" 4091 4092 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4093 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4094 tables = f" {self.expressions(expression)}" 4095 4096 exists = " IF EXISTS" if expression.args.get("exists") else "" 4097 4098 on_cluster = self.sql(expression, "cluster") 4099 on_cluster = f" {on_cluster}" if on_cluster else "" 4100 4101 identity = self.sql(expression, "identity") 4102 identity = f" {identity} IDENTITY" if identity else "" 4103 4104 option = self.sql(expression, "option") 4105 option = f" {option}" if option else "" 4106 4107 partition = self.sql(expression, "partition") 4108 partition = f" {partition}" if partition else "" 4109 4110 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4111 4112 # This transpiles T-SQL's CONVERT function 4113 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4114 def convert_sql(self, expression: exp.Convert) -> str: 4115 to = expression.this 4116 value = expression.expression 4117 style = expression.args.get("style") 4118 safe = expression.args.get("safe") 4119 strict = expression.args.get("strict") 4120 4121 if not to or not value: 4122 return "" 4123 4124 # Retrieve length of datatype and override to default if not specified 4125 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4126 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4127 4128 transformed: t.Optional[exp.Expression] = None 4129 cast = exp.Cast if strict else exp.TryCast 4130 4131 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4132 if isinstance(style, exp.Literal) and style.is_int: 4133 from sqlglot.dialects.tsql import TSQL 4134 4135 style_value = style.name 4136 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4137 if not converted_style: 4138 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4139 4140 fmt = exp.Literal.string(converted_style) 4141 4142 if to.this == exp.DataType.Type.DATE: 4143 transformed = exp.StrToDate(this=value, format=fmt) 4144 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4145 transformed = exp.StrToTime(this=value, format=fmt) 4146 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4147 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4148 elif to.this == exp.DataType.Type.TEXT: 4149 transformed = exp.TimeToStr(this=value, format=fmt) 4150 4151 if not transformed: 4152 transformed = cast(this=value, to=to, safe=safe) 4153 4154 return self.sql(transformed) 4155 4156 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4157 this = expression.this 4158 if isinstance(this, exp.JSONPathWildcard): 4159 this = self.json_path_part(this) 4160 return f".{this}" if this else "" 4161 4162 if exp.SAFE_IDENTIFIER_RE.match(this): 4163 return f".{this}" 4164 4165 this = self.json_path_part(this) 4166 return ( 4167 f"[{this}]" 4168 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4169 else f".{this}" 4170 ) 4171 4172 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4173 this = self.json_path_part(expression.this) 4174 return f"[{this}]" if this else "" 4175 4176 def _simplify_unless_literal(self, expression: E) -> E: 4177 if not isinstance(expression, exp.Literal): 4178 from sqlglot.optimizer.simplify import simplify 4179 4180 expression = simplify(expression, dialect=self.dialect) 4181 4182 return expression 4183 4184 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4185 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4186 # The first modifier here will be the one closest to the AggFunc's arg 4187 mods = sorted( 4188 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4189 key=lambda x: 0 4190 if isinstance(x, exp.HavingMax) 4191 else (1 if isinstance(x, exp.Order) else 2), 4192 ) 4193 4194 if mods: 4195 mod = mods[0] 4196 this = expression.__class__(this=mod.this.copy()) 4197 this.meta["inline"] = True 4198 mod.this.replace(this) 4199 return self.sql(expression.this) 4200 4201 agg_func = expression.find(exp.AggFunc) 4202 4203 if agg_func: 4204 return self.sql(agg_func)[:-1] + f" {text})" 4205 4206 return f"{self.sql(expression, 'this')} {text}" 4207 4208 def _replace_line_breaks(self, string: str) -> str: 4209 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4210 if self.pretty: 4211 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4212 return string 4213 4214 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4215 option = self.sql(expression, "this") 4216 4217 if expression.expressions: 4218 upper = option.upper() 4219 4220 # Snowflake FILE_FORMAT options are separated by whitespace 4221 sep = " " if upper == "FILE_FORMAT" else ", " 4222 4223 # Databricks copy/format options do not set their list of values with EQ 4224 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4225 values = self.expressions(expression, flat=True, sep=sep) 4226 return f"{option}{op}({values})" 4227 4228 value = self.sql(expression, "expression") 4229 4230 if not value: 4231 return option 4232 4233 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4234 4235 return f"{option}{op}{value}" 4236 4237 def credentials_sql(self, expression: exp.Credentials) -> str: 4238 cred_expr = expression.args.get("credentials") 4239 if isinstance(cred_expr, exp.Literal): 4240 # Redshift case: CREDENTIALS <string> 4241 credentials = self.sql(expression, "credentials") 4242 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4243 else: 4244 # Snowflake case: CREDENTIALS = (...) 4245 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4246 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4247 4248 storage = self.sql(expression, "storage") 4249 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4250 4251 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4252 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4253 4254 iam_role = self.sql(expression, "iam_role") 4255 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4256 4257 region = self.sql(expression, "region") 4258 region = f" REGION {region}" if region else "" 4259 4260 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4261 4262 def copy_sql(self, expression: exp.Copy) -> str: 4263 this = self.sql(expression, "this") 4264 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4265 4266 credentials = self.sql(expression, "credentials") 4267 credentials = self.seg(credentials) if credentials else "" 4268 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4269 files = self.expressions(expression, key="files", flat=True) 4270 4271 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4272 params = self.expressions( 4273 expression, 4274 key="params", 4275 sep=sep, 4276 new_line=True, 4277 skip_last=True, 4278 skip_first=True, 4279 indent=self.COPY_PARAMS_ARE_WRAPPED, 4280 ) 4281 4282 if params: 4283 if self.COPY_PARAMS_ARE_WRAPPED: 4284 params = f" WITH ({params})" 4285 elif not self.pretty: 4286 params = f" {params}" 4287 4288 return f"COPY{this}{kind} {files}{credentials}{params}" 4289 4290 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4291 return "" 4292 4293 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4294 on_sql = "ON" if expression.args.get("on") else "OFF" 4295 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4296 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4297 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4298 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4299 4300 if filter_col or retention_period: 4301 on_sql = self.func("ON", filter_col, retention_period) 4302 4303 return f"DATA_DELETION={on_sql}" 4304 4305 def maskingpolicycolumnconstraint_sql( 4306 self, expression: exp.MaskingPolicyColumnConstraint 4307 ) -> str: 4308 this = self.sql(expression, "this") 4309 expressions = self.expressions(expression, flat=True) 4310 expressions = f" USING ({expressions})" if expressions else "" 4311 return f"MASKING POLICY {this}{expressions}" 4312 4313 def gapfill_sql(self, expression: exp.GapFill) -> str: 4314 this = self.sql(expression, "this") 4315 this = f"TABLE {this}" 4316 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4317 4318 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4319 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4320 4321 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4322 this = self.sql(expression, "this") 4323 expr = expression.expression 4324 4325 if isinstance(expr, exp.Func): 4326 # T-SQL's CLR functions are case sensitive 4327 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4328 else: 4329 expr = self.sql(expression, "expression") 4330 4331 return self.scope_resolution(expr, this) 4332 4333 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4334 if self.PARSE_JSON_NAME is None: 4335 return self.sql(expression.this) 4336 4337 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4338 4339 def rand_sql(self, expression: exp.Rand) -> str: 4340 lower = self.sql(expression, "lower") 4341 upper = self.sql(expression, "upper") 4342 4343 if lower and upper: 4344 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4345 return self.func("RAND", expression.this) 4346 4347 def changes_sql(self, expression: exp.Changes) -> str: 4348 information = self.sql(expression, "information") 4349 information = f"INFORMATION => {information}" 4350 at_before = self.sql(expression, "at_before") 4351 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4352 end = self.sql(expression, "end") 4353 end = f"{self.seg('')}{end}" if end else "" 4354 4355 return f"CHANGES ({information}){at_before}{end}" 4356 4357 def pad_sql(self, expression: exp.Pad) -> str: 4358 prefix = "L" if expression.args.get("is_left") else "R" 4359 4360 fill_pattern = self.sql(expression, "fill_pattern") or None 4361 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4362 fill_pattern = "' '" 4363 4364 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4365 4366 def summarize_sql(self, expression: exp.Summarize) -> str: 4367 table = " TABLE" if expression.args.get("table") else "" 4368 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4369 4370 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4371 generate_series = exp.GenerateSeries(**expression.args) 4372 4373 parent = expression.parent 4374 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4375 parent = parent.parent 4376 4377 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4378 return self.sql(exp.Unnest(expressions=[generate_series])) 4379 4380 if isinstance(parent, exp.Select): 4381 self.unsupported("GenerateSeries projection unnesting is not supported.") 4382 4383 return self.sql(generate_series) 4384 4385 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4386 exprs = expression.expressions 4387 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4388 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4389 else: 4390 rhs = self.expressions(expression) 4391 4392 return self.func(name, expression.this, rhs or None) 4393 4394 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4395 if self.SUPPORTS_CONVERT_TIMEZONE: 4396 return self.function_fallback_sql(expression) 4397 4398 source_tz = expression.args.get("source_tz") 4399 target_tz = expression.args.get("target_tz") 4400 timestamp = expression.args.get("timestamp") 4401 4402 if source_tz and timestamp: 4403 timestamp = exp.AtTimeZone( 4404 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4405 ) 4406 4407 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4408 4409 return self.sql(expr) 4410 4411 def json_sql(self, expression: exp.JSON) -> str: 4412 this = self.sql(expression, "this") 4413 this = f" {this}" if this else "" 4414 4415 _with = expression.args.get("with") 4416 4417 if _with is None: 4418 with_sql = "" 4419 elif not _with: 4420 with_sql = " WITHOUT" 4421 else: 4422 with_sql = " WITH" 4423 4424 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4425 4426 return f"JSON{this}{with_sql}{unique_sql}" 4427 4428 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4429 def _generate_on_options(arg: t.Any) -> str: 4430 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4431 4432 path = self.sql(expression, "path") 4433 returning = self.sql(expression, "returning") 4434 returning = f" RETURNING {returning}" if returning else "" 4435 4436 on_condition = self.sql(expression, "on_condition") 4437 on_condition = f" {on_condition}" if on_condition else "" 4438 4439 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4440 4441 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4442 else_ = "ELSE " if expression.args.get("else_") else "" 4443 condition = self.sql(expression, "expression") 4444 condition = f"WHEN {condition} THEN " if condition else else_ 4445 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4446 return f"{condition}{insert}" 4447 4448 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4449 kind = self.sql(expression, "kind") 4450 expressions = self.seg(self.expressions(expression, sep=" ")) 4451 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4452 return res 4453 4454 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4455 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4456 empty = expression.args.get("empty") 4457 empty = ( 4458 f"DEFAULT {empty} ON EMPTY" 4459 if isinstance(empty, exp.Expression) 4460 else self.sql(expression, "empty") 4461 ) 4462 4463 error = expression.args.get("error") 4464 error = ( 4465 f"DEFAULT {error} ON ERROR" 4466 if isinstance(error, exp.Expression) 4467 else self.sql(expression, "error") 4468 ) 4469 4470 if error and empty: 4471 error = ( 4472 f"{empty} {error}" 4473 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4474 else f"{error} {empty}" 4475 ) 4476 empty = "" 4477 4478 null = self.sql(expression, "null") 4479 4480 return f"{empty}{error}{null}" 4481 4482 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4483 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4484 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4485 4486 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4487 this = self.sql(expression, "this") 4488 path = self.sql(expression, "path") 4489 4490 passing = self.expressions(expression, "passing") 4491 passing = f" PASSING {passing}" if passing else "" 4492 4493 on_condition = self.sql(expression, "on_condition") 4494 on_condition = f" {on_condition}" if on_condition else "" 4495 4496 path = f"{path}{passing}{on_condition}" 4497 4498 return self.func("JSON_EXISTS", this, path) 4499 4500 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4501 array_agg = self.function_fallback_sql(expression) 4502 4503 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4504 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4505 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4506 parent = expression.parent 4507 if isinstance(parent, exp.Filter): 4508 parent_cond = parent.expression.this 4509 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4510 else: 4511 this = expression.this 4512 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4513 if this.find(exp.Column): 4514 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4515 this_sql = ( 4516 self.expressions(this) 4517 if isinstance(this, exp.Distinct) 4518 else self.sql(expression, "this") 4519 ) 4520 4521 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4522 4523 return array_agg 4524 4525 def apply_sql(self, expression: exp.Apply) -> str: 4526 this = self.sql(expression, "this") 4527 expr = self.sql(expression, "expression") 4528 4529 return f"{this} APPLY({expr})" 4530 4531 def grant_sql(self, expression: exp.Grant) -> str: 4532 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4533 4534 kind = self.sql(expression, "kind") 4535 kind = f" {kind}" if kind else "" 4536 4537 securable = self.sql(expression, "securable") 4538 securable = f" {securable}" if securable else "" 4539 4540 principals = self.expressions(expression, key="principals", flat=True) 4541 4542 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4543 4544 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4545 4546 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4547 this = self.sql(expression, "this") 4548 columns = self.expressions(expression, flat=True) 4549 columns = f"({columns})" if columns else "" 4550 4551 return f"{this}{columns}" 4552 4553 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4554 this = self.sql(expression, "this") 4555 4556 kind = self.sql(expression, "kind") 4557 kind = f"{kind} " if kind else "" 4558 4559 return f"{kind}{this}" 4560 4561 def columns_sql(self, expression: exp.Columns): 4562 func = self.function_fallback_sql(expression) 4563 if expression.args.get("unpack"): 4564 func = f"*{func}" 4565 4566 return func 4567 4568 def overlay_sql(self, expression: exp.Overlay): 4569 this = self.sql(expression, "this") 4570 expr = self.sql(expression, "expression") 4571 from_sql = self.sql(expression, "from") 4572 for_sql = self.sql(expression, "for") 4573 for_sql = f" FOR {for_sql}" if for_sql else "" 4574 4575 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4576 4577 @unsupported_args("format") 4578 def todouble_sql(self, expression: exp.ToDouble) -> str: 4579 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4580 4581 def string_sql(self, expression: exp.String) -> str: 4582 this = expression.this 4583 zone = expression.args.get("zone") 4584 4585 if zone: 4586 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4587 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4588 # set for source_tz to transpile the time conversion before the STRING cast 4589 this = exp.ConvertTimezone( 4590 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4591 ) 4592 4593 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4594 4595 def median_sql(self, expression: exp.Median): 4596 if not self.SUPPORTS_MEDIAN: 4597 return self.sql( 4598 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4599 ) 4600 4601 return self.function_fallback_sql(expression) 4602 4603 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4604 filler = self.sql(expression, "this") 4605 filler = f" {filler}" if filler else "" 4606 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4607 return f"TRUNCATE{filler} {with_count}" 4608 4609 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4610 if self.SUPPORTS_UNIX_SECONDS: 4611 return self.function_fallback_sql(expression) 4612 4613 start_ts = exp.cast( 4614 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4615 ) 4616 4617 return self.sql( 4618 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4619 ) 4620 4621 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4622 dim = expression.expression 4623 4624 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4625 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4626 if not (dim.is_int and dim.name == "1"): 4627 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4628 dim = None 4629 4630 # If dimension is required but not specified, default initialize it 4631 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4632 dim = exp.Literal.number(1) 4633 4634 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4635 4636 def attach_sql(self, expression: exp.Attach) -> str: 4637 this = self.sql(expression, "this") 4638 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4639 expressions = self.expressions(expression) 4640 expressions = f" ({expressions})" if expressions else "" 4641 4642 return f"ATTACH{exists_sql} {this}{expressions}" 4643 4644 def detach_sql(self, expression: exp.Detach) -> str: 4645 this = self.sql(expression, "this") 4646 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4647 4648 return f"DETACH{exists_sql} {this}" 4649 4650 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4651 this = self.sql(expression, "this") 4652 value = self.sql(expression, "expression") 4653 value = f" {value}" if value else "" 4654 return f"{this}{value}" 4655 4656 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4657 this_sql = self.sql(expression, "this") 4658 if isinstance(expression.this, exp.Table): 4659 this_sql = f"TABLE {this_sql}" 4660 4661 return self.func( 4662 "FEATURES_AT_TIME", 4663 this_sql, 4664 expression.args.get("time"), 4665 expression.args.get("num_rows"), 4666 expression.args.get("ignore_feature_nulls"), 4667 ) 4668 4669 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4670 return ( 4671 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4672 ) 4673 4674 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4675 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4676 encode = f"{encode} {self.sql(expression, 'this')}" 4677 4678 properties = expression.args.get("properties") 4679 if properties: 4680 encode = f"{encode} {self.properties(properties)}" 4681 4682 return encode 4683 4684 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4685 this = self.sql(expression, "this") 4686 include = f"INCLUDE {this}" 4687 4688 column_def = self.sql(expression, "column_def") 4689 if column_def: 4690 include = f"{include} {column_def}" 4691 4692 alias = self.sql(expression, "alias") 4693 if alias: 4694 include = f"{include} AS {alias}" 4695 4696 return include 4697 4698 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4699 name = f"NAME {self.sql(expression, 'this')}" 4700 return self.func("XMLELEMENT", name, *expression.expressions) 4701 4702 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4703 partitions = self.expressions(expression, "partition_expressions") 4704 create = self.expressions(expression, "create_expressions") 4705 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4706 4707 def partitionbyrangepropertydynamic_sql( 4708 self, expression: exp.PartitionByRangePropertyDynamic 4709 ) -> str: 4710 start = self.sql(expression, "start") 4711 end = self.sql(expression, "end") 4712 4713 every = expression.args["every"] 4714 if isinstance(every, exp.Interval) and every.this.is_string: 4715 every.this.replace(exp.Literal.number(every.name)) 4716 4717 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4718 4719 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4720 name = self.sql(expression, "this") 4721 values = self.expressions(expression, flat=True) 4722 4723 return f"NAME {name} VALUE {values}" 4724 4725 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4726 kind = self.sql(expression, "kind") 4727 sample = self.sql(expression, "sample") 4728 return f"SAMPLE {sample} {kind}" 4729 4730 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4731 kind = self.sql(expression, "kind") 4732 option = self.sql(expression, "option") 4733 option = f" {option}" if option else "" 4734 this = self.sql(expression, "this") 4735 this = f" {this}" if this else "" 4736 columns = self.expressions(expression) 4737 columns = f" {columns}" if columns else "" 4738 return f"{kind}{option} STATISTICS{this}{columns}" 4739 4740 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4741 this = self.sql(expression, "this") 4742 columns = self.expressions(expression) 4743 inner_expression = self.sql(expression, "expression") 4744 inner_expression = f" {inner_expression}" if inner_expression else "" 4745 update_options = self.sql(expression, "update_options") 4746 update_options = f" {update_options} UPDATE" if update_options else "" 4747 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4748 4749 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4750 kind = self.sql(expression, "kind") 4751 kind = f" {kind}" if kind else "" 4752 return f"DELETE{kind} STATISTICS" 4753 4754 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4755 inner_expression = self.sql(expression, "expression") 4756 return f"LIST CHAINED ROWS{inner_expression}" 4757 4758 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4759 kind = self.sql(expression, "kind") 4760 this = self.sql(expression, "this") 4761 this = f" {this}" if this else "" 4762 inner_expression = self.sql(expression, "expression") 4763 return f"VALIDATE {kind}{this}{inner_expression}" 4764 4765 def analyze_sql(self, expression: exp.Analyze) -> str: 4766 options = self.expressions(expression, key="options", sep=" ") 4767 options = f" {options}" if options else "" 4768 kind = self.sql(expression, "kind") 4769 kind = f" {kind}" if kind else "" 4770 this = self.sql(expression, "this") 4771 this = f" {this}" if this else "" 4772 mode = self.sql(expression, "mode") 4773 mode = f" {mode}" if mode else "" 4774 properties = self.sql(expression, "properties") 4775 properties = f" {properties}" if properties else "" 4776 partition = self.sql(expression, "partition") 4777 partition = f" {partition}" if partition else "" 4778 inner_expression = self.sql(expression, "expression") 4779 inner_expression = f" {inner_expression}" if inner_expression else "" 4780 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4781 4782 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4783 this = self.sql(expression, "this") 4784 namespaces = self.expressions(expression, key="namespaces") 4785 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4786 passing = self.expressions(expression, key="passing") 4787 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4788 columns = self.expressions(expression, key="columns") 4789 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4790 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4791 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4792 4793 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4794 this = self.sql(expression, "this") 4795 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4796 4797 def export_sql(self, expression: exp.Export) -> str: 4798 this = self.sql(expression, "this") 4799 connection = self.sql(expression, "connection") 4800 connection = f"WITH CONNECTION {connection} " if connection else "" 4801 options = self.sql(expression, "options") 4802 return f"EXPORT DATA {connection}{options} AS {this}" 4803 4804 def declare_sql(self, expression: exp.Declare) -> str: 4805 return f"DECLARE {self.expressions(expression, flat=True)}" 4806 4807 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4808 variable = self.sql(expression, "this") 4809 default = self.sql(expression, "default") 4810 default = f" = {default}" if default else "" 4811 4812 kind = self.sql(expression, "kind") 4813 if isinstance(expression.args.get("kind"), exp.Schema): 4814 kind = f"TABLE {kind}" 4815 4816 return f"{variable} AS {kind}{default}" 4817 4818 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4819 kind = self.sql(expression, "kind") 4820 this = self.sql(expression, "this") 4821 set = self.sql(expression, "expression") 4822 using = self.sql(expression, "using") 4823 using = f" USING {using}" if using else "" 4824 4825 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4826 4827 return f"{kind_sql} {this} SET {set}{using}" 4828 4829 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4830 params = self.expressions(expression, key="params", flat=True) 4831 return self.func(expression.name, *expression.expressions) + f"({params})" 4832 4833 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4834 return self.func(expression.name, *expression.expressions) 4835 4836 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4837 return self.anonymousaggfunc_sql(expression) 4838 4839 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4840 return self.parameterizedagg_sql(expression) 4841 4842 def show_sql(self, expression: exp.Show) -> str: 4843 self.unsupported("Unsupported SHOW statement") 4844 return ""
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.CopyGrantsProperty: lambda *_: "COPY GRANTS", 136 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 137 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 138 exp.DynamicProperty: lambda *_: "DYNAMIC", 139 exp.EmptyProperty: lambda *_: "EMPTY", 140 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 141 exp.EphemeralColumnConstraint: lambda self, 142 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 143 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 144 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 145 exp.Except: lambda self, e: self.set_operations(e), 146 exp.ExternalProperty: lambda *_: "EXTERNAL", 147 exp.Floor: lambda self, e: self.ceil_floor(e), 148 exp.GlobalProperty: lambda *_: "GLOBAL", 149 exp.HeapProperty: lambda *_: "HEAP", 150 exp.IcebergProperty: lambda *_: "ICEBERG", 151 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 152 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 153 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 154 exp.Intersect: lambda self, e: self.set_operations(e), 155 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 156 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 157 exp.LanguageProperty: lambda self, e: self.naked_property(e), 158 exp.LocationProperty: lambda self, e: self.naked_property(e), 159 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 160 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 161 exp.NonClusteredColumnConstraint: lambda self, 162 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 163 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 164 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 165 exp.OnCommitProperty: lambda _, 166 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 167 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 168 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 169 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 170 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 171 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 172 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 173 exp.ProjectionPolicyColumnConstraint: lambda self, 174 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 175 exp.RemoteWithConnectionModelProperty: lambda self, 176 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 177 exp.ReturnsProperty: lambda self, e: ( 178 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 179 ), 180 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 181 exp.SecureProperty: lambda *_: "SECURE", 182 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 183 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 184 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 185 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 186 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 187 exp.SqlReadWriteProperty: lambda _, e: e.name, 188 exp.SqlSecurityProperty: lambda _, 189 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 190 exp.StabilityProperty: lambda _, e: e.name, 191 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 192 exp.StreamingTableProperty: lambda *_: "STREAMING", 193 exp.StrictProperty: lambda *_: "STRICT", 194 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 195 exp.TemporaryProperty: lambda *_: "TEMPORARY", 196 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 197 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 198 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 199 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 200 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 201 exp.TransientProperty: lambda *_: "TRANSIENT", 202 exp.Union: lambda self, e: self.set_operations(e), 203 exp.UnloggedProperty: lambda *_: "UNLOGGED", 204 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 205 exp.Uuid: lambda *_: "UUID()", 206 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 207 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 208 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 209 exp.VolatileProperty: lambda *_: "VOLATILE", 210 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 211 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 212 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 213 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 214 } 215 216 # Whether null ordering is supported in order by 217 # True: Full Support, None: No support, False: No support for certain cases 218 # such as window specifications, aggregate functions etc 219 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 220 221 # Whether ignore nulls is inside the agg or outside. 222 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 223 IGNORE_NULLS_IN_FUNC = False 224 225 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 226 LOCKING_READS_SUPPORTED = False 227 228 # Whether the EXCEPT and INTERSECT operations can return duplicates 229 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 230 231 # Wrap derived values in parens, usually standard but spark doesn't support it 232 WRAP_DERIVED_VALUES = True 233 234 # Whether create function uses an AS before the RETURN 235 CREATE_FUNCTION_RETURN_AS = True 236 237 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 238 MATCHED_BY_SOURCE = True 239 240 # Whether the INTERVAL expression works only with values like '1 day' 241 SINGLE_STRING_INTERVAL = False 242 243 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 244 INTERVAL_ALLOWS_PLURAL_FORM = True 245 246 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 247 LIMIT_FETCH = "ALL" 248 249 # Whether limit and fetch allows expresions or just limits 250 LIMIT_ONLY_LITERALS = False 251 252 # Whether a table is allowed to be renamed with a db 253 RENAME_TABLE_WITH_DB = True 254 255 # The separator for grouping sets and rollups 256 GROUPINGS_SEP = "," 257 258 # The string used for creating an index on a table 259 INDEX_ON = "ON" 260 261 # Whether join hints should be generated 262 JOIN_HINTS = True 263 264 # Whether table hints should be generated 265 TABLE_HINTS = True 266 267 # Whether query hints should be generated 268 QUERY_HINTS = True 269 270 # What kind of separator to use for query hints 271 QUERY_HINT_SEP = ", " 272 273 # Whether comparing against booleans (e.g. x IS TRUE) is supported 274 IS_BOOL_ALLOWED = True 275 276 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 277 DUPLICATE_KEY_UPDATE_WITH_SET = True 278 279 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 280 LIMIT_IS_TOP = False 281 282 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 283 RETURNING_END = True 284 285 # Whether to generate an unquoted value for EXTRACT's date part argument 286 EXTRACT_ALLOWS_QUOTES = True 287 288 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 289 TZ_TO_WITH_TIME_ZONE = False 290 291 # Whether the NVL2 function is supported 292 NVL2_SUPPORTED = True 293 294 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 295 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 296 297 # Whether VALUES statements can be used as derived tables. 298 # MySQL 5 and Redshift do not allow this, so when False, it will convert 299 # SELECT * VALUES into SELECT UNION 300 VALUES_AS_TABLE = True 301 302 # Whether the word COLUMN is included when adding a column with ALTER TABLE 303 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 304 305 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 306 UNNEST_WITH_ORDINALITY = True 307 308 # Whether FILTER (WHERE cond) can be used for conditional aggregation 309 AGGREGATE_FILTER_SUPPORTED = True 310 311 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 312 SEMI_ANTI_JOIN_WITH_SIDE = True 313 314 # Whether to include the type of a computed column in the CREATE DDL 315 COMPUTED_COLUMN_WITH_TYPE = True 316 317 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 318 SUPPORTS_TABLE_COPY = True 319 320 # Whether parentheses are required around the table sample's expression 321 TABLESAMPLE_REQUIRES_PARENS = True 322 323 # Whether a table sample clause's size needs to be followed by the ROWS keyword 324 TABLESAMPLE_SIZE_IS_ROWS = True 325 326 # The keyword(s) to use when generating a sample clause 327 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 328 329 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 330 TABLESAMPLE_WITH_METHOD = True 331 332 # The keyword to use when specifying the seed of a sample clause 333 TABLESAMPLE_SEED_KEYWORD = "SEED" 334 335 # Whether COLLATE is a function instead of a binary operator 336 COLLATE_IS_FUNC = False 337 338 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 339 DATA_TYPE_SPECIFIERS_ALLOWED = False 340 341 # Whether conditions require booleans WHERE x = 0 vs WHERE x 342 ENSURE_BOOLS = False 343 344 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 345 CTE_RECURSIVE_KEYWORD_REQUIRED = True 346 347 # Whether CONCAT requires >1 arguments 348 SUPPORTS_SINGLE_ARG_CONCAT = True 349 350 # Whether LAST_DAY function supports a date part argument 351 LAST_DAY_SUPPORTS_DATE_PART = True 352 353 # Whether named columns are allowed in table aliases 354 SUPPORTS_TABLE_ALIAS_COLUMNS = True 355 356 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 357 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 358 359 # What delimiter to use for separating JSON key/value pairs 360 JSON_KEY_VALUE_PAIR_SEP = ":" 361 362 # INSERT OVERWRITE TABLE x override 363 INSERT_OVERWRITE = " OVERWRITE TABLE" 364 365 # Whether the SELECT .. INTO syntax is used instead of CTAS 366 SUPPORTS_SELECT_INTO = False 367 368 # Whether UNLOGGED tables can be created 369 SUPPORTS_UNLOGGED_TABLES = False 370 371 # Whether the CREATE TABLE LIKE statement is supported 372 SUPPORTS_CREATE_TABLE_LIKE = True 373 374 # Whether the LikeProperty needs to be specified inside of the schema clause 375 LIKE_PROPERTY_INSIDE_SCHEMA = False 376 377 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 378 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 379 MULTI_ARG_DISTINCT = True 380 381 # Whether the JSON extraction operators expect a value of type JSON 382 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 383 384 # Whether bracketed keys like ["foo"] are supported in JSON paths 385 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 386 387 # Whether to escape keys using single quotes in JSON paths 388 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 389 390 # The JSONPathPart expressions supported by this dialect 391 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 392 393 # Whether any(f(x) for x in array) can be implemented by this dialect 394 CAN_IMPLEMENT_ARRAY_ANY = False 395 396 # Whether the function TO_NUMBER is supported 397 SUPPORTS_TO_NUMBER = True 398 399 # Whether or not set op modifiers apply to the outer set op or select. 400 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 401 # True means limit 1 happens after the set op, False means it it happens on y. 402 SET_OP_MODIFIERS = True 403 404 # Whether parameters from COPY statement are wrapped in parentheses 405 COPY_PARAMS_ARE_WRAPPED = True 406 407 # Whether values of params are set with "=" token or empty space 408 COPY_PARAMS_EQ_REQUIRED = False 409 410 # Whether COPY statement has INTO keyword 411 COPY_HAS_INTO_KEYWORD = True 412 413 # Whether the conditional TRY(expression) function is supported 414 TRY_SUPPORTED = True 415 416 # Whether the UESCAPE syntax in unicode strings is supported 417 SUPPORTS_UESCAPE = True 418 419 # The keyword to use when generating a star projection with excluded columns 420 STAR_EXCEPT = "EXCEPT" 421 422 # The HEX function name 423 HEX_FUNC = "HEX" 424 425 # The keywords to use when prefixing & separating WITH based properties 426 WITH_PROPERTIES_PREFIX = "WITH" 427 428 # Whether to quote the generated expression of exp.JsonPath 429 QUOTE_JSON_PATH = True 430 431 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 432 PAD_FILL_PATTERN_IS_REQUIRED = False 433 434 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 435 SUPPORTS_EXPLODING_PROJECTIONS = True 436 437 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 438 ARRAY_CONCAT_IS_VAR_LEN = True 439 440 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 441 SUPPORTS_CONVERT_TIMEZONE = False 442 443 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 444 SUPPORTS_MEDIAN = True 445 446 # Whether UNIX_SECONDS(timestamp) is supported 447 SUPPORTS_UNIX_SECONDS = False 448 449 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 450 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 451 452 # The function name of the exp.ArraySize expression 453 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 454 455 # The syntax to use when altering the type of a column 456 ALTER_SET_TYPE = "SET DATA TYPE" 457 458 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 459 # None -> Doesn't support it at all 460 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 461 # True (Postgres) -> Explicitly requires it 462 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 463 464 TYPE_MAPPING = { 465 exp.DataType.Type.DATETIME2: "TIMESTAMP", 466 exp.DataType.Type.NCHAR: "CHAR", 467 exp.DataType.Type.NVARCHAR: "VARCHAR", 468 exp.DataType.Type.MEDIUMTEXT: "TEXT", 469 exp.DataType.Type.LONGTEXT: "TEXT", 470 exp.DataType.Type.TINYTEXT: "TEXT", 471 exp.DataType.Type.MEDIUMBLOB: "BLOB", 472 exp.DataType.Type.LONGBLOB: "BLOB", 473 exp.DataType.Type.TINYBLOB: "BLOB", 474 exp.DataType.Type.INET: "INET", 475 exp.DataType.Type.ROWVERSION: "VARBINARY", 476 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 477 } 478 479 TIME_PART_SINGULARS = { 480 "MICROSECONDS": "MICROSECOND", 481 "SECONDS": "SECOND", 482 "MINUTES": "MINUTE", 483 "HOURS": "HOUR", 484 "DAYS": "DAY", 485 "WEEKS": "WEEK", 486 "MONTHS": "MONTH", 487 "QUARTERS": "QUARTER", 488 "YEARS": "YEAR", 489 } 490 491 AFTER_HAVING_MODIFIER_TRANSFORMS = { 492 "cluster": lambda self, e: self.sql(e, "cluster"), 493 "distribute": lambda self, e: self.sql(e, "distribute"), 494 "sort": lambda self, e: self.sql(e, "sort"), 495 "windows": lambda self, e: ( 496 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 497 if e.args.get("windows") 498 else "" 499 ), 500 "qualify": lambda self, e: self.sql(e, "qualify"), 501 } 502 503 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 504 505 STRUCT_DELIMITER = ("<", ">") 506 507 PARAMETER_TOKEN = "@" 508 NAMED_PLACEHOLDER_TOKEN = ":" 509 510 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 511 512 PROPERTIES_LOCATION = { 513 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 514 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 515 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 519 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 520 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 521 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 524 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 527 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 528 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 529 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 530 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 531 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 532 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 533 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 537 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 540 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 541 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 542 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 543 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 544 exp.HeapProperty: exp.Properties.Location.POST_WITH, 545 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 546 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 547 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 550 exp.JournalProperty: exp.Properties.Location.POST_NAME, 551 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 556 exp.LogProperty: exp.Properties.Location.POST_NAME, 557 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 558 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 559 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 560 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 561 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 562 exp.Order: exp.Properties.Location.POST_SCHEMA, 563 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 564 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 565 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 567 exp.Property: exp.Properties.Location.POST_WITH, 568 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 576 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 577 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 578 exp.Set: exp.Properties.Location.POST_SCHEMA, 579 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 580 exp.SetProperty: exp.Properties.Location.POST_CREATE, 581 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 582 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 583 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 584 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 585 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 586 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 587 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 588 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 589 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.Tags: exp.Properties.Location.POST_WITH, 591 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 592 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 593 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 594 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 595 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 596 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 597 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 598 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 599 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 600 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 601 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 602 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 603 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 604 } 605 606 # Keywords that can't be used as unquoted identifier names 607 RESERVED_KEYWORDS: t.Set[str] = set() 608 609 # Expressions whose comments are separated from them for better formatting 610 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 611 exp.Command, 612 exp.Create, 613 exp.Describe, 614 exp.Delete, 615 exp.Drop, 616 exp.From, 617 exp.Insert, 618 exp.Join, 619 exp.MultitableInserts, 620 exp.Select, 621 exp.SetOperation, 622 exp.Update, 623 exp.Where, 624 exp.With, 625 ) 626 627 # Expressions that should not have their comments generated in maybe_comment 628 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 629 exp.Binary, 630 exp.SetOperation, 631 ) 632 633 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 634 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 635 exp.Column, 636 exp.Literal, 637 exp.Neg, 638 exp.Paren, 639 ) 640 641 PARAMETERIZABLE_TEXT_TYPES = { 642 exp.DataType.Type.NVARCHAR, 643 exp.DataType.Type.VARCHAR, 644 exp.DataType.Type.CHAR, 645 exp.DataType.Type.NCHAR, 646 } 647 648 # Expressions that need to have all CTEs under them bubbled up to them 649 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 650 651 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 652 653 __slots__ = ( 654 "pretty", 655 "identify", 656 "normalize", 657 "pad", 658 "_indent", 659 "normalize_functions", 660 "unsupported_level", 661 "max_unsupported", 662 "leading_comma", 663 "max_text_width", 664 "comments", 665 "dialect", 666 "unsupported_messages", 667 "_escaped_quote_end", 668 "_escaped_identifier_end", 669 "_next_name", 670 "_identifier_start", 671 "_identifier_end", 672 "_quote_json_path_key_using_brackets", 673 ) 674 675 def __init__( 676 self, 677 pretty: t.Optional[bool] = None, 678 identify: str | bool = False, 679 normalize: bool = False, 680 pad: int = 2, 681 indent: int = 2, 682 normalize_functions: t.Optional[str | bool] = None, 683 unsupported_level: ErrorLevel = ErrorLevel.WARN, 684 max_unsupported: int = 3, 685 leading_comma: bool = False, 686 max_text_width: int = 80, 687 comments: bool = True, 688 dialect: DialectType = None, 689 ): 690 import sqlglot 691 from sqlglot.dialects import Dialect 692 693 self.pretty = pretty if pretty is not None else sqlglot.pretty 694 self.identify = identify 695 self.normalize = normalize 696 self.pad = pad 697 self._indent = indent 698 self.unsupported_level = unsupported_level 699 self.max_unsupported = max_unsupported 700 self.leading_comma = leading_comma 701 self.max_text_width = max_text_width 702 self.comments = comments 703 self.dialect = Dialect.get_or_raise(dialect) 704 705 # This is both a Dialect property and a Generator argument, so we prioritize the latter 706 self.normalize_functions = ( 707 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 708 ) 709 710 self.unsupported_messages: t.List[str] = [] 711 self._escaped_quote_end: str = ( 712 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 713 ) 714 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 715 716 self._next_name = name_sequence("_t") 717 718 self._identifier_start = self.dialect.IDENTIFIER_START 719 self._identifier_end = self.dialect.IDENTIFIER_END 720 721 self._quote_json_path_key_using_brackets = True 722 723 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 724 """ 725 Generates the SQL string corresponding to the given syntax tree. 726 727 Args: 728 expression: The syntax tree. 729 copy: Whether to copy the expression. The generator performs mutations so 730 it is safer to copy. 731 732 Returns: 733 The SQL string corresponding to `expression`. 734 """ 735 if copy: 736 expression = expression.copy() 737 738 expression = self.preprocess(expression) 739 740 self.unsupported_messages = [] 741 sql = self.sql(expression).strip() 742 743 if self.pretty: 744 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 745 746 if self.unsupported_level == ErrorLevel.IGNORE: 747 return sql 748 749 if self.unsupported_level == ErrorLevel.WARN: 750 for msg in self.unsupported_messages: 751 logger.warning(msg) 752 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 753 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 754 755 return sql 756 757 def preprocess(self, expression: exp.Expression) -> exp.Expression: 758 """Apply generic preprocessing transformations to a given expression.""" 759 expression = self._move_ctes_to_top_level(expression) 760 761 if self.ENSURE_BOOLS: 762 from sqlglot.transforms import ensure_bools 763 764 expression = ensure_bools(expression) 765 766 return expression 767 768 def _move_ctes_to_top_level(self, expression: E) -> E: 769 if ( 770 not expression.parent 771 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 772 and any(node.parent is not expression for node in expression.find_all(exp.With)) 773 ): 774 from sqlglot.transforms import move_ctes_to_top_level 775 776 expression = move_ctes_to_top_level(expression) 777 return expression 778 779 def unsupported(self, message: str) -> None: 780 if self.unsupported_level == ErrorLevel.IMMEDIATE: 781 raise UnsupportedError(message) 782 self.unsupported_messages.append(message) 783 784 def sep(self, sep: str = " ") -> str: 785 return f"{sep.strip()}\n" if self.pretty else sep 786 787 def seg(self, sql: str, sep: str = " ") -> str: 788 return f"{self.sep(sep)}{sql}" 789 790 def pad_comment(self, comment: str) -> str: 791 comment = " " + comment if comment[0].strip() else comment 792 comment = comment + " " if comment[-1].strip() else comment 793 return comment 794 795 def maybe_comment( 796 self, 797 sql: str, 798 expression: t.Optional[exp.Expression] = None, 799 comments: t.Optional[t.List[str]] = None, 800 separated: bool = False, 801 ) -> str: 802 comments = ( 803 ((expression and expression.comments) if comments is None else comments) # type: ignore 804 if self.comments 805 else None 806 ) 807 808 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 809 return sql 810 811 comments_sql = " ".join( 812 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 813 ) 814 815 if not comments_sql: 816 return sql 817 818 comments_sql = self._replace_line_breaks(comments_sql) 819 820 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 821 return ( 822 f"{self.sep()}{comments_sql}{sql}" 823 if not sql or sql[0].isspace() 824 else f"{comments_sql}{self.sep()}{sql}" 825 ) 826 827 return f"{sql} {comments_sql}" 828 829 def wrap(self, expression: exp.Expression | str) -> str: 830 this_sql = ( 831 self.sql(expression) 832 if isinstance(expression, exp.UNWRAPPED_QUERIES) 833 else self.sql(expression, "this") 834 ) 835 if not this_sql: 836 return "()" 837 838 this_sql = self.indent(this_sql, level=1, pad=0) 839 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 840 841 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 842 original = self.identify 843 self.identify = False 844 result = func(*args, **kwargs) 845 self.identify = original 846 return result 847 848 def normalize_func(self, name: str) -> str: 849 if self.normalize_functions == "upper" or self.normalize_functions is True: 850 return name.upper() 851 if self.normalize_functions == "lower": 852 return name.lower() 853 return name 854 855 def indent( 856 self, 857 sql: str, 858 level: int = 0, 859 pad: t.Optional[int] = None, 860 skip_first: bool = False, 861 skip_last: bool = False, 862 ) -> str: 863 if not self.pretty or not sql: 864 return sql 865 866 pad = self.pad if pad is None else pad 867 lines = sql.split("\n") 868 869 return "\n".join( 870 ( 871 line 872 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 873 else f"{' ' * (level * self._indent + pad)}{line}" 874 ) 875 for i, line in enumerate(lines) 876 ) 877 878 def sql( 879 self, 880 expression: t.Optional[str | exp.Expression], 881 key: t.Optional[str] = None, 882 comment: bool = True, 883 ) -> str: 884 if not expression: 885 return "" 886 887 if isinstance(expression, str): 888 return expression 889 890 if key: 891 value = expression.args.get(key) 892 if value: 893 return self.sql(value) 894 return "" 895 896 transform = self.TRANSFORMS.get(expression.__class__) 897 898 if callable(transform): 899 sql = transform(self, expression) 900 elif isinstance(expression, exp.Expression): 901 exp_handler_name = f"{expression.key}_sql" 902 903 if hasattr(self, exp_handler_name): 904 sql = getattr(self, exp_handler_name)(expression) 905 elif isinstance(expression, exp.Func): 906 sql = self.function_fallback_sql(expression) 907 elif isinstance(expression, exp.Property): 908 sql = self.property_sql(expression) 909 else: 910 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 911 else: 912 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 913 914 return self.maybe_comment(sql, expression) if self.comments and comment else sql 915 916 def uncache_sql(self, expression: exp.Uncache) -> str: 917 table = self.sql(expression, "this") 918 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 919 return f"UNCACHE TABLE{exists_sql} {table}" 920 921 def cache_sql(self, expression: exp.Cache) -> str: 922 lazy = " LAZY" if expression.args.get("lazy") else "" 923 table = self.sql(expression, "this") 924 options = expression.args.get("options") 925 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 926 sql = self.sql(expression, "expression") 927 sql = f" AS{self.sep()}{sql}" if sql else "" 928 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 929 return self.prepend_ctes(expression, sql) 930 931 def characterset_sql(self, expression: exp.CharacterSet) -> str: 932 if isinstance(expression.parent, exp.Cast): 933 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 934 default = "DEFAULT " if expression.args.get("default") else "" 935 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 936 937 def column_parts(self, expression: exp.Column) -> str: 938 return ".".join( 939 self.sql(part) 940 for part in ( 941 expression.args.get("catalog"), 942 expression.args.get("db"), 943 expression.args.get("table"), 944 expression.args.get("this"), 945 ) 946 if part 947 ) 948 949 def column_sql(self, expression: exp.Column) -> str: 950 join_mark = " (+)" if expression.args.get("join_mark") else "" 951 952 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 953 join_mark = "" 954 self.unsupported("Outer join syntax using the (+) operator is not supported.") 955 956 return f"{self.column_parts(expression)}{join_mark}" 957 958 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 959 this = self.sql(expression, "this") 960 this = f" {this}" if this else "" 961 position = self.sql(expression, "position") 962 return f"{position}{this}" 963 964 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 965 column = self.sql(expression, "this") 966 kind = self.sql(expression, "kind") 967 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 968 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 969 kind = f"{sep}{kind}" if kind else "" 970 constraints = f" {constraints}" if constraints else "" 971 position = self.sql(expression, "position") 972 position = f" {position}" if position else "" 973 974 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 975 kind = "" 976 977 return f"{exists}{column}{kind}{constraints}{position}" 978 979 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 980 this = self.sql(expression, "this") 981 kind_sql = self.sql(expression, "kind").strip() 982 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 983 984 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 985 this = self.sql(expression, "this") 986 if expression.args.get("not_null"): 987 persisted = " PERSISTED NOT NULL" 988 elif expression.args.get("persisted"): 989 persisted = " PERSISTED" 990 else: 991 persisted = "" 992 return f"AS {this}{persisted}" 993 994 def autoincrementcolumnconstraint_sql(self, _) -> str: 995 return self.token_sql(TokenType.AUTO_INCREMENT) 996 997 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 998 if isinstance(expression.this, list): 999 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1000 else: 1001 this = self.sql(expression, "this") 1002 1003 return f"COMPRESS {this}" 1004 1005 def generatedasidentitycolumnconstraint_sql( 1006 self, expression: exp.GeneratedAsIdentityColumnConstraint 1007 ) -> str: 1008 this = "" 1009 if expression.this is not None: 1010 on_null = " ON NULL" if expression.args.get("on_null") else "" 1011 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1012 1013 start = expression.args.get("start") 1014 start = f"START WITH {start}" if start else "" 1015 increment = expression.args.get("increment") 1016 increment = f" INCREMENT BY {increment}" if increment else "" 1017 minvalue = expression.args.get("minvalue") 1018 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1019 maxvalue = expression.args.get("maxvalue") 1020 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1021 cycle = expression.args.get("cycle") 1022 cycle_sql = "" 1023 1024 if cycle is not None: 1025 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1026 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1027 1028 sequence_opts = "" 1029 if start or increment or cycle_sql: 1030 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1031 sequence_opts = f" ({sequence_opts.strip()})" 1032 1033 expr = self.sql(expression, "expression") 1034 expr = f"({expr})" if expr else "IDENTITY" 1035 1036 return f"GENERATED{this} AS {expr}{sequence_opts}" 1037 1038 def generatedasrowcolumnconstraint_sql( 1039 self, expression: exp.GeneratedAsRowColumnConstraint 1040 ) -> str: 1041 start = "START" if expression.args.get("start") else "END" 1042 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1043 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1044 1045 def periodforsystemtimeconstraint_sql( 1046 self, expression: exp.PeriodForSystemTimeConstraint 1047 ) -> str: 1048 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1049 1050 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1051 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1052 1053 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1054 return f"AS {self.sql(expression, 'this')}" 1055 1056 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1057 desc = expression.args.get("desc") 1058 if desc is not None: 1059 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1060 return "PRIMARY KEY" 1061 1062 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1063 this = self.sql(expression, "this") 1064 this = f" {this}" if this else "" 1065 index_type = expression.args.get("index_type") 1066 index_type = f" USING {index_type}" if index_type else "" 1067 on_conflict = self.sql(expression, "on_conflict") 1068 on_conflict = f" {on_conflict}" if on_conflict else "" 1069 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1070 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1071 1072 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1073 return self.sql(expression, "this") 1074 1075 def create_sql(self, expression: exp.Create) -> str: 1076 kind = self.sql(expression, "kind") 1077 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1078 properties = expression.args.get("properties") 1079 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1080 1081 this = self.createable_sql(expression, properties_locs) 1082 1083 properties_sql = "" 1084 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1085 exp.Properties.Location.POST_WITH 1086 ): 1087 properties_sql = self.sql( 1088 exp.Properties( 1089 expressions=[ 1090 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1091 *properties_locs[exp.Properties.Location.POST_WITH], 1092 ] 1093 ) 1094 ) 1095 1096 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1097 properties_sql = self.sep() + properties_sql 1098 elif not self.pretty: 1099 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1100 properties_sql = f" {properties_sql}" 1101 1102 begin = " BEGIN" if expression.args.get("begin") else "" 1103 end = " END" if expression.args.get("end") else "" 1104 1105 expression_sql = self.sql(expression, "expression") 1106 if expression_sql: 1107 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1108 1109 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1110 postalias_props_sql = "" 1111 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1112 postalias_props_sql = self.properties( 1113 exp.Properties( 1114 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1115 ), 1116 wrapped=False, 1117 ) 1118 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1119 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1120 1121 postindex_props_sql = "" 1122 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1123 postindex_props_sql = self.properties( 1124 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1125 wrapped=False, 1126 prefix=" ", 1127 ) 1128 1129 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1130 indexes = f" {indexes}" if indexes else "" 1131 index_sql = indexes + postindex_props_sql 1132 1133 replace = " OR REPLACE" if expression.args.get("replace") else "" 1134 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1135 unique = " UNIQUE" if expression.args.get("unique") else "" 1136 1137 clustered = expression.args.get("clustered") 1138 if clustered is None: 1139 clustered_sql = "" 1140 elif clustered: 1141 clustered_sql = " CLUSTERED COLUMNSTORE" 1142 else: 1143 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1144 1145 postcreate_props_sql = "" 1146 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1147 postcreate_props_sql = self.properties( 1148 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1149 sep=" ", 1150 prefix=" ", 1151 wrapped=False, 1152 ) 1153 1154 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1155 1156 postexpression_props_sql = "" 1157 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1158 postexpression_props_sql = self.properties( 1159 exp.Properties( 1160 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1161 ), 1162 sep=" ", 1163 prefix=" ", 1164 wrapped=False, 1165 ) 1166 1167 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1168 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1169 no_schema_binding = ( 1170 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1171 ) 1172 1173 clone = self.sql(expression, "clone") 1174 clone = f" {clone}" if clone else "" 1175 1176 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1177 properties_expression = f"{expression_sql}{properties_sql}" 1178 else: 1179 properties_expression = f"{properties_sql}{expression_sql}" 1180 1181 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1182 return self.prepend_ctes(expression, expression_sql) 1183 1184 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1185 start = self.sql(expression, "start") 1186 start = f"START WITH {start}" if start else "" 1187 increment = self.sql(expression, "increment") 1188 increment = f" INCREMENT BY {increment}" if increment else "" 1189 minvalue = self.sql(expression, "minvalue") 1190 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1191 maxvalue = self.sql(expression, "maxvalue") 1192 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1193 owned = self.sql(expression, "owned") 1194 owned = f" OWNED BY {owned}" if owned else "" 1195 1196 cache = expression.args.get("cache") 1197 if cache is None: 1198 cache_str = "" 1199 elif cache is True: 1200 cache_str = " CACHE" 1201 else: 1202 cache_str = f" CACHE {cache}" 1203 1204 options = self.expressions(expression, key="options", flat=True, sep=" ") 1205 options = f" {options}" if options else "" 1206 1207 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1208 1209 def clone_sql(self, expression: exp.Clone) -> str: 1210 this = self.sql(expression, "this") 1211 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1212 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1213 return f"{shallow}{keyword} {this}" 1214 1215 def describe_sql(self, expression: exp.Describe) -> str: 1216 style = expression.args.get("style") 1217 style = f" {style}" if style else "" 1218 partition = self.sql(expression, "partition") 1219 partition = f" {partition}" if partition else "" 1220 format = self.sql(expression, "format") 1221 format = f" {format}" if format else "" 1222 1223 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1224 1225 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1226 tag = self.sql(expression, "tag") 1227 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1228 1229 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1230 with_ = self.sql(expression, "with") 1231 if with_: 1232 sql = f"{with_}{self.sep()}{sql}" 1233 return sql 1234 1235 def with_sql(self, expression: exp.With) -> str: 1236 sql = self.expressions(expression, flat=True) 1237 recursive = ( 1238 "RECURSIVE " 1239 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1240 else "" 1241 ) 1242 search = self.sql(expression, "search") 1243 search = f" {search}" if search else "" 1244 1245 return f"WITH {recursive}{sql}{search}" 1246 1247 def cte_sql(self, expression: exp.CTE) -> str: 1248 alias = expression.args.get("alias") 1249 if alias: 1250 alias.add_comments(expression.pop_comments()) 1251 1252 alias_sql = self.sql(expression, "alias") 1253 1254 materialized = expression.args.get("materialized") 1255 if materialized is False: 1256 materialized = "NOT MATERIALIZED " 1257 elif materialized: 1258 materialized = "MATERIALIZED " 1259 1260 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1261 1262 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1263 alias = self.sql(expression, "this") 1264 columns = self.expressions(expression, key="columns", flat=True) 1265 columns = f"({columns})" if columns else "" 1266 1267 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1268 columns = "" 1269 self.unsupported("Named columns are not supported in table alias.") 1270 1271 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1272 alias = self._next_name() 1273 1274 return f"{alias}{columns}" 1275 1276 def bitstring_sql(self, expression: exp.BitString) -> str: 1277 this = self.sql(expression, "this") 1278 if self.dialect.BIT_START: 1279 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1280 return f"{int(this, 2)}" 1281 1282 def hexstring_sql( 1283 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1284 ) -> str: 1285 this = self.sql(expression, "this") 1286 is_integer_type = expression.args.get("is_integer") 1287 1288 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1289 not self.dialect.HEX_START and not binary_function_repr 1290 ): 1291 # Integer representation will be returned if: 1292 # - The read dialect treats the hex value as integer literal but not the write 1293 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1294 return f"{int(this, 16)}" 1295 1296 if not is_integer_type: 1297 # Read dialect treats the hex value as BINARY/BLOB 1298 if binary_function_repr: 1299 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1300 return self.func(binary_function_repr, exp.Literal.string(this)) 1301 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1302 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1303 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1304 1305 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1306 1307 def bytestring_sql(self, expression: exp.ByteString) -> str: 1308 this = self.sql(expression, "this") 1309 if self.dialect.BYTE_START: 1310 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1311 return this 1312 1313 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1314 this = self.sql(expression, "this") 1315 escape = expression.args.get("escape") 1316 1317 if self.dialect.UNICODE_START: 1318 escape_substitute = r"\\\1" 1319 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1320 else: 1321 escape_substitute = r"\\u\1" 1322 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1323 1324 if escape: 1325 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1326 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1327 else: 1328 escape_pattern = ESCAPED_UNICODE_RE 1329 escape_sql = "" 1330 1331 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1332 this = escape_pattern.sub(escape_substitute, this) 1333 1334 return f"{left_quote}{this}{right_quote}{escape_sql}" 1335 1336 def rawstring_sql(self, expression: exp.RawString) -> str: 1337 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1338 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1339 1340 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1341 this = self.sql(expression, "this") 1342 specifier = self.sql(expression, "expression") 1343 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1344 return f"{this}{specifier}" 1345 1346 def datatype_sql(self, expression: exp.DataType) -> str: 1347 nested = "" 1348 values = "" 1349 interior = self.expressions(expression, flat=True) 1350 1351 type_value = expression.this 1352 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1353 type_sql = self.sql(expression, "kind") 1354 else: 1355 type_sql = ( 1356 self.TYPE_MAPPING.get(type_value, type_value.value) 1357 if isinstance(type_value, exp.DataType.Type) 1358 else type_value 1359 ) 1360 1361 if interior: 1362 if expression.args.get("nested"): 1363 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1364 if expression.args.get("values") is not None: 1365 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1366 values = self.expressions(expression, key="values", flat=True) 1367 values = f"{delimiters[0]}{values}{delimiters[1]}" 1368 elif type_value == exp.DataType.Type.INTERVAL: 1369 nested = f" {interior}" 1370 else: 1371 nested = f"({interior})" 1372 1373 type_sql = f"{type_sql}{nested}{values}" 1374 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1375 exp.DataType.Type.TIMETZ, 1376 exp.DataType.Type.TIMESTAMPTZ, 1377 ): 1378 type_sql = f"{type_sql} WITH TIME ZONE" 1379 1380 return type_sql 1381 1382 def directory_sql(self, expression: exp.Directory) -> str: 1383 local = "LOCAL " if expression.args.get("local") else "" 1384 row_format = self.sql(expression, "row_format") 1385 row_format = f" {row_format}" if row_format else "" 1386 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1387 1388 def delete_sql(self, expression: exp.Delete) -> str: 1389 this = self.sql(expression, "this") 1390 this = f" FROM {this}" if this else "" 1391 using = self.sql(expression, "using") 1392 using = f" USING {using}" if using else "" 1393 cluster = self.sql(expression, "cluster") 1394 cluster = f" {cluster}" if cluster else "" 1395 where = self.sql(expression, "where") 1396 returning = self.sql(expression, "returning") 1397 limit = self.sql(expression, "limit") 1398 tables = self.expressions(expression, key="tables") 1399 tables = f" {tables}" if tables else "" 1400 if self.RETURNING_END: 1401 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1402 else: 1403 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1404 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1405 1406 def drop_sql(self, expression: exp.Drop) -> str: 1407 this = self.sql(expression, "this") 1408 expressions = self.expressions(expression, flat=True) 1409 expressions = f" ({expressions})" if expressions else "" 1410 kind = expression.args["kind"] 1411 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1412 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1413 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1414 on_cluster = self.sql(expression, "cluster") 1415 on_cluster = f" {on_cluster}" if on_cluster else "" 1416 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1417 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1418 cascade = " CASCADE" if expression.args.get("cascade") else "" 1419 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1420 purge = " PURGE" if expression.args.get("purge") else "" 1421 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1422 1423 def set_operation(self, expression: exp.SetOperation) -> str: 1424 op_type = type(expression) 1425 op_name = op_type.key.upper() 1426 1427 distinct = expression.args.get("distinct") 1428 if ( 1429 distinct is False 1430 and op_type in (exp.Except, exp.Intersect) 1431 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1432 ): 1433 self.unsupported(f"{op_name} ALL is not supported") 1434 1435 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1436 1437 if distinct is None: 1438 distinct = default_distinct 1439 if distinct is None: 1440 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1441 1442 if distinct is default_distinct: 1443 kind = "" 1444 else: 1445 kind = " DISTINCT" if distinct else " ALL" 1446 1447 by_name = " BY NAME" if expression.args.get("by_name") else "" 1448 return f"{op_name}{kind}{by_name}" 1449 1450 def set_operations(self, expression: exp.SetOperation) -> str: 1451 if not self.SET_OP_MODIFIERS: 1452 limit = expression.args.get("limit") 1453 order = expression.args.get("order") 1454 1455 if limit or order: 1456 select = self._move_ctes_to_top_level( 1457 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1458 ) 1459 1460 if limit: 1461 select = select.limit(limit.pop(), copy=False) 1462 if order: 1463 select = select.order_by(order.pop(), copy=False) 1464 return self.sql(select) 1465 1466 sqls: t.List[str] = [] 1467 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1468 1469 while stack: 1470 node = stack.pop() 1471 1472 if isinstance(node, exp.SetOperation): 1473 stack.append(node.expression) 1474 stack.append( 1475 self.maybe_comment( 1476 self.set_operation(node), comments=node.comments, separated=True 1477 ) 1478 ) 1479 stack.append(node.this) 1480 else: 1481 sqls.append(self.sql(node)) 1482 1483 this = self.sep().join(sqls) 1484 this = self.query_modifiers(expression, this) 1485 return self.prepend_ctes(expression, this) 1486 1487 def fetch_sql(self, expression: exp.Fetch) -> str: 1488 direction = expression.args.get("direction") 1489 direction = f" {direction}" if direction else "" 1490 count = self.sql(expression, "count") 1491 count = f" {count}" if count else "" 1492 limit_options = self.sql(expression, "limit_options") 1493 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1494 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1495 1496 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1497 percent = " PERCENT" if expression.args.get("percent") else "" 1498 rows = " ROWS" if expression.args.get("rows") else "" 1499 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1500 if not with_ties and rows: 1501 with_ties = " ONLY" 1502 return f"{percent}{rows}{with_ties}" 1503 1504 def filter_sql(self, expression: exp.Filter) -> str: 1505 if self.AGGREGATE_FILTER_SUPPORTED: 1506 this = self.sql(expression, "this") 1507 where = self.sql(expression, "expression").strip() 1508 return f"{this} FILTER({where})" 1509 1510 agg = expression.this 1511 agg_arg = agg.this 1512 cond = expression.expression.this 1513 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1514 return self.sql(agg) 1515 1516 def hint_sql(self, expression: exp.Hint) -> str: 1517 if not self.QUERY_HINTS: 1518 self.unsupported("Hints are not supported") 1519 return "" 1520 1521 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1522 1523 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1524 using = self.sql(expression, "using") 1525 using = f" USING {using}" if using else "" 1526 columns = self.expressions(expression, key="columns", flat=True) 1527 columns = f"({columns})" if columns else "" 1528 partition_by = self.expressions(expression, key="partition_by", flat=True) 1529 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1530 where = self.sql(expression, "where") 1531 include = self.expressions(expression, key="include", flat=True) 1532 if include: 1533 include = f" INCLUDE ({include})" 1534 with_storage = self.expressions(expression, key="with_storage", flat=True) 1535 with_storage = f" WITH ({with_storage})" if with_storage else "" 1536 tablespace = self.sql(expression, "tablespace") 1537 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1538 on = self.sql(expression, "on") 1539 on = f" ON {on}" if on else "" 1540 1541 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1542 1543 def index_sql(self, expression: exp.Index) -> str: 1544 unique = "UNIQUE " if expression.args.get("unique") else "" 1545 primary = "PRIMARY " if expression.args.get("primary") else "" 1546 amp = "AMP " if expression.args.get("amp") else "" 1547 name = self.sql(expression, "this") 1548 name = f"{name} " if name else "" 1549 table = self.sql(expression, "table") 1550 table = f"{self.INDEX_ON} {table}" if table else "" 1551 1552 index = "INDEX " if not table else "" 1553 1554 params = self.sql(expression, "params") 1555 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1556 1557 def identifier_sql(self, expression: exp.Identifier) -> str: 1558 text = expression.name 1559 lower = text.lower() 1560 text = lower if self.normalize and not expression.quoted else text 1561 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1562 if ( 1563 expression.quoted 1564 or self.dialect.can_identify(text, self.identify) 1565 or lower in self.RESERVED_KEYWORDS 1566 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1567 ): 1568 text = f"{self._identifier_start}{text}{self._identifier_end}" 1569 return text 1570 1571 def hex_sql(self, expression: exp.Hex) -> str: 1572 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1573 if self.dialect.HEX_LOWERCASE: 1574 text = self.func("LOWER", text) 1575 1576 return text 1577 1578 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1579 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1580 if not self.dialect.HEX_LOWERCASE: 1581 text = self.func("LOWER", text) 1582 return text 1583 1584 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1585 input_format = self.sql(expression, "input_format") 1586 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1587 output_format = self.sql(expression, "output_format") 1588 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1589 return self.sep().join((input_format, output_format)) 1590 1591 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1592 string = self.sql(exp.Literal.string(expression.name)) 1593 return f"{prefix}{string}" 1594 1595 def partition_sql(self, expression: exp.Partition) -> str: 1596 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1597 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1598 1599 def properties_sql(self, expression: exp.Properties) -> str: 1600 root_properties = [] 1601 with_properties = [] 1602 1603 for p in expression.expressions: 1604 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1605 if p_loc == exp.Properties.Location.POST_WITH: 1606 with_properties.append(p) 1607 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1608 root_properties.append(p) 1609 1610 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1611 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1612 1613 if root_props and with_props and not self.pretty: 1614 with_props = " " + with_props 1615 1616 return root_props + with_props 1617 1618 def root_properties(self, properties: exp.Properties) -> str: 1619 if properties.expressions: 1620 return self.expressions(properties, indent=False, sep=" ") 1621 return "" 1622 1623 def properties( 1624 self, 1625 properties: exp.Properties, 1626 prefix: str = "", 1627 sep: str = ", ", 1628 suffix: str = "", 1629 wrapped: bool = True, 1630 ) -> str: 1631 if properties.expressions: 1632 expressions = self.expressions(properties, sep=sep, indent=False) 1633 if expressions: 1634 expressions = self.wrap(expressions) if wrapped else expressions 1635 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1636 return "" 1637 1638 def with_properties(self, properties: exp.Properties) -> str: 1639 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1640 1641 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1642 properties_locs = defaultdict(list) 1643 for p in properties.expressions: 1644 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1645 if p_loc != exp.Properties.Location.UNSUPPORTED: 1646 properties_locs[p_loc].append(p) 1647 else: 1648 self.unsupported(f"Unsupported property {p.key}") 1649 1650 return properties_locs 1651 1652 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1653 if isinstance(expression.this, exp.Dot): 1654 return self.sql(expression, "this") 1655 return f"'{expression.name}'" if string_key else expression.name 1656 1657 def property_sql(self, expression: exp.Property) -> str: 1658 property_cls = expression.__class__ 1659 if property_cls == exp.Property: 1660 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1661 1662 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1663 if not property_name: 1664 self.unsupported(f"Unsupported property {expression.key}") 1665 1666 return f"{property_name}={self.sql(expression, 'this')}" 1667 1668 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1669 if self.SUPPORTS_CREATE_TABLE_LIKE: 1670 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1671 options = f" {options}" if options else "" 1672 1673 like = f"LIKE {self.sql(expression, 'this')}{options}" 1674 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1675 like = f"({like})" 1676 1677 return like 1678 1679 if expression.expressions: 1680 self.unsupported("Transpilation of LIKE property options is unsupported") 1681 1682 select = exp.select("*").from_(expression.this).limit(0) 1683 return f"AS {self.sql(select)}" 1684 1685 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1686 no = "NO " if expression.args.get("no") else "" 1687 protection = " PROTECTION" if expression.args.get("protection") else "" 1688 return f"{no}FALLBACK{protection}" 1689 1690 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1691 no = "NO " if expression.args.get("no") else "" 1692 local = expression.args.get("local") 1693 local = f"{local} " if local else "" 1694 dual = "DUAL " if expression.args.get("dual") else "" 1695 before = "BEFORE " if expression.args.get("before") else "" 1696 after = "AFTER " if expression.args.get("after") else "" 1697 return f"{no}{local}{dual}{before}{after}JOURNAL" 1698 1699 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1700 freespace = self.sql(expression, "this") 1701 percent = " PERCENT" if expression.args.get("percent") else "" 1702 return f"FREESPACE={freespace}{percent}" 1703 1704 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1705 if expression.args.get("default"): 1706 property = "DEFAULT" 1707 elif expression.args.get("on"): 1708 property = "ON" 1709 else: 1710 property = "OFF" 1711 return f"CHECKSUM={property}" 1712 1713 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1714 if expression.args.get("no"): 1715 return "NO MERGEBLOCKRATIO" 1716 if expression.args.get("default"): 1717 return "DEFAULT MERGEBLOCKRATIO" 1718 1719 percent = " PERCENT" if expression.args.get("percent") else "" 1720 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1721 1722 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1723 default = expression.args.get("default") 1724 minimum = expression.args.get("minimum") 1725 maximum = expression.args.get("maximum") 1726 if default or minimum or maximum: 1727 if default: 1728 prop = "DEFAULT" 1729 elif minimum: 1730 prop = "MINIMUM" 1731 else: 1732 prop = "MAXIMUM" 1733 return f"{prop} DATABLOCKSIZE" 1734 units = expression.args.get("units") 1735 units = f" {units}" if units else "" 1736 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1737 1738 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1739 autotemp = expression.args.get("autotemp") 1740 always = expression.args.get("always") 1741 default = expression.args.get("default") 1742 manual = expression.args.get("manual") 1743 never = expression.args.get("never") 1744 1745 if autotemp is not None: 1746 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1747 elif always: 1748 prop = "ALWAYS" 1749 elif default: 1750 prop = "DEFAULT" 1751 elif manual: 1752 prop = "MANUAL" 1753 elif never: 1754 prop = "NEVER" 1755 return f"BLOCKCOMPRESSION={prop}" 1756 1757 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1758 no = expression.args.get("no") 1759 no = " NO" if no else "" 1760 concurrent = expression.args.get("concurrent") 1761 concurrent = " CONCURRENT" if concurrent else "" 1762 target = self.sql(expression, "target") 1763 target = f" {target}" if target else "" 1764 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1765 1766 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1767 if isinstance(expression.this, list): 1768 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1769 if expression.this: 1770 modulus = self.sql(expression, "this") 1771 remainder = self.sql(expression, "expression") 1772 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1773 1774 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1775 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1776 return f"FROM ({from_expressions}) TO ({to_expressions})" 1777 1778 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1779 this = self.sql(expression, "this") 1780 1781 for_values_or_default = expression.expression 1782 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1783 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1784 else: 1785 for_values_or_default = " DEFAULT" 1786 1787 return f"PARTITION OF {this}{for_values_or_default}" 1788 1789 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1790 kind = expression.args.get("kind") 1791 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1792 for_or_in = expression.args.get("for_or_in") 1793 for_or_in = f" {for_or_in}" if for_or_in else "" 1794 lock_type = expression.args.get("lock_type") 1795 override = " OVERRIDE" if expression.args.get("override") else "" 1796 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1797 1798 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1799 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1800 statistics = expression.args.get("statistics") 1801 statistics_sql = "" 1802 if statistics is not None: 1803 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1804 return f"{data_sql}{statistics_sql}" 1805 1806 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1807 this = self.sql(expression, "this") 1808 this = f"HISTORY_TABLE={this}" if this else "" 1809 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1810 data_consistency = ( 1811 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1812 ) 1813 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1814 retention_period = ( 1815 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1816 ) 1817 1818 if this: 1819 on_sql = self.func("ON", this, data_consistency, retention_period) 1820 else: 1821 on_sql = "ON" if expression.args.get("on") else "OFF" 1822 1823 sql = f"SYSTEM_VERSIONING={on_sql}" 1824 1825 return f"WITH({sql})" if expression.args.get("with") else sql 1826 1827 def insert_sql(self, expression: exp.Insert) -> str: 1828 hint = self.sql(expression, "hint") 1829 overwrite = expression.args.get("overwrite") 1830 1831 if isinstance(expression.this, exp.Directory): 1832 this = " OVERWRITE" if overwrite else " INTO" 1833 else: 1834 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1835 1836 stored = self.sql(expression, "stored") 1837 stored = f" {stored}" if stored else "" 1838 alternative = expression.args.get("alternative") 1839 alternative = f" OR {alternative}" if alternative else "" 1840 ignore = " IGNORE" if expression.args.get("ignore") else "" 1841 is_function = expression.args.get("is_function") 1842 if is_function: 1843 this = f"{this} FUNCTION" 1844 this = f"{this} {self.sql(expression, 'this')}" 1845 1846 exists = " IF EXISTS" if expression.args.get("exists") else "" 1847 where = self.sql(expression, "where") 1848 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1849 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1850 on_conflict = self.sql(expression, "conflict") 1851 on_conflict = f" {on_conflict}" if on_conflict else "" 1852 by_name = " BY NAME" if expression.args.get("by_name") else "" 1853 returning = self.sql(expression, "returning") 1854 1855 if self.RETURNING_END: 1856 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1857 else: 1858 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1859 1860 partition_by = self.sql(expression, "partition") 1861 partition_by = f" {partition_by}" if partition_by else "" 1862 settings = self.sql(expression, "settings") 1863 settings = f" {settings}" if settings else "" 1864 1865 source = self.sql(expression, "source") 1866 source = f"TABLE {source}" if source else "" 1867 1868 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1869 return self.prepend_ctes(expression, sql) 1870 1871 def introducer_sql(self, expression: exp.Introducer) -> str: 1872 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1873 1874 def kill_sql(self, expression: exp.Kill) -> str: 1875 kind = self.sql(expression, "kind") 1876 kind = f" {kind}" if kind else "" 1877 this = self.sql(expression, "this") 1878 this = f" {this}" if this else "" 1879 return f"KILL{kind}{this}" 1880 1881 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1882 return expression.name 1883 1884 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1885 return expression.name 1886 1887 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1888 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1889 1890 constraint = self.sql(expression, "constraint") 1891 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1892 1893 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1894 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1895 action = self.sql(expression, "action") 1896 1897 expressions = self.expressions(expression, flat=True) 1898 if expressions: 1899 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1900 expressions = f" {set_keyword}{expressions}" 1901 1902 where = self.sql(expression, "where") 1903 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1904 1905 def returning_sql(self, expression: exp.Returning) -> str: 1906 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1907 1908 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1909 fields = self.sql(expression, "fields") 1910 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1911 escaped = self.sql(expression, "escaped") 1912 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1913 items = self.sql(expression, "collection_items") 1914 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1915 keys = self.sql(expression, "map_keys") 1916 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1917 lines = self.sql(expression, "lines") 1918 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1919 null = self.sql(expression, "null") 1920 null = f" NULL DEFINED AS {null}" if null else "" 1921 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1922 1923 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1924 return f"WITH ({self.expressions(expression, flat=True)})" 1925 1926 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1927 this = f"{self.sql(expression, 'this')} INDEX" 1928 target = self.sql(expression, "target") 1929 target = f" FOR {target}" if target else "" 1930 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1931 1932 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1933 this = self.sql(expression, "this") 1934 kind = self.sql(expression, "kind") 1935 expr = self.sql(expression, "expression") 1936 return f"{this} ({kind} => {expr})" 1937 1938 def table_parts(self, expression: exp.Table) -> str: 1939 return ".".join( 1940 self.sql(part) 1941 for part in ( 1942 expression.args.get("catalog"), 1943 expression.args.get("db"), 1944 expression.args.get("this"), 1945 ) 1946 if part is not None 1947 ) 1948 1949 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1950 table = self.table_parts(expression) 1951 only = "ONLY " if expression.args.get("only") else "" 1952 partition = self.sql(expression, "partition") 1953 partition = f" {partition}" if partition else "" 1954 version = self.sql(expression, "version") 1955 version = f" {version}" if version else "" 1956 alias = self.sql(expression, "alias") 1957 alias = f"{sep}{alias}" if alias else "" 1958 1959 sample = self.sql(expression, "sample") 1960 if self.dialect.ALIAS_POST_TABLESAMPLE: 1961 sample_pre_alias = sample 1962 sample_post_alias = "" 1963 else: 1964 sample_pre_alias = "" 1965 sample_post_alias = sample 1966 1967 hints = self.expressions(expression, key="hints", sep=" ") 1968 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1969 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1970 joins = self.indent( 1971 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1972 ) 1973 laterals = self.expressions(expression, key="laterals", sep="") 1974 1975 file_format = self.sql(expression, "format") 1976 if file_format: 1977 pattern = self.sql(expression, "pattern") 1978 pattern = f", PATTERN => {pattern}" if pattern else "" 1979 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1980 1981 ordinality = expression.args.get("ordinality") or "" 1982 if ordinality: 1983 ordinality = f" WITH ORDINALITY{alias}" 1984 alias = "" 1985 1986 when = self.sql(expression, "when") 1987 if when: 1988 table = f"{table} {when}" 1989 1990 changes = self.sql(expression, "changes") 1991 changes = f" {changes}" if changes else "" 1992 1993 rows_from = self.expressions(expression, key="rows_from") 1994 if rows_from: 1995 table = f"ROWS FROM {self.wrap(rows_from)}" 1996 1997 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1998 1999 def tablesample_sql( 2000 self, 2001 expression: exp.TableSample, 2002 tablesample_keyword: t.Optional[str] = None, 2003 ) -> str: 2004 method = self.sql(expression, "method") 2005 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2006 numerator = self.sql(expression, "bucket_numerator") 2007 denominator = self.sql(expression, "bucket_denominator") 2008 field = self.sql(expression, "bucket_field") 2009 field = f" ON {field}" if field else "" 2010 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2011 seed = self.sql(expression, "seed") 2012 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2013 2014 size = self.sql(expression, "size") 2015 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2016 size = f"{size} ROWS" 2017 2018 percent = self.sql(expression, "percent") 2019 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2020 percent = f"{percent} PERCENT" 2021 2022 expr = f"{bucket}{percent}{size}" 2023 if self.TABLESAMPLE_REQUIRES_PARENS: 2024 expr = f"({expr})" 2025 2026 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2027 2028 def pivot_sql(self, expression: exp.Pivot) -> str: 2029 expressions = self.expressions(expression, flat=True) 2030 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2031 2032 if expression.this: 2033 this = self.sql(expression, "this") 2034 if not expressions: 2035 return f"UNPIVOT {this}" 2036 2037 on = f"{self.seg('ON')} {expressions}" 2038 into = self.sql(expression, "into") 2039 into = f"{self.seg('INTO')} {into}" if into else "" 2040 using = self.expressions(expression, key="using", flat=True) 2041 using = f"{self.seg('USING')} {using}" if using else "" 2042 group = self.sql(expression, "group") 2043 return f"{direction} {this}{on}{into}{using}{group}" 2044 2045 alias = self.sql(expression, "alias") 2046 alias = f" AS {alias}" if alias else "" 2047 2048 field = self.sql(expression, "field") 2049 2050 include_nulls = expression.args.get("include_nulls") 2051 if include_nulls is not None: 2052 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2053 else: 2054 nulls = "" 2055 2056 default_on_null = self.sql(expression, "default_on_null") 2057 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2058 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2059 2060 def version_sql(self, expression: exp.Version) -> str: 2061 this = f"FOR {expression.name}" 2062 kind = expression.text("kind") 2063 expr = self.sql(expression, "expression") 2064 return f"{this} {kind} {expr}" 2065 2066 def tuple_sql(self, expression: exp.Tuple) -> str: 2067 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2068 2069 def update_sql(self, expression: exp.Update) -> str: 2070 this = self.sql(expression, "this") 2071 set_sql = self.expressions(expression, flat=True) 2072 from_sql = self.sql(expression, "from") 2073 where_sql = self.sql(expression, "where") 2074 returning = self.sql(expression, "returning") 2075 order = self.sql(expression, "order") 2076 limit = self.sql(expression, "limit") 2077 if self.RETURNING_END: 2078 expression_sql = f"{from_sql}{where_sql}{returning}" 2079 else: 2080 expression_sql = f"{returning}{from_sql}{where_sql}" 2081 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2082 return self.prepend_ctes(expression, sql) 2083 2084 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2085 values_as_table = values_as_table and self.VALUES_AS_TABLE 2086 2087 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2088 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2089 args = self.expressions(expression) 2090 alias = self.sql(expression, "alias") 2091 values = f"VALUES{self.seg('')}{args}" 2092 values = ( 2093 f"({values})" 2094 if self.WRAP_DERIVED_VALUES 2095 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2096 else values 2097 ) 2098 return f"{values} AS {alias}" if alias else values 2099 2100 # Converts `VALUES...` expression into a series of select unions. 2101 alias_node = expression.args.get("alias") 2102 column_names = alias_node and alias_node.columns 2103 2104 selects: t.List[exp.Query] = [] 2105 2106 for i, tup in enumerate(expression.expressions): 2107 row = tup.expressions 2108 2109 if i == 0 and column_names: 2110 row = [ 2111 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2112 ] 2113 2114 selects.append(exp.Select(expressions=row)) 2115 2116 if self.pretty: 2117 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2118 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2119 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2120 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2121 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2122 2123 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2124 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2125 return f"({unions}){alias}" 2126 2127 def var_sql(self, expression: exp.Var) -> str: 2128 return self.sql(expression, "this") 2129 2130 @unsupported_args("expressions") 2131 def into_sql(self, expression: exp.Into) -> str: 2132 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2133 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2134 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2135 2136 def from_sql(self, expression: exp.From) -> str: 2137 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2138 2139 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2140 grouping_sets = self.expressions(expression, indent=False) 2141 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2142 2143 def rollup_sql(self, expression: exp.Rollup) -> str: 2144 expressions = self.expressions(expression, indent=False) 2145 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2146 2147 def cube_sql(self, expression: exp.Cube) -> str: 2148 expressions = self.expressions(expression, indent=False) 2149 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2150 2151 def group_sql(self, expression: exp.Group) -> str: 2152 group_by_all = expression.args.get("all") 2153 if group_by_all is True: 2154 modifier = " ALL" 2155 elif group_by_all is False: 2156 modifier = " DISTINCT" 2157 else: 2158 modifier = "" 2159 2160 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2161 2162 grouping_sets = self.expressions(expression, key="grouping_sets") 2163 cube = self.expressions(expression, key="cube") 2164 rollup = self.expressions(expression, key="rollup") 2165 2166 groupings = csv( 2167 self.seg(grouping_sets) if grouping_sets else "", 2168 self.seg(cube) if cube else "", 2169 self.seg(rollup) if rollup else "", 2170 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2171 sep=self.GROUPINGS_SEP, 2172 ) 2173 2174 if ( 2175 expression.expressions 2176 and groupings 2177 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2178 ): 2179 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2180 2181 return f"{group_by}{groupings}" 2182 2183 def having_sql(self, expression: exp.Having) -> str: 2184 this = self.indent(self.sql(expression, "this")) 2185 return f"{self.seg('HAVING')}{self.sep()}{this}" 2186 2187 def connect_sql(self, expression: exp.Connect) -> str: 2188 start = self.sql(expression, "start") 2189 start = self.seg(f"START WITH {start}") if start else "" 2190 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2191 connect = self.sql(expression, "connect") 2192 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2193 return start + connect 2194 2195 def prior_sql(self, expression: exp.Prior) -> str: 2196 return f"PRIOR {self.sql(expression, 'this')}" 2197 2198 def join_sql(self, expression: exp.Join) -> str: 2199 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2200 side = None 2201 else: 2202 side = expression.side 2203 2204 op_sql = " ".join( 2205 op 2206 for op in ( 2207 expression.method, 2208 "GLOBAL" if expression.args.get("global") else None, 2209 side, 2210 expression.kind, 2211 expression.hint if self.JOIN_HINTS else None, 2212 ) 2213 if op 2214 ) 2215 match_cond = self.sql(expression, "match_condition") 2216 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2217 on_sql = self.sql(expression, "on") 2218 using = expression.args.get("using") 2219 2220 if not on_sql and using: 2221 on_sql = csv(*(self.sql(column) for column in using)) 2222 2223 this = expression.this 2224 this_sql = self.sql(this) 2225 2226 exprs = self.expressions(expression) 2227 if exprs: 2228 this_sql = f"{this_sql},{self.seg(exprs)}" 2229 2230 if on_sql: 2231 on_sql = self.indent(on_sql, skip_first=True) 2232 space = self.seg(" " * self.pad) if self.pretty else " " 2233 if using: 2234 on_sql = f"{space}USING ({on_sql})" 2235 else: 2236 on_sql = f"{space}ON {on_sql}" 2237 elif not op_sql: 2238 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2239 return f" {this_sql}" 2240 2241 return f", {this_sql}" 2242 2243 if op_sql != "STRAIGHT_JOIN": 2244 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2245 2246 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2247 2248 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2249 args = self.expressions(expression, flat=True) 2250 args = f"({args})" if len(args.split(",")) > 1 else args 2251 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2252 2253 def lateral_op(self, expression: exp.Lateral) -> str: 2254 cross_apply = expression.args.get("cross_apply") 2255 2256 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2257 if cross_apply is True: 2258 op = "INNER JOIN " 2259 elif cross_apply is False: 2260 op = "LEFT JOIN " 2261 else: 2262 op = "" 2263 2264 return f"{op}LATERAL" 2265 2266 def lateral_sql(self, expression: exp.Lateral) -> str: 2267 this = self.sql(expression, "this") 2268 2269 if expression.args.get("view"): 2270 alias = expression.args["alias"] 2271 columns = self.expressions(alias, key="columns", flat=True) 2272 table = f" {alias.name}" if alias.name else "" 2273 columns = f" AS {columns}" if columns else "" 2274 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2275 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2276 2277 alias = self.sql(expression, "alias") 2278 alias = f" AS {alias}" if alias else "" 2279 return f"{self.lateral_op(expression)} {this}{alias}" 2280 2281 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2282 this = self.sql(expression, "this") 2283 2284 args = [ 2285 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2286 for e in (expression.args.get(k) for k in ("offset", "expression")) 2287 if e 2288 ] 2289 2290 args_sql = ", ".join(self.sql(e) for e in args) 2291 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2292 expressions = self.expressions(expression, flat=True) 2293 limit_options = self.sql(expression, "limit_options") 2294 expressions = f" BY {expressions}" if expressions else "" 2295 2296 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2297 2298 def offset_sql(self, expression: exp.Offset) -> str: 2299 this = self.sql(expression, "this") 2300 value = expression.expression 2301 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2302 expressions = self.expressions(expression, flat=True) 2303 expressions = f" BY {expressions}" if expressions else "" 2304 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2305 2306 def setitem_sql(self, expression: exp.SetItem) -> str: 2307 kind = self.sql(expression, "kind") 2308 kind = f"{kind} " if kind else "" 2309 this = self.sql(expression, "this") 2310 expressions = self.expressions(expression) 2311 collate = self.sql(expression, "collate") 2312 collate = f" COLLATE {collate}" if collate else "" 2313 global_ = "GLOBAL " if expression.args.get("global") else "" 2314 return f"{global_}{kind}{this}{expressions}{collate}" 2315 2316 def set_sql(self, expression: exp.Set) -> str: 2317 expressions = f" {self.expressions(expression, flat=True)}" 2318 tag = " TAG" if expression.args.get("tag") else "" 2319 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2320 2321 def pragma_sql(self, expression: exp.Pragma) -> str: 2322 return f"PRAGMA {self.sql(expression, 'this')}" 2323 2324 def lock_sql(self, expression: exp.Lock) -> str: 2325 if not self.LOCKING_READS_SUPPORTED: 2326 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2327 return "" 2328 2329 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2330 expressions = self.expressions(expression, flat=True) 2331 expressions = f" OF {expressions}" if expressions else "" 2332 wait = expression.args.get("wait") 2333 2334 if wait is not None: 2335 if isinstance(wait, exp.Literal): 2336 wait = f" WAIT {self.sql(wait)}" 2337 else: 2338 wait = " NOWAIT" if wait else " SKIP LOCKED" 2339 2340 return f"{lock_type}{expressions}{wait or ''}" 2341 2342 def literal_sql(self, expression: exp.Literal) -> str: 2343 text = expression.this or "" 2344 if expression.is_string: 2345 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2346 return text 2347 2348 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2349 if self.dialect.ESCAPED_SEQUENCES: 2350 to_escaped = self.dialect.ESCAPED_SEQUENCES 2351 text = "".join( 2352 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2353 ) 2354 2355 return self._replace_line_breaks(text).replace( 2356 self.dialect.QUOTE_END, self._escaped_quote_end 2357 ) 2358 2359 def loaddata_sql(self, expression: exp.LoadData) -> str: 2360 local = " LOCAL" if expression.args.get("local") else "" 2361 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2362 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2363 this = f" INTO TABLE {self.sql(expression, 'this')}" 2364 partition = self.sql(expression, "partition") 2365 partition = f" {partition}" if partition else "" 2366 input_format = self.sql(expression, "input_format") 2367 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2368 serde = self.sql(expression, "serde") 2369 serde = f" SERDE {serde}" if serde else "" 2370 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2371 2372 def null_sql(self, *_) -> str: 2373 return "NULL" 2374 2375 def boolean_sql(self, expression: exp.Boolean) -> str: 2376 return "TRUE" if expression.this else "FALSE" 2377 2378 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2379 this = self.sql(expression, "this") 2380 this = f"{this} " if this else this 2381 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2382 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2383 2384 def withfill_sql(self, expression: exp.WithFill) -> str: 2385 from_sql = self.sql(expression, "from") 2386 from_sql = f" FROM {from_sql}" if from_sql else "" 2387 to_sql = self.sql(expression, "to") 2388 to_sql = f" TO {to_sql}" if to_sql else "" 2389 step_sql = self.sql(expression, "step") 2390 step_sql = f" STEP {step_sql}" if step_sql else "" 2391 interpolated_values = [ 2392 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2393 if isinstance(e, exp.Alias) 2394 else self.sql(e, "this") 2395 for e in expression.args.get("interpolate") or [] 2396 ] 2397 interpolate = ( 2398 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2399 ) 2400 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2401 2402 def cluster_sql(self, expression: exp.Cluster) -> str: 2403 return self.op_expressions("CLUSTER BY", expression) 2404 2405 def distribute_sql(self, expression: exp.Distribute) -> str: 2406 return self.op_expressions("DISTRIBUTE BY", expression) 2407 2408 def sort_sql(self, expression: exp.Sort) -> str: 2409 return self.op_expressions("SORT BY", expression) 2410 2411 def ordered_sql(self, expression: exp.Ordered) -> str: 2412 desc = expression.args.get("desc") 2413 asc = not desc 2414 2415 nulls_first = expression.args.get("nulls_first") 2416 nulls_last = not nulls_first 2417 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2418 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2419 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2420 2421 this = self.sql(expression, "this") 2422 2423 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2424 nulls_sort_change = "" 2425 if nulls_first and ( 2426 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2427 ): 2428 nulls_sort_change = " NULLS FIRST" 2429 elif ( 2430 nulls_last 2431 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2432 and not nulls_are_last 2433 ): 2434 nulls_sort_change = " NULLS LAST" 2435 2436 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2437 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2438 window = expression.find_ancestor(exp.Window, exp.Select) 2439 if isinstance(window, exp.Window) and window.args.get("spec"): 2440 self.unsupported( 2441 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2442 ) 2443 nulls_sort_change = "" 2444 elif self.NULL_ORDERING_SUPPORTED is False and ( 2445 (asc and nulls_sort_change == " NULLS LAST") 2446 or (desc and nulls_sort_change == " NULLS FIRST") 2447 ): 2448 # BigQuery does not allow these ordering/nulls combinations when used under 2449 # an aggregation func or under a window containing one 2450 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2451 2452 if isinstance(ancestor, exp.Window): 2453 ancestor = ancestor.this 2454 if isinstance(ancestor, exp.AggFunc): 2455 self.unsupported( 2456 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2457 ) 2458 nulls_sort_change = "" 2459 elif self.NULL_ORDERING_SUPPORTED is None: 2460 if expression.this.is_int: 2461 self.unsupported( 2462 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2463 ) 2464 elif not isinstance(expression.this, exp.Rand): 2465 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2466 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2467 nulls_sort_change = "" 2468 2469 with_fill = self.sql(expression, "with_fill") 2470 with_fill = f" {with_fill}" if with_fill else "" 2471 2472 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2473 2474 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2475 window_frame = self.sql(expression, "window_frame") 2476 window_frame = f"{window_frame} " if window_frame else "" 2477 2478 this = self.sql(expression, "this") 2479 2480 return f"{window_frame}{this}" 2481 2482 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2483 partition = self.partition_by_sql(expression) 2484 order = self.sql(expression, "order") 2485 measures = self.expressions(expression, key="measures") 2486 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2487 rows = self.sql(expression, "rows") 2488 rows = self.seg(rows) if rows else "" 2489 after = self.sql(expression, "after") 2490 after = self.seg(after) if after else "" 2491 pattern = self.sql(expression, "pattern") 2492 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2493 definition_sqls = [ 2494 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2495 for definition in expression.args.get("define", []) 2496 ] 2497 definitions = self.expressions(sqls=definition_sqls) 2498 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2499 body = "".join( 2500 ( 2501 partition, 2502 order, 2503 measures, 2504 rows, 2505 after, 2506 pattern, 2507 define, 2508 ) 2509 ) 2510 alias = self.sql(expression, "alias") 2511 alias = f" {alias}" if alias else "" 2512 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2513 2514 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2515 limit = expression.args.get("limit") 2516 2517 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2518 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2519 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2520 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2521 2522 return csv( 2523 *sqls, 2524 *[self.sql(join) for join in expression.args.get("joins") or []], 2525 self.sql(expression, "match"), 2526 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2527 self.sql(expression, "prewhere"), 2528 self.sql(expression, "where"), 2529 self.sql(expression, "connect"), 2530 self.sql(expression, "group"), 2531 self.sql(expression, "having"), 2532 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2533 self.sql(expression, "order"), 2534 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2535 *self.after_limit_modifiers(expression), 2536 self.options_modifier(expression), 2537 sep="", 2538 ) 2539 2540 def options_modifier(self, expression: exp.Expression) -> str: 2541 options = self.expressions(expression, key="options") 2542 return f" {options}" if options else "" 2543 2544 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2545 return "" 2546 2547 def offset_limit_modifiers( 2548 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2549 ) -> t.List[str]: 2550 return [ 2551 self.sql(expression, "offset") if fetch else self.sql(limit), 2552 self.sql(limit) if fetch else self.sql(expression, "offset"), 2553 ] 2554 2555 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2556 locks = self.expressions(expression, key="locks", sep=" ") 2557 locks = f" {locks}" if locks else "" 2558 return [locks, self.sql(expression, "sample")] 2559 2560 def select_sql(self, expression: exp.Select) -> str: 2561 into = expression.args.get("into") 2562 if not self.SUPPORTS_SELECT_INTO and into: 2563 into.pop() 2564 2565 hint = self.sql(expression, "hint") 2566 distinct = self.sql(expression, "distinct") 2567 distinct = f" {distinct}" if distinct else "" 2568 kind = self.sql(expression, "kind") 2569 2570 limit = expression.args.get("limit") 2571 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2572 top = self.limit_sql(limit, top=True) 2573 limit.pop() 2574 else: 2575 top = "" 2576 2577 expressions = self.expressions(expression) 2578 2579 if kind: 2580 if kind in self.SELECT_KINDS: 2581 kind = f" AS {kind}" 2582 else: 2583 if kind == "STRUCT": 2584 expressions = self.expressions( 2585 sqls=[ 2586 self.sql( 2587 exp.Struct( 2588 expressions=[ 2589 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2590 if isinstance(e, exp.Alias) 2591 else e 2592 for e in expression.expressions 2593 ] 2594 ) 2595 ) 2596 ] 2597 ) 2598 kind = "" 2599 2600 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2601 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2602 2603 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2604 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2605 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2606 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2607 sql = self.query_modifiers( 2608 expression, 2609 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2610 self.sql(expression, "into", comment=False), 2611 self.sql(expression, "from", comment=False), 2612 ) 2613 2614 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2615 if expression.args.get("with"): 2616 sql = self.maybe_comment(sql, expression) 2617 expression.pop_comments() 2618 2619 sql = self.prepend_ctes(expression, sql) 2620 2621 if not self.SUPPORTS_SELECT_INTO and into: 2622 if into.args.get("temporary"): 2623 table_kind = " TEMPORARY" 2624 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2625 table_kind = " UNLOGGED" 2626 else: 2627 table_kind = "" 2628 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2629 2630 return sql 2631 2632 def schema_sql(self, expression: exp.Schema) -> str: 2633 this = self.sql(expression, "this") 2634 sql = self.schema_columns_sql(expression) 2635 return f"{this} {sql}" if this and sql else this or sql 2636 2637 def schema_columns_sql(self, expression: exp.Schema) -> str: 2638 if expression.expressions: 2639 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2640 return "" 2641 2642 def star_sql(self, expression: exp.Star) -> str: 2643 except_ = self.expressions(expression, key="except", flat=True) 2644 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2645 replace = self.expressions(expression, key="replace", flat=True) 2646 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2647 rename = self.expressions(expression, key="rename", flat=True) 2648 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2649 return f"*{except_}{replace}{rename}" 2650 2651 def parameter_sql(self, expression: exp.Parameter) -> str: 2652 this = self.sql(expression, "this") 2653 return f"{self.PARAMETER_TOKEN}{this}" 2654 2655 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2656 this = self.sql(expression, "this") 2657 kind = expression.text("kind") 2658 if kind: 2659 kind = f"{kind}." 2660 return f"@@{kind}{this}" 2661 2662 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2663 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2664 2665 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2666 alias = self.sql(expression, "alias") 2667 alias = f"{sep}{alias}" if alias else "" 2668 sample = self.sql(expression, "sample") 2669 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2670 alias = f"{sample}{alias}" 2671 2672 # Set to None so it's not generated again by self.query_modifiers() 2673 expression.set("sample", None) 2674 2675 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2676 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2677 return self.prepend_ctes(expression, sql) 2678 2679 def qualify_sql(self, expression: exp.Qualify) -> str: 2680 this = self.indent(self.sql(expression, "this")) 2681 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2682 2683 def unnest_sql(self, expression: exp.Unnest) -> str: 2684 args = self.expressions(expression, flat=True) 2685 2686 alias = expression.args.get("alias") 2687 offset = expression.args.get("offset") 2688 2689 if self.UNNEST_WITH_ORDINALITY: 2690 if alias and isinstance(offset, exp.Expression): 2691 alias.append("columns", offset) 2692 2693 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2694 columns = alias.columns 2695 alias = self.sql(columns[0]) if columns else "" 2696 else: 2697 alias = self.sql(alias) 2698 2699 alias = f" AS {alias}" if alias else alias 2700 if self.UNNEST_WITH_ORDINALITY: 2701 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2702 else: 2703 if isinstance(offset, exp.Expression): 2704 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2705 elif offset: 2706 suffix = f"{alias} WITH OFFSET" 2707 else: 2708 suffix = alias 2709 2710 return f"UNNEST({args}){suffix}" 2711 2712 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2713 return "" 2714 2715 def where_sql(self, expression: exp.Where) -> str: 2716 this = self.indent(self.sql(expression, "this")) 2717 return f"{self.seg('WHERE')}{self.sep()}{this}" 2718 2719 def window_sql(self, expression: exp.Window) -> str: 2720 this = self.sql(expression, "this") 2721 partition = self.partition_by_sql(expression) 2722 order = expression.args.get("order") 2723 order = self.order_sql(order, flat=True) if order else "" 2724 spec = self.sql(expression, "spec") 2725 alias = self.sql(expression, "alias") 2726 over = self.sql(expression, "over") or "OVER" 2727 2728 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2729 2730 first = expression.args.get("first") 2731 if first is None: 2732 first = "" 2733 else: 2734 first = "FIRST" if first else "LAST" 2735 2736 if not partition and not order and not spec and alias: 2737 return f"{this} {alias}" 2738 2739 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2740 return f"{this} ({args})" 2741 2742 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2743 partition = self.expressions(expression, key="partition_by", flat=True) 2744 return f"PARTITION BY {partition}" if partition else "" 2745 2746 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2747 kind = self.sql(expression, "kind") 2748 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2749 end = ( 2750 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2751 or "CURRENT ROW" 2752 ) 2753 return f"{kind} BETWEEN {start} AND {end}" 2754 2755 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2756 this = self.sql(expression, "this") 2757 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2758 return f"{this} WITHIN GROUP ({expression_sql})" 2759 2760 def between_sql(self, expression: exp.Between) -> str: 2761 this = self.sql(expression, "this") 2762 low = self.sql(expression, "low") 2763 high = self.sql(expression, "high") 2764 return f"{this} BETWEEN {low} AND {high}" 2765 2766 def bracket_offset_expressions( 2767 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2768 ) -> t.List[exp.Expression]: 2769 return apply_index_offset( 2770 expression.this, 2771 expression.expressions, 2772 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2773 ) 2774 2775 def bracket_sql(self, expression: exp.Bracket) -> str: 2776 expressions = self.bracket_offset_expressions(expression) 2777 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2778 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2779 2780 def all_sql(self, expression: exp.All) -> str: 2781 return f"ALL {self.wrap(expression)}" 2782 2783 def any_sql(self, expression: exp.Any) -> str: 2784 this = self.sql(expression, "this") 2785 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2786 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2787 this = self.wrap(this) 2788 return f"ANY{this}" 2789 return f"ANY {this}" 2790 2791 def exists_sql(self, expression: exp.Exists) -> str: 2792 return f"EXISTS{self.wrap(expression)}" 2793 2794 def case_sql(self, expression: exp.Case) -> str: 2795 this = self.sql(expression, "this") 2796 statements = [f"CASE {this}" if this else "CASE"] 2797 2798 for e in expression.args["ifs"]: 2799 statements.append(f"WHEN {self.sql(e, 'this')}") 2800 statements.append(f"THEN {self.sql(e, 'true')}") 2801 2802 default = self.sql(expression, "default") 2803 2804 if default: 2805 statements.append(f"ELSE {default}") 2806 2807 statements.append("END") 2808 2809 if self.pretty and self.too_wide(statements): 2810 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2811 2812 return " ".join(statements) 2813 2814 def constraint_sql(self, expression: exp.Constraint) -> str: 2815 this = self.sql(expression, "this") 2816 expressions = self.expressions(expression, flat=True) 2817 return f"CONSTRAINT {this} {expressions}" 2818 2819 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2820 order = expression.args.get("order") 2821 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2822 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2823 2824 def extract_sql(self, expression: exp.Extract) -> str: 2825 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2826 expression_sql = self.sql(expression, "expression") 2827 return f"EXTRACT({this} FROM {expression_sql})" 2828 2829 def trim_sql(self, expression: exp.Trim) -> str: 2830 trim_type = self.sql(expression, "position") 2831 2832 if trim_type == "LEADING": 2833 func_name = "LTRIM" 2834 elif trim_type == "TRAILING": 2835 func_name = "RTRIM" 2836 else: 2837 func_name = "TRIM" 2838 2839 return self.func(func_name, expression.this, expression.expression) 2840 2841 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2842 args = expression.expressions 2843 if isinstance(expression, exp.ConcatWs): 2844 args = args[1:] # Skip the delimiter 2845 2846 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2847 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2848 2849 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2850 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2851 2852 return args 2853 2854 def concat_sql(self, expression: exp.Concat) -> str: 2855 expressions = self.convert_concat_args(expression) 2856 2857 # Some dialects don't allow a single-argument CONCAT call 2858 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2859 return self.sql(expressions[0]) 2860 2861 return self.func("CONCAT", *expressions) 2862 2863 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2864 return self.func( 2865 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2866 ) 2867 2868 def check_sql(self, expression: exp.Check) -> str: 2869 this = self.sql(expression, key="this") 2870 return f"CHECK ({this})" 2871 2872 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2873 expressions = self.expressions(expression, flat=True) 2874 expressions = f" ({expressions})" if expressions else "" 2875 reference = self.sql(expression, "reference") 2876 reference = f" {reference}" if reference else "" 2877 delete = self.sql(expression, "delete") 2878 delete = f" ON DELETE {delete}" if delete else "" 2879 update = self.sql(expression, "update") 2880 update = f" ON UPDATE {update}" if update else "" 2881 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2882 2883 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2884 expressions = self.expressions(expression, flat=True) 2885 options = self.expressions(expression, key="options", flat=True, sep=" ") 2886 options = f" {options}" if options else "" 2887 return f"PRIMARY KEY ({expressions}){options}" 2888 2889 def if_sql(self, expression: exp.If) -> str: 2890 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2891 2892 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2893 modifier = expression.args.get("modifier") 2894 modifier = f" {modifier}" if modifier else "" 2895 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2896 2897 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2898 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2899 2900 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2901 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2902 2903 if expression.args.get("escape"): 2904 path = self.escape_str(path) 2905 2906 if self.QUOTE_JSON_PATH: 2907 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2908 2909 return path 2910 2911 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2912 if isinstance(expression, exp.JSONPathPart): 2913 transform = self.TRANSFORMS.get(expression.__class__) 2914 if not callable(transform): 2915 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2916 return "" 2917 2918 return transform(self, expression) 2919 2920 if isinstance(expression, int): 2921 return str(expression) 2922 2923 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2924 escaped = expression.replace("'", "\\'") 2925 escaped = f"\\'{expression}\\'" 2926 else: 2927 escaped = expression.replace('"', '\\"') 2928 escaped = f'"{escaped}"' 2929 2930 return escaped 2931 2932 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2933 return f"{self.sql(expression, 'this')} FORMAT JSON" 2934 2935 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2936 null_handling = expression.args.get("null_handling") 2937 null_handling = f" {null_handling}" if null_handling else "" 2938 2939 unique_keys = expression.args.get("unique_keys") 2940 if unique_keys is not None: 2941 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2942 else: 2943 unique_keys = "" 2944 2945 return_type = self.sql(expression, "return_type") 2946 return_type = f" RETURNING {return_type}" if return_type else "" 2947 encoding = self.sql(expression, "encoding") 2948 encoding = f" ENCODING {encoding}" if encoding else "" 2949 2950 return self.func( 2951 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2952 *expression.expressions, 2953 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2954 ) 2955 2956 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2957 return self.jsonobject_sql(expression) 2958 2959 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2960 null_handling = expression.args.get("null_handling") 2961 null_handling = f" {null_handling}" if null_handling else "" 2962 return_type = self.sql(expression, "return_type") 2963 return_type = f" RETURNING {return_type}" if return_type else "" 2964 strict = " STRICT" if expression.args.get("strict") else "" 2965 return self.func( 2966 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2967 ) 2968 2969 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2970 this = self.sql(expression, "this") 2971 order = self.sql(expression, "order") 2972 null_handling = expression.args.get("null_handling") 2973 null_handling = f" {null_handling}" if null_handling else "" 2974 return_type = self.sql(expression, "return_type") 2975 return_type = f" RETURNING {return_type}" if return_type else "" 2976 strict = " STRICT" if expression.args.get("strict") else "" 2977 return self.func( 2978 "JSON_ARRAYAGG", 2979 this, 2980 suffix=f"{order}{null_handling}{return_type}{strict})", 2981 ) 2982 2983 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2984 path = self.sql(expression, "path") 2985 path = f" PATH {path}" if path else "" 2986 nested_schema = self.sql(expression, "nested_schema") 2987 2988 if nested_schema: 2989 return f"NESTED{path} {nested_schema}" 2990 2991 this = self.sql(expression, "this") 2992 kind = self.sql(expression, "kind") 2993 kind = f" {kind}" if kind else "" 2994 return f"{this}{kind}{path}" 2995 2996 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2997 return self.func("COLUMNS", *expression.expressions) 2998 2999 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3000 this = self.sql(expression, "this") 3001 path = self.sql(expression, "path") 3002 path = f", {path}" if path else "" 3003 error_handling = expression.args.get("error_handling") 3004 error_handling = f" {error_handling}" if error_handling else "" 3005 empty_handling = expression.args.get("empty_handling") 3006 empty_handling = f" {empty_handling}" if empty_handling else "" 3007 schema = self.sql(expression, "schema") 3008 return self.func( 3009 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3010 ) 3011 3012 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3013 this = self.sql(expression, "this") 3014 kind = self.sql(expression, "kind") 3015 path = self.sql(expression, "path") 3016 path = f" {path}" if path else "" 3017 as_json = " AS JSON" if expression.args.get("as_json") else "" 3018 return f"{this} {kind}{path}{as_json}" 3019 3020 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3021 this = self.sql(expression, "this") 3022 path = self.sql(expression, "path") 3023 path = f", {path}" if path else "" 3024 expressions = self.expressions(expression) 3025 with_ = ( 3026 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3027 if expressions 3028 else "" 3029 ) 3030 return f"OPENJSON({this}{path}){with_}" 3031 3032 def in_sql(self, expression: exp.In) -> str: 3033 query = expression.args.get("query") 3034 unnest = expression.args.get("unnest") 3035 field = expression.args.get("field") 3036 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3037 3038 if query: 3039 in_sql = self.sql(query) 3040 elif unnest: 3041 in_sql = self.in_unnest_op(unnest) 3042 elif field: 3043 in_sql = self.sql(field) 3044 else: 3045 in_sql = f"({self.expressions(expression, flat=True)})" 3046 3047 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3048 3049 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3050 return f"(SELECT {self.sql(unnest)})" 3051 3052 def interval_sql(self, expression: exp.Interval) -> str: 3053 unit = self.sql(expression, "unit") 3054 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3055 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3056 unit = f" {unit}" if unit else "" 3057 3058 if self.SINGLE_STRING_INTERVAL: 3059 this = expression.this.name if expression.this else "" 3060 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3061 3062 this = self.sql(expression, "this") 3063 if this: 3064 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3065 this = f" {this}" if unwrapped else f" ({this})" 3066 3067 return f"INTERVAL{this}{unit}" 3068 3069 def return_sql(self, expression: exp.Return) -> str: 3070 return f"RETURN {self.sql(expression, 'this')}" 3071 3072 def reference_sql(self, expression: exp.Reference) -> str: 3073 this = self.sql(expression, "this") 3074 expressions = self.expressions(expression, flat=True) 3075 expressions = f"({expressions})" if expressions else "" 3076 options = self.expressions(expression, key="options", flat=True, sep=" ") 3077 options = f" {options}" if options else "" 3078 return f"REFERENCES {this}{expressions}{options}" 3079 3080 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3081 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3082 parent = expression.parent 3083 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3084 return self.func( 3085 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3086 ) 3087 3088 def paren_sql(self, expression: exp.Paren) -> str: 3089 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3090 return f"({sql}{self.seg(')', sep='')}" 3091 3092 def neg_sql(self, expression: exp.Neg) -> str: 3093 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3094 this_sql = self.sql(expression, "this") 3095 sep = " " if this_sql[0] == "-" else "" 3096 return f"-{sep}{this_sql}" 3097 3098 def not_sql(self, expression: exp.Not) -> str: 3099 return f"NOT {self.sql(expression, 'this')}" 3100 3101 def alias_sql(self, expression: exp.Alias) -> str: 3102 alias = self.sql(expression, "alias") 3103 alias = f" AS {alias}" if alias else "" 3104 return f"{self.sql(expression, 'this')}{alias}" 3105 3106 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3107 alias = expression.args["alias"] 3108 3109 identifier_alias = isinstance(alias, exp.Identifier) 3110 literal_alias = isinstance(alias, exp.Literal) 3111 3112 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3113 alias.replace(exp.Literal.string(alias.output_name)) 3114 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3115 alias.replace(exp.to_identifier(alias.output_name)) 3116 3117 return self.alias_sql(expression) 3118 3119 def aliases_sql(self, expression: exp.Aliases) -> str: 3120 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3121 3122 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3123 this = self.sql(expression, "this") 3124 index = self.sql(expression, "expression") 3125 return f"{this} AT {index}" 3126 3127 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3128 this = self.sql(expression, "this") 3129 zone = self.sql(expression, "zone") 3130 return f"{this} AT TIME ZONE {zone}" 3131 3132 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3133 this = self.sql(expression, "this") 3134 zone = self.sql(expression, "zone") 3135 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3136 3137 def add_sql(self, expression: exp.Add) -> str: 3138 return self.binary(expression, "+") 3139 3140 def and_sql( 3141 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3142 ) -> str: 3143 return self.connector_sql(expression, "AND", stack) 3144 3145 def or_sql( 3146 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3147 ) -> str: 3148 return self.connector_sql(expression, "OR", stack) 3149 3150 def xor_sql( 3151 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3152 ) -> str: 3153 return self.connector_sql(expression, "XOR", stack) 3154 3155 def connector_sql( 3156 self, 3157 expression: exp.Connector, 3158 op: str, 3159 stack: t.Optional[t.List[str | exp.Expression]] = None, 3160 ) -> str: 3161 if stack is not None: 3162 if expression.expressions: 3163 stack.append(self.expressions(expression, sep=f" {op} ")) 3164 else: 3165 stack.append(expression.right) 3166 if expression.comments and self.comments: 3167 for comment in expression.comments: 3168 if comment: 3169 op += f" /*{self.pad_comment(comment)}*/" 3170 stack.extend((op, expression.left)) 3171 return op 3172 3173 stack = [expression] 3174 sqls: t.List[str] = [] 3175 ops = set() 3176 3177 while stack: 3178 node = stack.pop() 3179 if isinstance(node, exp.Connector): 3180 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3181 else: 3182 sql = self.sql(node) 3183 if sqls and sqls[-1] in ops: 3184 sqls[-1] += f" {sql}" 3185 else: 3186 sqls.append(sql) 3187 3188 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3189 return sep.join(sqls) 3190 3191 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3192 return self.binary(expression, "&") 3193 3194 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3195 return self.binary(expression, "<<") 3196 3197 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3198 return f"~{self.sql(expression, 'this')}" 3199 3200 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3201 return self.binary(expression, "|") 3202 3203 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3204 return self.binary(expression, ">>") 3205 3206 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3207 return self.binary(expression, "^") 3208 3209 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3210 format_sql = self.sql(expression, "format") 3211 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3212 to_sql = self.sql(expression, "to") 3213 to_sql = f" {to_sql}" if to_sql else "" 3214 action = self.sql(expression, "action") 3215 action = f" {action}" if action else "" 3216 default = self.sql(expression, "default") 3217 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3218 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3219 3220 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3221 zone = self.sql(expression, "this") 3222 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3223 3224 def collate_sql(self, expression: exp.Collate) -> str: 3225 if self.COLLATE_IS_FUNC: 3226 return self.function_fallback_sql(expression) 3227 return self.binary(expression, "COLLATE") 3228 3229 def command_sql(self, expression: exp.Command) -> str: 3230 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3231 3232 def comment_sql(self, expression: exp.Comment) -> str: 3233 this = self.sql(expression, "this") 3234 kind = expression.args["kind"] 3235 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3236 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3237 expression_sql = self.sql(expression, "expression") 3238 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3239 3240 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3241 this = self.sql(expression, "this") 3242 delete = " DELETE" if expression.args.get("delete") else "" 3243 recompress = self.sql(expression, "recompress") 3244 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3245 to_disk = self.sql(expression, "to_disk") 3246 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3247 to_volume = self.sql(expression, "to_volume") 3248 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3249 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3250 3251 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3252 where = self.sql(expression, "where") 3253 group = self.sql(expression, "group") 3254 aggregates = self.expressions(expression, key="aggregates") 3255 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3256 3257 if not (where or group or aggregates) and len(expression.expressions) == 1: 3258 return f"TTL {self.expressions(expression, flat=True)}" 3259 3260 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3261 3262 def transaction_sql(self, expression: exp.Transaction) -> str: 3263 return "BEGIN" 3264 3265 def commit_sql(self, expression: exp.Commit) -> str: 3266 chain = expression.args.get("chain") 3267 if chain is not None: 3268 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3269 3270 return f"COMMIT{chain or ''}" 3271 3272 def rollback_sql(self, expression: exp.Rollback) -> str: 3273 savepoint = expression.args.get("savepoint") 3274 savepoint = f" TO {savepoint}" if savepoint else "" 3275 return f"ROLLBACK{savepoint}" 3276 3277 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3278 this = self.sql(expression, "this") 3279 3280 dtype = self.sql(expression, "dtype") 3281 if dtype: 3282 collate = self.sql(expression, "collate") 3283 collate = f" COLLATE {collate}" if collate else "" 3284 using = self.sql(expression, "using") 3285 using = f" USING {using}" if using else "" 3286 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3287 3288 default = self.sql(expression, "default") 3289 if default: 3290 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3291 3292 comment = self.sql(expression, "comment") 3293 if comment: 3294 return f"ALTER COLUMN {this} COMMENT {comment}" 3295 3296 allow_null = expression.args.get("allow_null") 3297 drop = expression.args.get("drop") 3298 3299 if not drop and not allow_null: 3300 self.unsupported("Unsupported ALTER COLUMN syntax") 3301 3302 if allow_null is not None: 3303 keyword = "DROP" if drop else "SET" 3304 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3305 3306 return f"ALTER COLUMN {this} DROP DEFAULT" 3307 3308 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3309 this = self.sql(expression, "this") 3310 3311 visible = expression.args.get("visible") 3312 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3313 3314 return f"ALTER INDEX {this} {visible_sql}" 3315 3316 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3317 this = self.sql(expression, "this") 3318 if not isinstance(expression.this, exp.Var): 3319 this = f"KEY DISTKEY {this}" 3320 return f"ALTER DISTSTYLE {this}" 3321 3322 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3323 compound = " COMPOUND" if expression.args.get("compound") else "" 3324 this = self.sql(expression, "this") 3325 expressions = self.expressions(expression, flat=True) 3326 expressions = f"({expressions})" if expressions else "" 3327 return f"ALTER{compound} SORTKEY {this or expressions}" 3328 3329 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3330 if not self.RENAME_TABLE_WITH_DB: 3331 # Remove db from tables 3332 expression = expression.transform( 3333 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3334 ).assert_is(exp.AlterRename) 3335 this = self.sql(expression, "this") 3336 return f"RENAME TO {this}" 3337 3338 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3339 exists = " IF EXISTS" if expression.args.get("exists") else "" 3340 old_column = self.sql(expression, "this") 3341 new_column = self.sql(expression, "to") 3342 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3343 3344 def alterset_sql(self, expression: exp.AlterSet) -> str: 3345 exprs = self.expressions(expression, flat=True) 3346 return f"SET {exprs}" 3347 3348 def alter_sql(self, expression: exp.Alter) -> str: 3349 actions = expression.args["actions"] 3350 3351 if isinstance(actions[0], exp.ColumnDef): 3352 actions = self.add_column_sql(expression) 3353 elif isinstance(actions[0], exp.Schema): 3354 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3355 elif isinstance(actions[0], exp.Delete): 3356 actions = self.expressions(expression, key="actions", flat=True) 3357 elif isinstance(actions[0], exp.Query): 3358 actions = "AS " + self.expressions(expression, key="actions") 3359 else: 3360 actions = self.expressions(expression, key="actions", flat=True) 3361 3362 exists = " IF EXISTS" if expression.args.get("exists") else "" 3363 on_cluster = self.sql(expression, "cluster") 3364 on_cluster = f" {on_cluster}" if on_cluster else "" 3365 only = " ONLY" if expression.args.get("only") else "" 3366 options = self.expressions(expression, key="options") 3367 options = f", {options}" if options else "" 3368 kind = self.sql(expression, "kind") 3369 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3370 3371 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3372 3373 def add_column_sql(self, expression: exp.Alter) -> str: 3374 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3375 return self.expressions( 3376 expression, 3377 key="actions", 3378 prefix="ADD COLUMN ", 3379 skip_first=True, 3380 ) 3381 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3382 3383 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3384 expressions = self.expressions(expression) 3385 exists = " IF EXISTS " if expression.args.get("exists") else " " 3386 return f"DROP{exists}{expressions}" 3387 3388 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3389 return f"ADD {self.expressions(expression)}" 3390 3391 def distinct_sql(self, expression: exp.Distinct) -> str: 3392 this = self.expressions(expression, flat=True) 3393 3394 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3395 case = exp.case() 3396 for arg in expression.expressions: 3397 case = case.when(arg.is_(exp.null()), exp.null()) 3398 this = self.sql(case.else_(f"({this})")) 3399 3400 this = f" {this}" if this else "" 3401 3402 on = self.sql(expression, "on") 3403 on = f" ON {on}" if on else "" 3404 return f"DISTINCT{this}{on}" 3405 3406 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3407 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3408 3409 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3410 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3411 3412 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3413 this_sql = self.sql(expression, "this") 3414 expression_sql = self.sql(expression, "expression") 3415 kind = "MAX" if expression.args.get("max") else "MIN" 3416 return f"{this_sql} HAVING {kind} {expression_sql}" 3417 3418 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3419 return self.sql( 3420 exp.Cast( 3421 this=exp.Div(this=expression.this, expression=expression.expression), 3422 to=exp.DataType(this=exp.DataType.Type.INT), 3423 ) 3424 ) 3425 3426 def dpipe_sql(self, expression: exp.DPipe) -> str: 3427 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3428 return self.func( 3429 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3430 ) 3431 return self.binary(expression, "||") 3432 3433 def div_sql(self, expression: exp.Div) -> str: 3434 l, r = expression.left, expression.right 3435 3436 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3437 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3438 3439 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3440 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3441 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3442 3443 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3444 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3445 return self.sql( 3446 exp.cast( 3447 l / r, 3448 to=exp.DataType.Type.BIGINT, 3449 ) 3450 ) 3451 3452 return self.binary(expression, "/") 3453 3454 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3455 n = exp._wrap(expression.this, exp.Binary) 3456 d = exp._wrap(expression.expression, exp.Binary) 3457 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3458 3459 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3460 return self.binary(expression, "OVERLAPS") 3461 3462 def distance_sql(self, expression: exp.Distance) -> str: 3463 return self.binary(expression, "<->") 3464 3465 def dot_sql(self, expression: exp.Dot) -> str: 3466 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3467 3468 def eq_sql(self, expression: exp.EQ) -> str: 3469 return self.binary(expression, "=") 3470 3471 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3472 return self.binary(expression, ":=") 3473 3474 def escape_sql(self, expression: exp.Escape) -> str: 3475 return self.binary(expression, "ESCAPE") 3476 3477 def glob_sql(self, expression: exp.Glob) -> str: 3478 return self.binary(expression, "GLOB") 3479 3480 def gt_sql(self, expression: exp.GT) -> str: 3481 return self.binary(expression, ">") 3482 3483 def gte_sql(self, expression: exp.GTE) -> str: 3484 return self.binary(expression, ">=") 3485 3486 def ilike_sql(self, expression: exp.ILike) -> str: 3487 return self.binary(expression, "ILIKE") 3488 3489 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3490 return self.binary(expression, "ILIKE ANY") 3491 3492 def is_sql(self, expression: exp.Is) -> str: 3493 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3494 return self.sql( 3495 expression.this if expression.expression.this else exp.not_(expression.this) 3496 ) 3497 return self.binary(expression, "IS") 3498 3499 def like_sql(self, expression: exp.Like) -> str: 3500 return self.binary(expression, "LIKE") 3501 3502 def likeany_sql(self, expression: exp.LikeAny) -> str: 3503 return self.binary(expression, "LIKE ANY") 3504 3505 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3506 return self.binary(expression, "SIMILAR TO") 3507 3508 def lt_sql(self, expression: exp.LT) -> str: 3509 return self.binary(expression, "<") 3510 3511 def lte_sql(self, expression: exp.LTE) -> str: 3512 return self.binary(expression, "<=") 3513 3514 def mod_sql(self, expression: exp.Mod) -> str: 3515 return self.binary(expression, "%") 3516 3517 def mul_sql(self, expression: exp.Mul) -> str: 3518 return self.binary(expression, "*") 3519 3520 def neq_sql(self, expression: exp.NEQ) -> str: 3521 return self.binary(expression, "<>") 3522 3523 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3524 return self.binary(expression, "IS NOT DISTINCT FROM") 3525 3526 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3527 return self.binary(expression, "IS DISTINCT FROM") 3528 3529 def slice_sql(self, expression: exp.Slice) -> str: 3530 return self.binary(expression, ":") 3531 3532 def sub_sql(self, expression: exp.Sub) -> str: 3533 return self.binary(expression, "-") 3534 3535 def trycast_sql(self, expression: exp.TryCast) -> str: 3536 return self.cast_sql(expression, safe_prefix="TRY_") 3537 3538 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3539 return self.cast_sql(expression) 3540 3541 def try_sql(self, expression: exp.Try) -> str: 3542 if not self.TRY_SUPPORTED: 3543 self.unsupported("Unsupported TRY function") 3544 return self.sql(expression, "this") 3545 3546 return self.func("TRY", expression.this) 3547 3548 def log_sql(self, expression: exp.Log) -> str: 3549 this = expression.this 3550 expr = expression.expression 3551 3552 if self.dialect.LOG_BASE_FIRST is False: 3553 this, expr = expr, this 3554 elif self.dialect.LOG_BASE_FIRST is None and expr: 3555 if this.name in ("2", "10"): 3556 return self.func(f"LOG{this.name}", expr) 3557 3558 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3559 3560 return self.func("LOG", this, expr) 3561 3562 def use_sql(self, expression: exp.Use) -> str: 3563 kind = self.sql(expression, "kind") 3564 kind = f" {kind}" if kind else "" 3565 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3566 this = f" {this}" if this else "" 3567 return f"USE{kind}{this}" 3568 3569 def binary(self, expression: exp.Binary, op: str) -> str: 3570 sqls: t.List[str] = [] 3571 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3572 binary_type = type(expression) 3573 3574 while stack: 3575 node = stack.pop() 3576 3577 if type(node) is binary_type: 3578 op_func = node.args.get("operator") 3579 if op_func: 3580 op = f"OPERATOR({self.sql(op_func)})" 3581 3582 stack.append(node.right) 3583 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3584 stack.append(node.left) 3585 else: 3586 sqls.append(self.sql(node)) 3587 3588 return "".join(sqls) 3589 3590 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3591 to_clause = self.sql(expression, "to") 3592 if to_clause: 3593 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3594 3595 return self.function_fallback_sql(expression) 3596 3597 def function_fallback_sql(self, expression: exp.Func) -> str: 3598 args = [] 3599 3600 for key in expression.arg_types: 3601 arg_value = expression.args.get(key) 3602 3603 if isinstance(arg_value, list): 3604 for value in arg_value: 3605 args.append(value) 3606 elif arg_value is not None: 3607 args.append(arg_value) 3608 3609 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3610 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3611 else: 3612 name = expression.sql_name() 3613 3614 return self.func(name, *args) 3615 3616 def func( 3617 self, 3618 name: str, 3619 *args: t.Optional[exp.Expression | str], 3620 prefix: str = "(", 3621 suffix: str = ")", 3622 normalize: bool = True, 3623 ) -> str: 3624 name = self.normalize_func(name) if normalize else name 3625 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3626 3627 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3628 arg_sqls = tuple( 3629 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3630 ) 3631 if self.pretty and self.too_wide(arg_sqls): 3632 return self.indent( 3633 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3634 ) 3635 return sep.join(arg_sqls) 3636 3637 def too_wide(self, args: t.Iterable) -> bool: 3638 return sum(len(arg) for arg in args) > self.max_text_width 3639 3640 def format_time( 3641 self, 3642 expression: exp.Expression, 3643 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3644 inverse_time_trie: t.Optional[t.Dict] = None, 3645 ) -> t.Optional[str]: 3646 return format_time( 3647 self.sql(expression, "format"), 3648 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3649 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3650 ) 3651 3652 def expressions( 3653 self, 3654 expression: t.Optional[exp.Expression] = None, 3655 key: t.Optional[str] = None, 3656 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3657 flat: bool = False, 3658 indent: bool = True, 3659 skip_first: bool = False, 3660 skip_last: bool = False, 3661 sep: str = ", ", 3662 prefix: str = "", 3663 dynamic: bool = False, 3664 new_line: bool = False, 3665 ) -> str: 3666 expressions = expression.args.get(key or "expressions") if expression else sqls 3667 3668 if not expressions: 3669 return "" 3670 3671 if flat: 3672 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3673 3674 num_sqls = len(expressions) 3675 result_sqls = [] 3676 3677 for i, e in enumerate(expressions): 3678 sql = self.sql(e, comment=False) 3679 if not sql: 3680 continue 3681 3682 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3683 3684 if self.pretty: 3685 if self.leading_comma: 3686 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3687 else: 3688 result_sqls.append( 3689 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3690 ) 3691 else: 3692 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3693 3694 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3695 if new_line: 3696 result_sqls.insert(0, "") 3697 result_sqls.append("") 3698 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3699 else: 3700 result_sql = "".join(result_sqls) 3701 3702 return ( 3703 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3704 if indent 3705 else result_sql 3706 ) 3707 3708 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3709 flat = flat or isinstance(expression.parent, exp.Properties) 3710 expressions_sql = self.expressions(expression, flat=flat) 3711 if flat: 3712 return f"{op} {expressions_sql}" 3713 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3714 3715 def naked_property(self, expression: exp.Property) -> str: 3716 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3717 if not property_name: 3718 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3719 return f"{property_name} {self.sql(expression, 'this')}" 3720 3721 def tag_sql(self, expression: exp.Tag) -> str: 3722 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3723 3724 def token_sql(self, token_type: TokenType) -> str: 3725 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3726 3727 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3728 this = self.sql(expression, "this") 3729 expressions = self.no_identify(self.expressions, expression) 3730 expressions = ( 3731 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3732 ) 3733 return f"{this}{expressions}" if expressions.strip() != "" else this 3734 3735 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3736 this = self.sql(expression, "this") 3737 expressions = self.expressions(expression, flat=True) 3738 return f"{this}({expressions})" 3739 3740 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3741 return self.binary(expression, "=>") 3742 3743 def when_sql(self, expression: exp.When) -> str: 3744 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3745 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3746 condition = self.sql(expression, "condition") 3747 condition = f" AND {condition}" if condition else "" 3748 3749 then_expression = expression.args.get("then") 3750 if isinstance(then_expression, exp.Insert): 3751 this = self.sql(then_expression, "this") 3752 this = f"INSERT {this}" if this else "INSERT" 3753 then = self.sql(then_expression, "expression") 3754 then = f"{this} VALUES {then}" if then else this 3755 elif isinstance(then_expression, exp.Update): 3756 if isinstance(then_expression.args.get("expressions"), exp.Star): 3757 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3758 else: 3759 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3760 else: 3761 then = self.sql(then_expression) 3762 return f"WHEN {matched}{source}{condition} THEN {then}" 3763 3764 def whens_sql(self, expression: exp.Whens) -> str: 3765 return self.expressions(expression, sep=" ", indent=False) 3766 3767 def merge_sql(self, expression: exp.Merge) -> str: 3768 table = expression.this 3769 table_alias = "" 3770 3771 hints = table.args.get("hints") 3772 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3773 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3774 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3775 3776 this = self.sql(table) 3777 using = f"USING {self.sql(expression, 'using')}" 3778 on = f"ON {self.sql(expression, 'on')}" 3779 whens = self.sql(expression, "whens") 3780 3781 returning = self.sql(expression, "returning") 3782 if returning: 3783 whens = f"{whens}{returning}" 3784 3785 sep = self.sep() 3786 3787 return self.prepend_ctes( 3788 expression, 3789 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3790 ) 3791 3792 @unsupported_args("format") 3793 def tochar_sql(self, expression: exp.ToChar) -> str: 3794 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3795 3796 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3797 if not self.SUPPORTS_TO_NUMBER: 3798 self.unsupported("Unsupported TO_NUMBER function") 3799 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3800 3801 fmt = expression.args.get("format") 3802 if not fmt: 3803 self.unsupported("Conversion format is required for TO_NUMBER") 3804 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3805 3806 return self.func("TO_NUMBER", expression.this, fmt) 3807 3808 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3809 this = self.sql(expression, "this") 3810 kind = self.sql(expression, "kind") 3811 settings_sql = self.expressions(expression, key="settings", sep=" ") 3812 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3813 return f"{this}({kind}{args})" 3814 3815 def dictrange_sql(self, expression: exp.DictRange) -> str: 3816 this = self.sql(expression, "this") 3817 max = self.sql(expression, "max") 3818 min = self.sql(expression, "min") 3819 return f"{this}(MIN {min} MAX {max})" 3820 3821 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3822 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3823 3824 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3825 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3826 3827 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3828 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3829 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3830 3831 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3832 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3833 expressions = self.expressions(expression, flat=True) 3834 expressions = f" {self.wrap(expressions)}" if expressions else "" 3835 buckets = self.sql(expression, "buckets") 3836 kind = self.sql(expression, "kind") 3837 buckets = f" BUCKETS {buckets}" if buckets else "" 3838 order = self.sql(expression, "order") 3839 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3840 3841 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3842 return "" 3843 3844 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3845 expressions = self.expressions(expression, key="expressions", flat=True) 3846 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3847 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3848 buckets = self.sql(expression, "buckets") 3849 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3850 3851 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3852 this = self.sql(expression, "this") 3853 having = self.sql(expression, "having") 3854 3855 if having: 3856 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3857 3858 return self.func("ANY_VALUE", this) 3859 3860 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3861 transform = self.func("TRANSFORM", *expression.expressions) 3862 row_format_before = self.sql(expression, "row_format_before") 3863 row_format_before = f" {row_format_before}" if row_format_before else "" 3864 record_writer = self.sql(expression, "record_writer") 3865 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3866 using = f" USING {self.sql(expression, 'command_script')}" 3867 schema = self.sql(expression, "schema") 3868 schema = f" AS {schema}" if schema else "" 3869 row_format_after = self.sql(expression, "row_format_after") 3870 row_format_after = f" {row_format_after}" if row_format_after else "" 3871 record_reader = self.sql(expression, "record_reader") 3872 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3873 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3874 3875 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3876 key_block_size = self.sql(expression, "key_block_size") 3877 if key_block_size: 3878 return f"KEY_BLOCK_SIZE = {key_block_size}" 3879 3880 using = self.sql(expression, "using") 3881 if using: 3882 return f"USING {using}" 3883 3884 parser = self.sql(expression, "parser") 3885 if parser: 3886 return f"WITH PARSER {parser}" 3887 3888 comment = self.sql(expression, "comment") 3889 if comment: 3890 return f"COMMENT {comment}" 3891 3892 visible = expression.args.get("visible") 3893 if visible is not None: 3894 return "VISIBLE" if visible else "INVISIBLE" 3895 3896 engine_attr = self.sql(expression, "engine_attr") 3897 if engine_attr: 3898 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3899 3900 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3901 if secondary_engine_attr: 3902 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3903 3904 self.unsupported("Unsupported index constraint option.") 3905 return "" 3906 3907 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3908 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3909 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3910 3911 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3912 kind = self.sql(expression, "kind") 3913 kind = f"{kind} INDEX" if kind else "INDEX" 3914 this = self.sql(expression, "this") 3915 this = f" {this}" if this else "" 3916 index_type = self.sql(expression, "index_type") 3917 index_type = f" USING {index_type}" if index_type else "" 3918 expressions = self.expressions(expression, flat=True) 3919 expressions = f" ({expressions})" if expressions else "" 3920 options = self.expressions(expression, key="options", sep=" ") 3921 options = f" {options}" if options else "" 3922 return f"{kind}{this}{index_type}{expressions}{options}" 3923 3924 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3925 if self.NVL2_SUPPORTED: 3926 return self.function_fallback_sql(expression) 3927 3928 case = exp.Case().when( 3929 expression.this.is_(exp.null()).not_(copy=False), 3930 expression.args["true"], 3931 copy=False, 3932 ) 3933 else_cond = expression.args.get("false") 3934 if else_cond: 3935 case.else_(else_cond, copy=False) 3936 3937 return self.sql(case) 3938 3939 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3940 this = self.sql(expression, "this") 3941 expr = self.sql(expression, "expression") 3942 iterator = self.sql(expression, "iterator") 3943 condition = self.sql(expression, "condition") 3944 condition = f" IF {condition}" if condition else "" 3945 return f"{this} FOR {expr} IN {iterator}{condition}" 3946 3947 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3948 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3949 3950 def opclass_sql(self, expression: exp.Opclass) -> str: 3951 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3952 3953 def predict_sql(self, expression: exp.Predict) -> str: 3954 model = self.sql(expression, "this") 3955 model = f"MODEL {model}" 3956 table = self.sql(expression, "expression") 3957 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3958 parameters = self.sql(expression, "params_struct") 3959 return self.func("PREDICT", model, table, parameters or None) 3960 3961 def forin_sql(self, expression: exp.ForIn) -> str: 3962 this = self.sql(expression, "this") 3963 expression_sql = self.sql(expression, "expression") 3964 return f"FOR {this} DO {expression_sql}" 3965 3966 def refresh_sql(self, expression: exp.Refresh) -> str: 3967 this = self.sql(expression, "this") 3968 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3969 return f"REFRESH {table}{this}" 3970 3971 def toarray_sql(self, expression: exp.ToArray) -> str: 3972 arg = expression.this 3973 if not arg.type: 3974 from sqlglot.optimizer.annotate_types import annotate_types 3975 3976 arg = annotate_types(arg) 3977 3978 if arg.is_type(exp.DataType.Type.ARRAY): 3979 return self.sql(arg) 3980 3981 cond_for_null = arg.is_(exp.null()) 3982 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3983 3984 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3985 this = expression.this 3986 time_format = self.format_time(expression) 3987 3988 if time_format: 3989 return self.sql( 3990 exp.cast( 3991 exp.StrToTime(this=this, format=expression.args["format"]), 3992 exp.DataType.Type.TIME, 3993 ) 3994 ) 3995 3996 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3997 return self.sql(this) 3998 3999 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4000 4001 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4002 this = expression.this 4003 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4004 return self.sql(this) 4005 4006 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4007 4008 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4009 this = expression.this 4010 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4011 return self.sql(this) 4012 4013 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4014 4015 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4016 this = expression.this 4017 time_format = self.format_time(expression) 4018 4019 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4020 return self.sql( 4021 exp.cast( 4022 exp.StrToTime(this=this, format=expression.args["format"]), 4023 exp.DataType.Type.DATE, 4024 ) 4025 ) 4026 4027 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4028 return self.sql(this) 4029 4030 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4031 4032 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4033 return self.sql( 4034 exp.func( 4035 "DATEDIFF", 4036 expression.this, 4037 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4038 "day", 4039 ) 4040 ) 4041 4042 def lastday_sql(self, expression: exp.LastDay) -> str: 4043 if self.LAST_DAY_SUPPORTS_DATE_PART: 4044 return self.function_fallback_sql(expression) 4045 4046 unit = expression.text("unit") 4047 if unit and unit != "MONTH": 4048 self.unsupported("Date parts are not supported in LAST_DAY.") 4049 4050 return self.func("LAST_DAY", expression.this) 4051 4052 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4053 from sqlglot.dialects.dialect import unit_to_str 4054 4055 return self.func( 4056 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4057 ) 4058 4059 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4060 if self.CAN_IMPLEMENT_ARRAY_ANY: 4061 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4062 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4063 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4064 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4065 4066 from sqlglot.dialects import Dialect 4067 4068 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4069 if self.dialect.__class__ != Dialect: 4070 self.unsupported("ARRAY_ANY is unsupported") 4071 4072 return self.function_fallback_sql(expression) 4073 4074 def struct_sql(self, expression: exp.Struct) -> str: 4075 expression.set( 4076 "expressions", 4077 [ 4078 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4079 if isinstance(e, exp.PropertyEQ) 4080 else e 4081 for e in expression.expressions 4082 ], 4083 ) 4084 4085 return self.function_fallback_sql(expression) 4086 4087 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4088 low = self.sql(expression, "this") 4089 high = self.sql(expression, "expression") 4090 4091 return f"{low} TO {high}" 4092 4093 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4094 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4095 tables = f" {self.expressions(expression)}" 4096 4097 exists = " IF EXISTS" if expression.args.get("exists") else "" 4098 4099 on_cluster = self.sql(expression, "cluster") 4100 on_cluster = f" {on_cluster}" if on_cluster else "" 4101 4102 identity = self.sql(expression, "identity") 4103 identity = f" {identity} IDENTITY" if identity else "" 4104 4105 option = self.sql(expression, "option") 4106 option = f" {option}" if option else "" 4107 4108 partition = self.sql(expression, "partition") 4109 partition = f" {partition}" if partition else "" 4110 4111 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4112 4113 # This transpiles T-SQL's CONVERT function 4114 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4115 def convert_sql(self, expression: exp.Convert) -> str: 4116 to = expression.this 4117 value = expression.expression 4118 style = expression.args.get("style") 4119 safe = expression.args.get("safe") 4120 strict = expression.args.get("strict") 4121 4122 if not to or not value: 4123 return "" 4124 4125 # Retrieve length of datatype and override to default if not specified 4126 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4127 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4128 4129 transformed: t.Optional[exp.Expression] = None 4130 cast = exp.Cast if strict else exp.TryCast 4131 4132 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4133 if isinstance(style, exp.Literal) and style.is_int: 4134 from sqlglot.dialects.tsql import TSQL 4135 4136 style_value = style.name 4137 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4138 if not converted_style: 4139 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4140 4141 fmt = exp.Literal.string(converted_style) 4142 4143 if to.this == exp.DataType.Type.DATE: 4144 transformed = exp.StrToDate(this=value, format=fmt) 4145 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4146 transformed = exp.StrToTime(this=value, format=fmt) 4147 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4148 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4149 elif to.this == exp.DataType.Type.TEXT: 4150 transformed = exp.TimeToStr(this=value, format=fmt) 4151 4152 if not transformed: 4153 transformed = cast(this=value, to=to, safe=safe) 4154 4155 return self.sql(transformed) 4156 4157 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4158 this = expression.this 4159 if isinstance(this, exp.JSONPathWildcard): 4160 this = self.json_path_part(this) 4161 return f".{this}" if this else "" 4162 4163 if exp.SAFE_IDENTIFIER_RE.match(this): 4164 return f".{this}" 4165 4166 this = self.json_path_part(this) 4167 return ( 4168 f"[{this}]" 4169 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4170 else f".{this}" 4171 ) 4172 4173 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4174 this = self.json_path_part(expression.this) 4175 return f"[{this}]" if this else "" 4176 4177 def _simplify_unless_literal(self, expression: E) -> E: 4178 if not isinstance(expression, exp.Literal): 4179 from sqlglot.optimizer.simplify import simplify 4180 4181 expression = simplify(expression, dialect=self.dialect) 4182 4183 return expression 4184 4185 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4186 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4187 # The first modifier here will be the one closest to the AggFunc's arg 4188 mods = sorted( 4189 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4190 key=lambda x: 0 4191 if isinstance(x, exp.HavingMax) 4192 else (1 if isinstance(x, exp.Order) else 2), 4193 ) 4194 4195 if mods: 4196 mod = mods[0] 4197 this = expression.__class__(this=mod.this.copy()) 4198 this.meta["inline"] = True 4199 mod.this.replace(this) 4200 return self.sql(expression.this) 4201 4202 agg_func = expression.find(exp.AggFunc) 4203 4204 if agg_func: 4205 return self.sql(agg_func)[:-1] + f" {text})" 4206 4207 return f"{self.sql(expression, 'this')} {text}" 4208 4209 def _replace_line_breaks(self, string: str) -> str: 4210 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4211 if self.pretty: 4212 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4213 return string 4214 4215 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4216 option = self.sql(expression, "this") 4217 4218 if expression.expressions: 4219 upper = option.upper() 4220 4221 # Snowflake FILE_FORMAT options are separated by whitespace 4222 sep = " " if upper == "FILE_FORMAT" else ", " 4223 4224 # Databricks copy/format options do not set their list of values with EQ 4225 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4226 values = self.expressions(expression, flat=True, sep=sep) 4227 return f"{option}{op}({values})" 4228 4229 value = self.sql(expression, "expression") 4230 4231 if not value: 4232 return option 4233 4234 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4235 4236 return f"{option}{op}{value}" 4237 4238 def credentials_sql(self, expression: exp.Credentials) -> str: 4239 cred_expr = expression.args.get("credentials") 4240 if isinstance(cred_expr, exp.Literal): 4241 # Redshift case: CREDENTIALS <string> 4242 credentials = self.sql(expression, "credentials") 4243 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4244 else: 4245 # Snowflake case: CREDENTIALS = (...) 4246 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4247 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4248 4249 storage = self.sql(expression, "storage") 4250 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4251 4252 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4253 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4254 4255 iam_role = self.sql(expression, "iam_role") 4256 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4257 4258 region = self.sql(expression, "region") 4259 region = f" REGION {region}" if region else "" 4260 4261 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4262 4263 def copy_sql(self, expression: exp.Copy) -> str: 4264 this = self.sql(expression, "this") 4265 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4266 4267 credentials = self.sql(expression, "credentials") 4268 credentials = self.seg(credentials) if credentials else "" 4269 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4270 files = self.expressions(expression, key="files", flat=True) 4271 4272 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4273 params = self.expressions( 4274 expression, 4275 key="params", 4276 sep=sep, 4277 new_line=True, 4278 skip_last=True, 4279 skip_first=True, 4280 indent=self.COPY_PARAMS_ARE_WRAPPED, 4281 ) 4282 4283 if params: 4284 if self.COPY_PARAMS_ARE_WRAPPED: 4285 params = f" WITH ({params})" 4286 elif not self.pretty: 4287 params = f" {params}" 4288 4289 return f"COPY{this}{kind} {files}{credentials}{params}" 4290 4291 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4292 return "" 4293 4294 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4295 on_sql = "ON" if expression.args.get("on") else "OFF" 4296 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4297 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4298 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4299 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4300 4301 if filter_col or retention_period: 4302 on_sql = self.func("ON", filter_col, retention_period) 4303 4304 return f"DATA_DELETION={on_sql}" 4305 4306 def maskingpolicycolumnconstraint_sql( 4307 self, expression: exp.MaskingPolicyColumnConstraint 4308 ) -> str: 4309 this = self.sql(expression, "this") 4310 expressions = self.expressions(expression, flat=True) 4311 expressions = f" USING ({expressions})" if expressions else "" 4312 return f"MASKING POLICY {this}{expressions}" 4313 4314 def gapfill_sql(self, expression: exp.GapFill) -> str: 4315 this = self.sql(expression, "this") 4316 this = f"TABLE {this}" 4317 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4318 4319 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4320 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4321 4322 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4323 this = self.sql(expression, "this") 4324 expr = expression.expression 4325 4326 if isinstance(expr, exp.Func): 4327 # T-SQL's CLR functions are case sensitive 4328 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4329 else: 4330 expr = self.sql(expression, "expression") 4331 4332 return self.scope_resolution(expr, this) 4333 4334 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4335 if self.PARSE_JSON_NAME is None: 4336 return self.sql(expression.this) 4337 4338 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4339 4340 def rand_sql(self, expression: exp.Rand) -> str: 4341 lower = self.sql(expression, "lower") 4342 upper = self.sql(expression, "upper") 4343 4344 if lower and upper: 4345 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4346 return self.func("RAND", expression.this) 4347 4348 def changes_sql(self, expression: exp.Changes) -> str: 4349 information = self.sql(expression, "information") 4350 information = f"INFORMATION => {information}" 4351 at_before = self.sql(expression, "at_before") 4352 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4353 end = self.sql(expression, "end") 4354 end = f"{self.seg('')}{end}" if end else "" 4355 4356 return f"CHANGES ({information}){at_before}{end}" 4357 4358 def pad_sql(self, expression: exp.Pad) -> str: 4359 prefix = "L" if expression.args.get("is_left") else "R" 4360 4361 fill_pattern = self.sql(expression, "fill_pattern") or None 4362 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4363 fill_pattern = "' '" 4364 4365 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4366 4367 def summarize_sql(self, expression: exp.Summarize) -> str: 4368 table = " TABLE" if expression.args.get("table") else "" 4369 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4370 4371 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4372 generate_series = exp.GenerateSeries(**expression.args) 4373 4374 parent = expression.parent 4375 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4376 parent = parent.parent 4377 4378 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4379 return self.sql(exp.Unnest(expressions=[generate_series])) 4380 4381 if isinstance(parent, exp.Select): 4382 self.unsupported("GenerateSeries projection unnesting is not supported.") 4383 4384 return self.sql(generate_series) 4385 4386 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4387 exprs = expression.expressions 4388 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4389 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4390 else: 4391 rhs = self.expressions(expression) 4392 4393 return self.func(name, expression.this, rhs or None) 4394 4395 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4396 if self.SUPPORTS_CONVERT_TIMEZONE: 4397 return self.function_fallback_sql(expression) 4398 4399 source_tz = expression.args.get("source_tz") 4400 target_tz = expression.args.get("target_tz") 4401 timestamp = expression.args.get("timestamp") 4402 4403 if source_tz and timestamp: 4404 timestamp = exp.AtTimeZone( 4405 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4406 ) 4407 4408 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4409 4410 return self.sql(expr) 4411 4412 def json_sql(self, expression: exp.JSON) -> str: 4413 this = self.sql(expression, "this") 4414 this = f" {this}" if this else "" 4415 4416 _with = expression.args.get("with") 4417 4418 if _with is None: 4419 with_sql = "" 4420 elif not _with: 4421 with_sql = " WITHOUT" 4422 else: 4423 with_sql = " WITH" 4424 4425 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4426 4427 return f"JSON{this}{with_sql}{unique_sql}" 4428 4429 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4430 def _generate_on_options(arg: t.Any) -> str: 4431 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4432 4433 path = self.sql(expression, "path") 4434 returning = self.sql(expression, "returning") 4435 returning = f" RETURNING {returning}" if returning else "" 4436 4437 on_condition = self.sql(expression, "on_condition") 4438 on_condition = f" {on_condition}" if on_condition else "" 4439 4440 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4441 4442 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4443 else_ = "ELSE " if expression.args.get("else_") else "" 4444 condition = self.sql(expression, "expression") 4445 condition = f"WHEN {condition} THEN " if condition else else_ 4446 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4447 return f"{condition}{insert}" 4448 4449 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4450 kind = self.sql(expression, "kind") 4451 expressions = self.seg(self.expressions(expression, sep=" ")) 4452 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4453 return res 4454 4455 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4456 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4457 empty = expression.args.get("empty") 4458 empty = ( 4459 f"DEFAULT {empty} ON EMPTY" 4460 if isinstance(empty, exp.Expression) 4461 else self.sql(expression, "empty") 4462 ) 4463 4464 error = expression.args.get("error") 4465 error = ( 4466 f"DEFAULT {error} ON ERROR" 4467 if isinstance(error, exp.Expression) 4468 else self.sql(expression, "error") 4469 ) 4470 4471 if error and empty: 4472 error = ( 4473 f"{empty} {error}" 4474 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4475 else f"{error} {empty}" 4476 ) 4477 empty = "" 4478 4479 null = self.sql(expression, "null") 4480 4481 return f"{empty}{error}{null}" 4482 4483 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4484 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4485 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4486 4487 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4488 this = self.sql(expression, "this") 4489 path = self.sql(expression, "path") 4490 4491 passing = self.expressions(expression, "passing") 4492 passing = f" PASSING {passing}" if passing else "" 4493 4494 on_condition = self.sql(expression, "on_condition") 4495 on_condition = f" {on_condition}" if on_condition else "" 4496 4497 path = f"{path}{passing}{on_condition}" 4498 4499 return self.func("JSON_EXISTS", this, path) 4500 4501 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4502 array_agg = self.function_fallback_sql(expression) 4503 4504 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4505 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4506 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4507 parent = expression.parent 4508 if isinstance(parent, exp.Filter): 4509 parent_cond = parent.expression.this 4510 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4511 else: 4512 this = expression.this 4513 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4514 if this.find(exp.Column): 4515 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4516 this_sql = ( 4517 self.expressions(this) 4518 if isinstance(this, exp.Distinct) 4519 else self.sql(expression, "this") 4520 ) 4521 4522 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4523 4524 return array_agg 4525 4526 def apply_sql(self, expression: exp.Apply) -> str: 4527 this = self.sql(expression, "this") 4528 expr = self.sql(expression, "expression") 4529 4530 return f"{this} APPLY({expr})" 4531 4532 def grant_sql(self, expression: exp.Grant) -> str: 4533 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4534 4535 kind = self.sql(expression, "kind") 4536 kind = f" {kind}" if kind else "" 4537 4538 securable = self.sql(expression, "securable") 4539 securable = f" {securable}" if securable else "" 4540 4541 principals = self.expressions(expression, key="principals", flat=True) 4542 4543 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4544 4545 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4546 4547 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4548 this = self.sql(expression, "this") 4549 columns = self.expressions(expression, flat=True) 4550 columns = f"({columns})" if columns else "" 4551 4552 return f"{this}{columns}" 4553 4554 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4555 this = self.sql(expression, "this") 4556 4557 kind = self.sql(expression, "kind") 4558 kind = f"{kind} " if kind else "" 4559 4560 return f"{kind}{this}" 4561 4562 def columns_sql(self, expression: exp.Columns): 4563 func = self.function_fallback_sql(expression) 4564 if expression.args.get("unpack"): 4565 func = f"*{func}" 4566 4567 return func 4568 4569 def overlay_sql(self, expression: exp.Overlay): 4570 this = self.sql(expression, "this") 4571 expr = self.sql(expression, "expression") 4572 from_sql = self.sql(expression, "from") 4573 for_sql = self.sql(expression, "for") 4574 for_sql = f" FOR {for_sql}" if for_sql else "" 4575 4576 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4577 4578 @unsupported_args("format") 4579 def todouble_sql(self, expression: exp.ToDouble) -> str: 4580 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4581 4582 def string_sql(self, expression: exp.String) -> str: 4583 this = expression.this 4584 zone = expression.args.get("zone") 4585 4586 if zone: 4587 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4588 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4589 # set for source_tz to transpile the time conversion before the STRING cast 4590 this = exp.ConvertTimezone( 4591 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4592 ) 4593 4594 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4595 4596 def median_sql(self, expression: exp.Median): 4597 if not self.SUPPORTS_MEDIAN: 4598 return self.sql( 4599 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4600 ) 4601 4602 return self.function_fallback_sql(expression) 4603 4604 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4605 filler = self.sql(expression, "this") 4606 filler = f" {filler}" if filler else "" 4607 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4608 return f"TRUNCATE{filler} {with_count}" 4609 4610 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4611 if self.SUPPORTS_UNIX_SECONDS: 4612 return self.function_fallback_sql(expression) 4613 4614 start_ts = exp.cast( 4615 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4616 ) 4617 4618 return self.sql( 4619 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4620 ) 4621 4622 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4623 dim = expression.expression 4624 4625 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4626 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4627 if not (dim.is_int and dim.name == "1"): 4628 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4629 dim = None 4630 4631 # If dimension is required but not specified, default initialize it 4632 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4633 dim = exp.Literal.number(1) 4634 4635 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4636 4637 def attach_sql(self, expression: exp.Attach) -> str: 4638 this = self.sql(expression, "this") 4639 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4640 expressions = self.expressions(expression) 4641 expressions = f" ({expressions})" if expressions else "" 4642 4643 return f"ATTACH{exists_sql} {this}{expressions}" 4644 4645 def detach_sql(self, expression: exp.Detach) -> str: 4646 this = self.sql(expression, "this") 4647 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4648 4649 return f"DETACH{exists_sql} {this}" 4650 4651 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4652 this = self.sql(expression, "this") 4653 value = self.sql(expression, "expression") 4654 value = f" {value}" if value else "" 4655 return f"{this}{value}" 4656 4657 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4658 this_sql = self.sql(expression, "this") 4659 if isinstance(expression.this, exp.Table): 4660 this_sql = f"TABLE {this_sql}" 4661 4662 return self.func( 4663 "FEATURES_AT_TIME", 4664 this_sql, 4665 expression.args.get("time"), 4666 expression.args.get("num_rows"), 4667 expression.args.get("ignore_feature_nulls"), 4668 ) 4669 4670 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4671 return ( 4672 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4673 ) 4674 4675 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4676 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4677 encode = f"{encode} {self.sql(expression, 'this')}" 4678 4679 properties = expression.args.get("properties") 4680 if properties: 4681 encode = f"{encode} {self.properties(properties)}" 4682 4683 return encode 4684 4685 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4686 this = self.sql(expression, "this") 4687 include = f"INCLUDE {this}" 4688 4689 column_def = self.sql(expression, "column_def") 4690 if column_def: 4691 include = f"{include} {column_def}" 4692 4693 alias = self.sql(expression, "alias") 4694 if alias: 4695 include = f"{include} AS {alias}" 4696 4697 return include 4698 4699 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4700 name = f"NAME {self.sql(expression, 'this')}" 4701 return self.func("XMLELEMENT", name, *expression.expressions) 4702 4703 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4704 partitions = self.expressions(expression, "partition_expressions") 4705 create = self.expressions(expression, "create_expressions") 4706 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4707 4708 def partitionbyrangepropertydynamic_sql( 4709 self, expression: exp.PartitionByRangePropertyDynamic 4710 ) -> str: 4711 start = self.sql(expression, "start") 4712 end = self.sql(expression, "end") 4713 4714 every = expression.args["every"] 4715 if isinstance(every, exp.Interval) and every.this.is_string: 4716 every.this.replace(exp.Literal.number(every.name)) 4717 4718 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4719 4720 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4721 name = self.sql(expression, "this") 4722 values = self.expressions(expression, flat=True) 4723 4724 return f"NAME {name} VALUE {values}" 4725 4726 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4727 kind = self.sql(expression, "kind") 4728 sample = self.sql(expression, "sample") 4729 return f"SAMPLE {sample} {kind}" 4730 4731 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4732 kind = self.sql(expression, "kind") 4733 option = self.sql(expression, "option") 4734 option = f" {option}" if option else "" 4735 this = self.sql(expression, "this") 4736 this = f" {this}" if this else "" 4737 columns = self.expressions(expression) 4738 columns = f" {columns}" if columns else "" 4739 return f"{kind}{option} STATISTICS{this}{columns}" 4740 4741 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4742 this = self.sql(expression, "this") 4743 columns = self.expressions(expression) 4744 inner_expression = self.sql(expression, "expression") 4745 inner_expression = f" {inner_expression}" if inner_expression else "" 4746 update_options = self.sql(expression, "update_options") 4747 update_options = f" {update_options} UPDATE" if update_options else "" 4748 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4749 4750 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4751 kind = self.sql(expression, "kind") 4752 kind = f" {kind}" if kind else "" 4753 return f"DELETE{kind} STATISTICS" 4754 4755 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4756 inner_expression = self.sql(expression, "expression") 4757 return f"LIST CHAINED ROWS{inner_expression}" 4758 4759 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4760 kind = self.sql(expression, "kind") 4761 this = self.sql(expression, "this") 4762 this = f" {this}" if this else "" 4763 inner_expression = self.sql(expression, "expression") 4764 return f"VALIDATE {kind}{this}{inner_expression}" 4765 4766 def analyze_sql(self, expression: exp.Analyze) -> str: 4767 options = self.expressions(expression, key="options", sep=" ") 4768 options = f" {options}" if options else "" 4769 kind = self.sql(expression, "kind") 4770 kind = f" {kind}" if kind else "" 4771 this = self.sql(expression, "this") 4772 this = f" {this}" if this else "" 4773 mode = self.sql(expression, "mode") 4774 mode = f" {mode}" if mode else "" 4775 properties = self.sql(expression, "properties") 4776 properties = f" {properties}" if properties else "" 4777 partition = self.sql(expression, "partition") 4778 partition = f" {partition}" if partition else "" 4779 inner_expression = self.sql(expression, "expression") 4780 inner_expression = f" {inner_expression}" if inner_expression else "" 4781 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4782 4783 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4784 this = self.sql(expression, "this") 4785 namespaces = self.expressions(expression, key="namespaces") 4786 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4787 passing = self.expressions(expression, key="passing") 4788 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4789 columns = self.expressions(expression, key="columns") 4790 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4791 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4792 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4793 4794 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4795 this = self.sql(expression, "this") 4796 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4797 4798 def export_sql(self, expression: exp.Export) -> str: 4799 this = self.sql(expression, "this") 4800 connection = self.sql(expression, "connection") 4801 connection = f"WITH CONNECTION {connection} " if connection else "" 4802 options = self.sql(expression, "options") 4803 return f"EXPORT DATA {connection}{options} AS {this}" 4804 4805 def declare_sql(self, expression: exp.Declare) -> str: 4806 return f"DECLARE {self.expressions(expression, flat=True)}" 4807 4808 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4809 variable = self.sql(expression, "this") 4810 default = self.sql(expression, "default") 4811 default = f" = {default}" if default else "" 4812 4813 kind = self.sql(expression, "kind") 4814 if isinstance(expression.args.get("kind"), exp.Schema): 4815 kind = f"TABLE {kind}" 4816 4817 return f"{variable} AS {kind}{default}" 4818 4819 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4820 kind = self.sql(expression, "kind") 4821 this = self.sql(expression, "this") 4822 set = self.sql(expression, "expression") 4823 using = self.sql(expression, "using") 4824 using = f" USING {using}" if using else "" 4825 4826 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4827 4828 return f"{kind_sql} {this} SET {set}{using}" 4829 4830 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4831 params = self.expressions(expression, key="params", flat=True) 4832 return self.func(expression.name, *expression.expressions) + f"({params})" 4833 4834 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4835 return self.func(expression.name, *expression.expressions) 4836 4837 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4838 return self.anonymousaggfunc_sql(expression) 4839 4840 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4841 return self.parameterizedagg_sql(expression) 4842 4843 def show_sql(self, expression: exp.Show) -> str: 4844 self.unsupported("Unsupported SHOW statement") 4845 return ""
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)
675 def __init__( 676 self, 677 pretty: t.Optional[bool] = None, 678 identify: str | bool = False, 679 normalize: bool = False, 680 pad: int = 2, 681 indent: int = 2, 682 normalize_functions: t.Optional[str | bool] = None, 683 unsupported_level: ErrorLevel = ErrorLevel.WARN, 684 max_unsupported: int = 3, 685 leading_comma: bool = False, 686 max_text_width: int = 80, 687 comments: bool = True, 688 dialect: DialectType = None, 689 ): 690 import sqlglot 691 from sqlglot.dialects import Dialect 692 693 self.pretty = pretty if pretty is not None else sqlglot.pretty 694 self.identify = identify 695 self.normalize = normalize 696 self.pad = pad 697 self._indent = indent 698 self.unsupported_level = unsupported_level 699 self.max_unsupported = max_unsupported 700 self.leading_comma = leading_comma 701 self.max_text_width = max_text_width 702 self.comments = comments 703 self.dialect = Dialect.get_or_raise(dialect) 704 705 # This is both a Dialect property and a Generator argument, so we prioritize the latter 706 self.normalize_functions = ( 707 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 708 ) 709 710 self.unsupported_messages: t.List[str] = [] 711 self._escaped_quote_end: str = ( 712 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 713 ) 714 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 715 716 self._next_name = name_sequence("_t") 717 718 self._identifier_start = self.dialect.IDENTIFIER_START 719 self._identifier_end = self.dialect.IDENTIFIER_END 720 721 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.CopyGrantsProperty'>: <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.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.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.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <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.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <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.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>>}
SUPPORTED_JSON_PATH_PARTS =
{<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'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathRecursive'>}
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.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.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.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.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'>}
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.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
723 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 724 """ 725 Generates the SQL string corresponding to the given syntax tree. 726 727 Args: 728 expression: The syntax tree. 729 copy: Whether to copy the expression. The generator performs mutations so 730 it is safer to copy. 731 732 Returns: 733 The SQL string corresponding to `expression`. 734 """ 735 if copy: 736 expression = expression.copy() 737 738 expression = self.preprocess(expression) 739 740 self.unsupported_messages = [] 741 sql = self.sql(expression).strip() 742 743 if self.pretty: 744 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 745 746 if self.unsupported_level == ErrorLevel.IGNORE: 747 return sql 748 749 if self.unsupported_level == ErrorLevel.WARN: 750 for msg in self.unsupported_messages: 751 logger.warning(msg) 752 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 753 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 754 755 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:
757 def preprocess(self, expression: exp.Expression) -> exp.Expression: 758 """Apply generic preprocessing transformations to a given expression.""" 759 expression = self._move_ctes_to_top_level(expression) 760 761 if self.ENSURE_BOOLS: 762 from sqlglot.transforms import ensure_bools 763 764 expression = ensure_bools(expression) 765 766 return expression
Apply generic preprocessing transformations to a given expression.
def
maybe_comment( self, sql: str, expression: Optional[sqlglot.expressions.Expression] = None, comments: Optional[List[str]] = None, separated: bool = False) -> str:
795 def maybe_comment( 796 self, 797 sql: str, 798 expression: t.Optional[exp.Expression] = None, 799 comments: t.Optional[t.List[str]] = None, 800 separated: bool = False, 801 ) -> str: 802 comments = ( 803 ((expression and expression.comments) if comments is None else comments) # type: ignore 804 if self.comments 805 else None 806 ) 807 808 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 809 return sql 810 811 comments_sql = " ".join( 812 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 813 ) 814 815 if not comments_sql: 816 return sql 817 818 comments_sql = self._replace_line_breaks(comments_sql) 819 820 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 821 return ( 822 f"{self.sep()}{comments_sql}{sql}" 823 if not sql or sql[0].isspace() 824 else f"{comments_sql}{self.sep()}{sql}" 825 ) 826 827 return f"{sql} {comments_sql}"
829 def wrap(self, expression: exp.Expression | str) -> str: 830 this_sql = ( 831 self.sql(expression) 832 if isinstance(expression, exp.UNWRAPPED_QUERIES) 833 else self.sql(expression, "this") 834 ) 835 if not this_sql: 836 return "()" 837 838 this_sql = self.indent(this_sql, level=1, pad=0) 839 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:
855 def indent( 856 self, 857 sql: str, 858 level: int = 0, 859 pad: t.Optional[int] = None, 860 skip_first: bool = False, 861 skip_last: bool = False, 862 ) -> str: 863 if not self.pretty or not sql: 864 return sql 865 866 pad = self.pad if pad is None else pad 867 lines = sql.split("\n") 868 869 return "\n".join( 870 ( 871 line 872 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 873 else f"{' ' * (level * self._indent + pad)}{line}" 874 ) 875 for i, line in enumerate(lines) 876 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
878 def sql( 879 self, 880 expression: t.Optional[str | exp.Expression], 881 key: t.Optional[str] = None, 882 comment: bool = True, 883 ) -> str: 884 if not expression: 885 return "" 886 887 if isinstance(expression, str): 888 return expression 889 890 if key: 891 value = expression.args.get(key) 892 if value: 893 return self.sql(value) 894 return "" 895 896 transform = self.TRANSFORMS.get(expression.__class__) 897 898 if callable(transform): 899 sql = transform(self, expression) 900 elif isinstance(expression, exp.Expression): 901 exp_handler_name = f"{expression.key}_sql" 902 903 if hasattr(self, exp_handler_name): 904 sql = getattr(self, exp_handler_name)(expression) 905 elif isinstance(expression, exp.Func): 906 sql = self.function_fallback_sql(expression) 907 elif isinstance(expression, exp.Property): 908 sql = self.property_sql(expression) 909 else: 910 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 911 else: 912 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 913 914 return self.maybe_comment(sql, expression) if self.comments and comment else sql
921 def cache_sql(self, expression: exp.Cache) -> str: 922 lazy = " LAZY" if expression.args.get("lazy") else "" 923 table = self.sql(expression, "this") 924 options = expression.args.get("options") 925 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 926 sql = self.sql(expression, "expression") 927 sql = f" AS{self.sep()}{sql}" if sql else "" 928 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 929 return self.prepend_ctes(expression, sql)
931 def characterset_sql(self, expression: exp.CharacterSet) -> str: 932 if isinstance(expression.parent, exp.Cast): 933 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 934 default = "DEFAULT " if expression.args.get("default") else "" 935 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
949 def column_sql(self, expression: exp.Column) -> str: 950 join_mark = " (+)" if expression.args.get("join_mark") else "" 951 952 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 953 join_mark = "" 954 self.unsupported("Outer join syntax using the (+) operator is not supported.") 955 956 return f"{self.column_parts(expression)}{join_mark}"
964 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 965 column = self.sql(expression, "this") 966 kind = self.sql(expression, "kind") 967 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 968 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 969 kind = f"{sep}{kind}" if kind else "" 970 constraints = f" {constraints}" if constraints else "" 971 position = self.sql(expression, "position") 972 position = f" {position}" if position else "" 973 974 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 975 kind = "" 976 977 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
984 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 985 this = self.sql(expression, "this") 986 if expression.args.get("not_null"): 987 persisted = " PERSISTED NOT NULL" 988 elif expression.args.get("persisted"): 989 persisted = " PERSISTED" 990 else: 991 persisted = "" 992 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1005 def generatedasidentitycolumnconstraint_sql( 1006 self, expression: exp.GeneratedAsIdentityColumnConstraint 1007 ) -> str: 1008 this = "" 1009 if expression.this is not None: 1010 on_null = " ON NULL" if expression.args.get("on_null") else "" 1011 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1012 1013 start = expression.args.get("start") 1014 start = f"START WITH {start}" if start else "" 1015 increment = expression.args.get("increment") 1016 increment = f" INCREMENT BY {increment}" if increment else "" 1017 minvalue = expression.args.get("minvalue") 1018 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1019 maxvalue = expression.args.get("maxvalue") 1020 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1021 cycle = expression.args.get("cycle") 1022 cycle_sql = "" 1023 1024 if cycle is not None: 1025 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1026 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1027 1028 sequence_opts = "" 1029 if start or increment or cycle_sql: 1030 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1031 sequence_opts = f" ({sequence_opts.strip()})" 1032 1033 expr = self.sql(expression, "expression") 1034 expr = f"({expr})" if expr else "IDENTITY" 1035 1036 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1038 def generatedasrowcolumnconstraint_sql( 1039 self, expression: exp.GeneratedAsRowColumnConstraint 1040 ) -> str: 1041 start = "START" if expression.args.get("start") else "END" 1042 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1043 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:
def
uniquecolumnconstraint_sql(self, expression: sqlglot.expressions.UniqueColumnConstraint) -> str:
1062 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1063 this = self.sql(expression, "this") 1064 this = f" {this}" if this else "" 1065 index_type = expression.args.get("index_type") 1066 index_type = f" USING {index_type}" if index_type else "" 1067 on_conflict = self.sql(expression, "on_conflict") 1068 on_conflict = f" {on_conflict}" if on_conflict else "" 1069 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1070 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1075 def create_sql(self, expression: exp.Create) -> str: 1076 kind = self.sql(expression, "kind") 1077 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1078 properties = expression.args.get("properties") 1079 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1080 1081 this = self.createable_sql(expression, properties_locs) 1082 1083 properties_sql = "" 1084 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1085 exp.Properties.Location.POST_WITH 1086 ): 1087 properties_sql = self.sql( 1088 exp.Properties( 1089 expressions=[ 1090 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1091 *properties_locs[exp.Properties.Location.POST_WITH], 1092 ] 1093 ) 1094 ) 1095 1096 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1097 properties_sql = self.sep() + properties_sql 1098 elif not self.pretty: 1099 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1100 properties_sql = f" {properties_sql}" 1101 1102 begin = " BEGIN" if expression.args.get("begin") else "" 1103 end = " END" if expression.args.get("end") else "" 1104 1105 expression_sql = self.sql(expression, "expression") 1106 if expression_sql: 1107 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1108 1109 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1110 postalias_props_sql = "" 1111 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1112 postalias_props_sql = self.properties( 1113 exp.Properties( 1114 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1115 ), 1116 wrapped=False, 1117 ) 1118 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1119 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1120 1121 postindex_props_sql = "" 1122 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1123 postindex_props_sql = self.properties( 1124 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1125 wrapped=False, 1126 prefix=" ", 1127 ) 1128 1129 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1130 indexes = f" {indexes}" if indexes else "" 1131 index_sql = indexes + postindex_props_sql 1132 1133 replace = " OR REPLACE" if expression.args.get("replace") else "" 1134 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1135 unique = " UNIQUE" if expression.args.get("unique") else "" 1136 1137 clustered = expression.args.get("clustered") 1138 if clustered is None: 1139 clustered_sql = "" 1140 elif clustered: 1141 clustered_sql = " CLUSTERED COLUMNSTORE" 1142 else: 1143 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1144 1145 postcreate_props_sql = "" 1146 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1147 postcreate_props_sql = self.properties( 1148 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1149 sep=" ", 1150 prefix=" ", 1151 wrapped=False, 1152 ) 1153 1154 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1155 1156 postexpression_props_sql = "" 1157 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1158 postexpression_props_sql = self.properties( 1159 exp.Properties( 1160 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1161 ), 1162 sep=" ", 1163 prefix=" ", 1164 wrapped=False, 1165 ) 1166 1167 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1168 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1169 no_schema_binding = ( 1170 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1171 ) 1172 1173 clone = self.sql(expression, "clone") 1174 clone = f" {clone}" if clone else "" 1175 1176 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1177 properties_expression = f"{expression_sql}{properties_sql}" 1178 else: 1179 properties_expression = f"{properties_sql}{expression_sql}" 1180 1181 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1182 return self.prepend_ctes(expression, expression_sql)
1184 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1185 start = self.sql(expression, "start") 1186 start = f"START WITH {start}" if start else "" 1187 increment = self.sql(expression, "increment") 1188 increment = f" INCREMENT BY {increment}" if increment else "" 1189 minvalue = self.sql(expression, "minvalue") 1190 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1191 maxvalue = self.sql(expression, "maxvalue") 1192 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1193 owned = self.sql(expression, "owned") 1194 owned = f" OWNED BY {owned}" if owned else "" 1195 1196 cache = expression.args.get("cache") 1197 if cache is None: 1198 cache_str = "" 1199 elif cache is True: 1200 cache_str = " CACHE" 1201 else: 1202 cache_str = f" CACHE {cache}" 1203 1204 options = self.expressions(expression, key="options", flat=True, sep=" ") 1205 options = f" {options}" if options else "" 1206 1207 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1209 def clone_sql(self, expression: exp.Clone) -> str: 1210 this = self.sql(expression, "this") 1211 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1212 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1213 return f"{shallow}{keyword} {this}"
1215 def describe_sql(self, expression: exp.Describe) -> str: 1216 style = expression.args.get("style") 1217 style = f" {style}" if style else "" 1218 partition = self.sql(expression, "partition") 1219 partition = f" {partition}" if partition else "" 1220 format = self.sql(expression, "format") 1221 format = f" {format}" if format else "" 1222 1223 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1235 def with_sql(self, expression: exp.With) -> str: 1236 sql = self.expressions(expression, flat=True) 1237 recursive = ( 1238 "RECURSIVE " 1239 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1240 else "" 1241 ) 1242 search = self.sql(expression, "search") 1243 search = f" {search}" if search else "" 1244 1245 return f"WITH {recursive}{sql}{search}"
1247 def cte_sql(self, expression: exp.CTE) -> str: 1248 alias = expression.args.get("alias") 1249 if alias: 1250 alias.add_comments(expression.pop_comments()) 1251 1252 alias_sql = self.sql(expression, "alias") 1253 1254 materialized = expression.args.get("materialized") 1255 if materialized is False: 1256 materialized = "NOT MATERIALIZED " 1257 elif materialized: 1258 materialized = "MATERIALIZED " 1259 1260 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1262 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1263 alias = self.sql(expression, "this") 1264 columns = self.expressions(expression, key="columns", flat=True) 1265 columns = f"({columns})" if columns else "" 1266 1267 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1268 columns = "" 1269 self.unsupported("Named columns are not supported in table alias.") 1270 1271 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1272 alias = self._next_name() 1273 1274 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1282 def hexstring_sql( 1283 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1284 ) -> str: 1285 this = self.sql(expression, "this") 1286 is_integer_type = expression.args.get("is_integer") 1287 1288 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1289 not self.dialect.HEX_START and not binary_function_repr 1290 ): 1291 # Integer representation will be returned if: 1292 # - The read dialect treats the hex value as integer literal but not the write 1293 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1294 return f"{int(this, 16)}" 1295 1296 if not is_integer_type: 1297 # Read dialect treats the hex value as BINARY/BLOB 1298 if binary_function_repr: 1299 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1300 return self.func(binary_function_repr, exp.Literal.string(this)) 1301 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1302 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1303 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1304 1305 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1313 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1314 this = self.sql(expression, "this") 1315 escape = expression.args.get("escape") 1316 1317 if self.dialect.UNICODE_START: 1318 escape_substitute = r"\\\1" 1319 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1320 else: 1321 escape_substitute = r"\\u\1" 1322 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1323 1324 if escape: 1325 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1326 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1327 else: 1328 escape_pattern = ESCAPED_UNICODE_RE 1329 escape_sql = "" 1330 1331 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1332 this = escape_pattern.sub(escape_substitute, this) 1333 1334 return f"{left_quote}{this}{right_quote}{escape_sql}"
1346 def datatype_sql(self, expression: exp.DataType) -> str: 1347 nested = "" 1348 values = "" 1349 interior = self.expressions(expression, flat=True) 1350 1351 type_value = expression.this 1352 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1353 type_sql = self.sql(expression, "kind") 1354 else: 1355 type_sql = ( 1356 self.TYPE_MAPPING.get(type_value, type_value.value) 1357 if isinstance(type_value, exp.DataType.Type) 1358 else type_value 1359 ) 1360 1361 if interior: 1362 if expression.args.get("nested"): 1363 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1364 if expression.args.get("values") is not None: 1365 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1366 values = self.expressions(expression, key="values", flat=True) 1367 values = f"{delimiters[0]}{values}{delimiters[1]}" 1368 elif type_value == exp.DataType.Type.INTERVAL: 1369 nested = f" {interior}" 1370 else: 1371 nested = f"({interior})" 1372 1373 type_sql = f"{type_sql}{nested}{values}" 1374 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1375 exp.DataType.Type.TIMETZ, 1376 exp.DataType.Type.TIMESTAMPTZ, 1377 ): 1378 type_sql = f"{type_sql} WITH TIME ZONE" 1379 1380 return type_sql
1382 def directory_sql(self, expression: exp.Directory) -> str: 1383 local = "LOCAL " if expression.args.get("local") else "" 1384 row_format = self.sql(expression, "row_format") 1385 row_format = f" {row_format}" if row_format else "" 1386 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1388 def delete_sql(self, expression: exp.Delete) -> str: 1389 this = self.sql(expression, "this") 1390 this = f" FROM {this}" if this else "" 1391 using = self.sql(expression, "using") 1392 using = f" USING {using}" if using else "" 1393 cluster = self.sql(expression, "cluster") 1394 cluster = f" {cluster}" if cluster else "" 1395 where = self.sql(expression, "where") 1396 returning = self.sql(expression, "returning") 1397 limit = self.sql(expression, "limit") 1398 tables = self.expressions(expression, key="tables") 1399 tables = f" {tables}" if tables else "" 1400 if self.RETURNING_END: 1401 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1402 else: 1403 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1404 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1406 def drop_sql(self, expression: exp.Drop) -> str: 1407 this = self.sql(expression, "this") 1408 expressions = self.expressions(expression, flat=True) 1409 expressions = f" ({expressions})" if expressions else "" 1410 kind = expression.args["kind"] 1411 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1412 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1413 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1414 on_cluster = self.sql(expression, "cluster") 1415 on_cluster = f" {on_cluster}" if on_cluster else "" 1416 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1417 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1418 cascade = " CASCADE" if expression.args.get("cascade") else "" 1419 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1420 purge = " PURGE" if expression.args.get("purge") else "" 1421 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1423 def set_operation(self, expression: exp.SetOperation) -> str: 1424 op_type = type(expression) 1425 op_name = op_type.key.upper() 1426 1427 distinct = expression.args.get("distinct") 1428 if ( 1429 distinct is False 1430 and op_type in (exp.Except, exp.Intersect) 1431 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1432 ): 1433 self.unsupported(f"{op_name} ALL is not supported") 1434 1435 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1436 1437 if distinct is None: 1438 distinct = default_distinct 1439 if distinct is None: 1440 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1441 1442 if distinct is default_distinct: 1443 kind = "" 1444 else: 1445 kind = " DISTINCT" if distinct else " ALL" 1446 1447 by_name = " BY NAME" if expression.args.get("by_name") else "" 1448 return f"{op_name}{kind}{by_name}"
1450 def set_operations(self, expression: exp.SetOperation) -> str: 1451 if not self.SET_OP_MODIFIERS: 1452 limit = expression.args.get("limit") 1453 order = expression.args.get("order") 1454 1455 if limit or order: 1456 select = self._move_ctes_to_top_level( 1457 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1458 ) 1459 1460 if limit: 1461 select = select.limit(limit.pop(), copy=False) 1462 if order: 1463 select = select.order_by(order.pop(), copy=False) 1464 return self.sql(select) 1465 1466 sqls: t.List[str] = [] 1467 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1468 1469 while stack: 1470 node = stack.pop() 1471 1472 if isinstance(node, exp.SetOperation): 1473 stack.append(node.expression) 1474 stack.append( 1475 self.maybe_comment( 1476 self.set_operation(node), comments=node.comments, separated=True 1477 ) 1478 ) 1479 stack.append(node.this) 1480 else: 1481 sqls.append(self.sql(node)) 1482 1483 this = self.sep().join(sqls) 1484 this = self.query_modifiers(expression, this) 1485 return self.prepend_ctes(expression, this)
1487 def fetch_sql(self, expression: exp.Fetch) -> str: 1488 direction = expression.args.get("direction") 1489 direction = f" {direction}" if direction else "" 1490 count = self.sql(expression, "count") 1491 count = f" {count}" if count else "" 1492 limit_options = self.sql(expression, "limit_options") 1493 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1494 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1496 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1497 percent = " PERCENT" if expression.args.get("percent") else "" 1498 rows = " ROWS" if expression.args.get("rows") else "" 1499 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1500 if not with_ties and rows: 1501 with_ties = " ONLY" 1502 return f"{percent}{rows}{with_ties}"
1504 def filter_sql(self, expression: exp.Filter) -> str: 1505 if self.AGGREGATE_FILTER_SUPPORTED: 1506 this = self.sql(expression, "this") 1507 where = self.sql(expression, "expression").strip() 1508 return f"{this} FILTER({where})" 1509 1510 agg = expression.this 1511 agg_arg = agg.this 1512 cond = expression.expression.this 1513 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1514 return self.sql(agg)
1523 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1524 using = self.sql(expression, "using") 1525 using = f" USING {using}" if using else "" 1526 columns = self.expressions(expression, key="columns", flat=True) 1527 columns = f"({columns})" if columns else "" 1528 partition_by = self.expressions(expression, key="partition_by", flat=True) 1529 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1530 where = self.sql(expression, "where") 1531 include = self.expressions(expression, key="include", flat=True) 1532 if include: 1533 include = f" INCLUDE ({include})" 1534 with_storage = self.expressions(expression, key="with_storage", flat=True) 1535 with_storage = f" WITH ({with_storage})" if with_storage else "" 1536 tablespace = self.sql(expression, "tablespace") 1537 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1538 on = self.sql(expression, "on") 1539 on = f" ON {on}" if on else "" 1540 1541 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1543 def index_sql(self, expression: exp.Index) -> str: 1544 unique = "UNIQUE " if expression.args.get("unique") else "" 1545 primary = "PRIMARY " if expression.args.get("primary") else "" 1546 amp = "AMP " if expression.args.get("amp") else "" 1547 name = self.sql(expression, "this") 1548 name = f"{name} " if name else "" 1549 table = self.sql(expression, "table") 1550 table = f"{self.INDEX_ON} {table}" if table else "" 1551 1552 index = "INDEX " if not table else "" 1553 1554 params = self.sql(expression, "params") 1555 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1557 def identifier_sql(self, expression: exp.Identifier) -> str: 1558 text = expression.name 1559 lower = text.lower() 1560 text = lower if self.normalize and not expression.quoted else text 1561 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1562 if ( 1563 expression.quoted 1564 or self.dialect.can_identify(text, self.identify) 1565 or lower in self.RESERVED_KEYWORDS 1566 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1567 ): 1568 text = f"{self._identifier_start}{text}{self._identifier_end}" 1569 return text
1584 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1585 input_format = self.sql(expression, "input_format") 1586 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1587 output_format = self.sql(expression, "output_format") 1588 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1589 return self.sep().join((input_format, output_format))
1599 def properties_sql(self, expression: exp.Properties) -> str: 1600 root_properties = [] 1601 with_properties = [] 1602 1603 for p in expression.expressions: 1604 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1605 if p_loc == exp.Properties.Location.POST_WITH: 1606 with_properties.append(p) 1607 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1608 root_properties.append(p) 1609 1610 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1611 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1612 1613 if root_props and with_props and not self.pretty: 1614 with_props = " " + with_props 1615 1616 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1623 def properties( 1624 self, 1625 properties: exp.Properties, 1626 prefix: str = "", 1627 sep: str = ", ", 1628 suffix: str = "", 1629 wrapped: bool = True, 1630 ) -> str: 1631 if properties.expressions: 1632 expressions = self.expressions(properties, sep=sep, indent=False) 1633 if expressions: 1634 expressions = self.wrap(expressions) if wrapped else expressions 1635 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1636 return ""
1641 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1642 properties_locs = defaultdict(list) 1643 for p in properties.expressions: 1644 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1645 if p_loc != exp.Properties.Location.UNSUPPORTED: 1646 properties_locs[p_loc].append(p) 1647 else: 1648 self.unsupported(f"Unsupported property {p.key}") 1649 1650 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1657 def property_sql(self, expression: exp.Property) -> str: 1658 property_cls = expression.__class__ 1659 if property_cls == exp.Property: 1660 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1661 1662 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1663 if not property_name: 1664 self.unsupported(f"Unsupported property {expression.key}") 1665 1666 return f"{property_name}={self.sql(expression, 'this')}"
1668 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1669 if self.SUPPORTS_CREATE_TABLE_LIKE: 1670 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1671 options = f" {options}" if options else "" 1672 1673 like = f"LIKE {self.sql(expression, 'this')}{options}" 1674 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1675 like = f"({like})" 1676 1677 return like 1678 1679 if expression.expressions: 1680 self.unsupported("Transpilation of LIKE property options is unsupported") 1681 1682 select = exp.select("*").from_(expression.this).limit(0) 1683 return f"AS {self.sql(select)}"
1690 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1691 no = "NO " if expression.args.get("no") else "" 1692 local = expression.args.get("local") 1693 local = f"{local} " if local else "" 1694 dual = "DUAL " if expression.args.get("dual") else "" 1695 before = "BEFORE " if expression.args.get("before") else "" 1696 after = "AFTER " if expression.args.get("after") else "" 1697 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1713 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1714 if expression.args.get("no"): 1715 return "NO MERGEBLOCKRATIO" 1716 if expression.args.get("default"): 1717 return "DEFAULT MERGEBLOCKRATIO" 1718 1719 percent = " PERCENT" if expression.args.get("percent") else "" 1720 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1722 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1723 default = expression.args.get("default") 1724 minimum = expression.args.get("minimum") 1725 maximum = expression.args.get("maximum") 1726 if default or minimum or maximum: 1727 if default: 1728 prop = "DEFAULT" 1729 elif minimum: 1730 prop = "MINIMUM" 1731 else: 1732 prop = "MAXIMUM" 1733 return f"{prop} DATABLOCKSIZE" 1734 units = expression.args.get("units") 1735 units = f" {units}" if units else "" 1736 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1738 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1739 autotemp = expression.args.get("autotemp") 1740 always = expression.args.get("always") 1741 default = expression.args.get("default") 1742 manual = expression.args.get("manual") 1743 never = expression.args.get("never") 1744 1745 if autotemp is not None: 1746 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1747 elif always: 1748 prop = "ALWAYS" 1749 elif default: 1750 prop = "DEFAULT" 1751 elif manual: 1752 prop = "MANUAL" 1753 elif never: 1754 prop = "NEVER" 1755 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1757 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1758 no = expression.args.get("no") 1759 no = " NO" if no else "" 1760 concurrent = expression.args.get("concurrent") 1761 concurrent = " CONCURRENT" if concurrent else "" 1762 target = self.sql(expression, "target") 1763 target = f" {target}" if target else "" 1764 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1766 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1767 if isinstance(expression.this, list): 1768 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1769 if expression.this: 1770 modulus = self.sql(expression, "this") 1771 remainder = self.sql(expression, "expression") 1772 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1773 1774 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1775 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1776 return f"FROM ({from_expressions}) TO ({to_expressions})"
1778 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1779 this = self.sql(expression, "this") 1780 1781 for_values_or_default = expression.expression 1782 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1783 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1784 else: 1785 for_values_or_default = " DEFAULT" 1786 1787 return f"PARTITION OF {this}{for_values_or_default}"
1789 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1790 kind = expression.args.get("kind") 1791 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1792 for_or_in = expression.args.get("for_or_in") 1793 for_or_in = f" {for_or_in}" if for_or_in else "" 1794 lock_type = expression.args.get("lock_type") 1795 override = " OVERRIDE" if expression.args.get("override") else "" 1796 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1798 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1799 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1800 statistics = expression.args.get("statistics") 1801 statistics_sql = "" 1802 if statistics is not None: 1803 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1804 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1806 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1807 this = self.sql(expression, "this") 1808 this = f"HISTORY_TABLE={this}" if this else "" 1809 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1810 data_consistency = ( 1811 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1812 ) 1813 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1814 retention_period = ( 1815 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1816 ) 1817 1818 if this: 1819 on_sql = self.func("ON", this, data_consistency, retention_period) 1820 else: 1821 on_sql = "ON" if expression.args.get("on") else "OFF" 1822 1823 sql = f"SYSTEM_VERSIONING={on_sql}" 1824 1825 return f"WITH({sql})" if expression.args.get("with") else sql
1827 def insert_sql(self, expression: exp.Insert) -> str: 1828 hint = self.sql(expression, "hint") 1829 overwrite = expression.args.get("overwrite") 1830 1831 if isinstance(expression.this, exp.Directory): 1832 this = " OVERWRITE" if overwrite else " INTO" 1833 else: 1834 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1835 1836 stored = self.sql(expression, "stored") 1837 stored = f" {stored}" if stored else "" 1838 alternative = expression.args.get("alternative") 1839 alternative = f" OR {alternative}" if alternative else "" 1840 ignore = " IGNORE" if expression.args.get("ignore") else "" 1841 is_function = expression.args.get("is_function") 1842 if is_function: 1843 this = f"{this} FUNCTION" 1844 this = f"{this} {self.sql(expression, 'this')}" 1845 1846 exists = " IF EXISTS" if expression.args.get("exists") else "" 1847 where = self.sql(expression, "where") 1848 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1849 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1850 on_conflict = self.sql(expression, "conflict") 1851 on_conflict = f" {on_conflict}" if on_conflict else "" 1852 by_name = " BY NAME" if expression.args.get("by_name") else "" 1853 returning = self.sql(expression, "returning") 1854 1855 if self.RETURNING_END: 1856 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1857 else: 1858 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1859 1860 partition_by = self.sql(expression, "partition") 1861 partition_by = f" {partition_by}" if partition_by else "" 1862 settings = self.sql(expression, "settings") 1863 settings = f" {settings}" if settings else "" 1864 1865 source = self.sql(expression, "source") 1866 source = f"TABLE {source}" if source else "" 1867 1868 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1869 return self.prepend_ctes(expression, sql)
1887 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1888 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1889 1890 constraint = self.sql(expression, "constraint") 1891 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1892 1893 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1894 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1895 action = self.sql(expression, "action") 1896 1897 expressions = self.expressions(expression, flat=True) 1898 if expressions: 1899 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1900 expressions = f" {set_keyword}{expressions}" 1901 1902 where = self.sql(expression, "where") 1903 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1908 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1909 fields = self.sql(expression, "fields") 1910 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1911 escaped = self.sql(expression, "escaped") 1912 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1913 items = self.sql(expression, "collection_items") 1914 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1915 keys = self.sql(expression, "map_keys") 1916 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1917 lines = self.sql(expression, "lines") 1918 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1919 null = self.sql(expression, "null") 1920 null = f" NULL DEFINED AS {null}" if null else "" 1921 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1949 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1950 table = self.table_parts(expression) 1951 only = "ONLY " if expression.args.get("only") else "" 1952 partition = self.sql(expression, "partition") 1953 partition = f" {partition}" if partition else "" 1954 version = self.sql(expression, "version") 1955 version = f" {version}" if version else "" 1956 alias = self.sql(expression, "alias") 1957 alias = f"{sep}{alias}" if alias else "" 1958 1959 sample = self.sql(expression, "sample") 1960 if self.dialect.ALIAS_POST_TABLESAMPLE: 1961 sample_pre_alias = sample 1962 sample_post_alias = "" 1963 else: 1964 sample_pre_alias = "" 1965 sample_post_alias = sample 1966 1967 hints = self.expressions(expression, key="hints", sep=" ") 1968 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1969 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1970 joins = self.indent( 1971 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1972 ) 1973 laterals = self.expressions(expression, key="laterals", sep="") 1974 1975 file_format = self.sql(expression, "format") 1976 if file_format: 1977 pattern = self.sql(expression, "pattern") 1978 pattern = f", PATTERN => {pattern}" if pattern else "" 1979 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1980 1981 ordinality = expression.args.get("ordinality") or "" 1982 if ordinality: 1983 ordinality = f" WITH ORDINALITY{alias}" 1984 alias = "" 1985 1986 when = self.sql(expression, "when") 1987 if when: 1988 table = f"{table} {when}" 1989 1990 changes = self.sql(expression, "changes") 1991 changes = f" {changes}" if changes else "" 1992 1993 rows_from = self.expressions(expression, key="rows_from") 1994 if rows_from: 1995 table = f"ROWS FROM {self.wrap(rows_from)}" 1996 1997 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
1999 def tablesample_sql( 2000 self, 2001 expression: exp.TableSample, 2002 tablesample_keyword: t.Optional[str] = None, 2003 ) -> str: 2004 method = self.sql(expression, "method") 2005 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2006 numerator = self.sql(expression, "bucket_numerator") 2007 denominator = self.sql(expression, "bucket_denominator") 2008 field = self.sql(expression, "bucket_field") 2009 field = f" ON {field}" if field else "" 2010 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2011 seed = self.sql(expression, "seed") 2012 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2013 2014 size = self.sql(expression, "size") 2015 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2016 size = f"{size} ROWS" 2017 2018 percent = self.sql(expression, "percent") 2019 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2020 percent = f"{percent} PERCENT" 2021 2022 expr = f"{bucket}{percent}{size}" 2023 if self.TABLESAMPLE_REQUIRES_PARENS: 2024 expr = f"({expr})" 2025 2026 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2028 def pivot_sql(self, expression: exp.Pivot) -> str: 2029 expressions = self.expressions(expression, flat=True) 2030 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2031 2032 if expression.this: 2033 this = self.sql(expression, "this") 2034 if not expressions: 2035 return f"UNPIVOT {this}" 2036 2037 on = f"{self.seg('ON')} {expressions}" 2038 into = self.sql(expression, "into") 2039 into = f"{self.seg('INTO')} {into}" if into else "" 2040 using = self.expressions(expression, key="using", flat=True) 2041 using = f"{self.seg('USING')} {using}" if using else "" 2042 group = self.sql(expression, "group") 2043 return f"{direction} {this}{on}{into}{using}{group}" 2044 2045 alias = self.sql(expression, "alias") 2046 alias = f" AS {alias}" if alias else "" 2047 2048 field = self.sql(expression, "field") 2049 2050 include_nulls = expression.args.get("include_nulls") 2051 if include_nulls is not None: 2052 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2053 else: 2054 nulls = "" 2055 2056 default_on_null = self.sql(expression, "default_on_null") 2057 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2058 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
2069 def update_sql(self, expression: exp.Update) -> str: 2070 this = self.sql(expression, "this") 2071 set_sql = self.expressions(expression, flat=True) 2072 from_sql = self.sql(expression, "from") 2073 where_sql = self.sql(expression, "where") 2074 returning = self.sql(expression, "returning") 2075 order = self.sql(expression, "order") 2076 limit = self.sql(expression, "limit") 2077 if self.RETURNING_END: 2078 expression_sql = f"{from_sql}{where_sql}{returning}" 2079 else: 2080 expression_sql = f"{returning}{from_sql}{where_sql}" 2081 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2082 return self.prepend_ctes(expression, sql)
2084 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2085 values_as_table = values_as_table and self.VALUES_AS_TABLE 2086 2087 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2088 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2089 args = self.expressions(expression) 2090 alias = self.sql(expression, "alias") 2091 values = f"VALUES{self.seg('')}{args}" 2092 values = ( 2093 f"({values})" 2094 if self.WRAP_DERIVED_VALUES 2095 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2096 else values 2097 ) 2098 return f"{values} AS {alias}" if alias else values 2099 2100 # Converts `VALUES...` expression into a series of select unions. 2101 alias_node = expression.args.get("alias") 2102 column_names = alias_node and alias_node.columns 2103 2104 selects: t.List[exp.Query] = [] 2105 2106 for i, tup in enumerate(expression.expressions): 2107 row = tup.expressions 2108 2109 if i == 0 and column_names: 2110 row = [ 2111 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2112 ] 2113 2114 selects.append(exp.Select(expressions=row)) 2115 2116 if self.pretty: 2117 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2118 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2119 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2120 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2121 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2122 2123 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2124 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2125 return f"({unions}){alias}"
2130 @unsupported_args("expressions") 2131 def into_sql(self, expression: exp.Into) -> str: 2132 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2133 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2134 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2151 def group_sql(self, expression: exp.Group) -> str: 2152 group_by_all = expression.args.get("all") 2153 if group_by_all is True: 2154 modifier = " ALL" 2155 elif group_by_all is False: 2156 modifier = " DISTINCT" 2157 else: 2158 modifier = "" 2159 2160 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2161 2162 grouping_sets = self.expressions(expression, key="grouping_sets") 2163 cube = self.expressions(expression, key="cube") 2164 rollup = self.expressions(expression, key="rollup") 2165 2166 groupings = csv( 2167 self.seg(grouping_sets) if grouping_sets else "", 2168 self.seg(cube) if cube else "", 2169 self.seg(rollup) if rollup else "", 2170 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2171 sep=self.GROUPINGS_SEP, 2172 ) 2173 2174 if ( 2175 expression.expressions 2176 and groupings 2177 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2178 ): 2179 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2180 2181 return f"{group_by}{groupings}"
2187 def connect_sql(self, expression: exp.Connect) -> str: 2188 start = self.sql(expression, "start") 2189 start = self.seg(f"START WITH {start}") if start else "" 2190 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2191 connect = self.sql(expression, "connect") 2192 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2193 return start + connect
2198 def join_sql(self, expression: exp.Join) -> str: 2199 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2200 side = None 2201 else: 2202 side = expression.side 2203 2204 op_sql = " ".join( 2205 op 2206 for op in ( 2207 expression.method, 2208 "GLOBAL" if expression.args.get("global") else None, 2209 side, 2210 expression.kind, 2211 expression.hint if self.JOIN_HINTS else None, 2212 ) 2213 if op 2214 ) 2215 match_cond = self.sql(expression, "match_condition") 2216 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2217 on_sql = self.sql(expression, "on") 2218 using = expression.args.get("using") 2219 2220 if not on_sql and using: 2221 on_sql = csv(*(self.sql(column) for column in using)) 2222 2223 this = expression.this 2224 this_sql = self.sql(this) 2225 2226 exprs = self.expressions(expression) 2227 if exprs: 2228 this_sql = f"{this_sql},{self.seg(exprs)}" 2229 2230 if on_sql: 2231 on_sql = self.indent(on_sql, skip_first=True) 2232 space = self.seg(" " * self.pad) if self.pretty else " " 2233 if using: 2234 on_sql = f"{space}USING ({on_sql})" 2235 else: 2236 on_sql = f"{space}ON {on_sql}" 2237 elif not op_sql: 2238 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2239 return f" {this_sql}" 2240 2241 return f", {this_sql}" 2242 2243 if op_sql != "STRAIGHT_JOIN": 2244 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2245 2246 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2253 def lateral_op(self, expression: exp.Lateral) -> str: 2254 cross_apply = expression.args.get("cross_apply") 2255 2256 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2257 if cross_apply is True: 2258 op = "INNER JOIN " 2259 elif cross_apply is False: 2260 op = "LEFT JOIN " 2261 else: 2262 op = "" 2263 2264 return f"{op}LATERAL"
2266 def lateral_sql(self, expression: exp.Lateral) -> str: 2267 this = self.sql(expression, "this") 2268 2269 if expression.args.get("view"): 2270 alias = expression.args["alias"] 2271 columns = self.expressions(alias, key="columns", flat=True) 2272 table = f" {alias.name}" if alias.name else "" 2273 columns = f" AS {columns}" if columns else "" 2274 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2275 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2276 2277 alias = self.sql(expression, "alias") 2278 alias = f" AS {alias}" if alias else "" 2279 return f"{self.lateral_op(expression)} {this}{alias}"
2281 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2282 this = self.sql(expression, "this") 2283 2284 args = [ 2285 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2286 for e in (expression.args.get(k) for k in ("offset", "expression")) 2287 if e 2288 ] 2289 2290 args_sql = ", ".join(self.sql(e) for e in args) 2291 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2292 expressions = self.expressions(expression, flat=True) 2293 limit_options = self.sql(expression, "limit_options") 2294 expressions = f" BY {expressions}" if expressions else "" 2295 2296 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2298 def offset_sql(self, expression: exp.Offset) -> str: 2299 this = self.sql(expression, "this") 2300 value = expression.expression 2301 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2302 expressions = self.expressions(expression, flat=True) 2303 expressions = f" BY {expressions}" if expressions else "" 2304 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2306 def setitem_sql(self, expression: exp.SetItem) -> str: 2307 kind = self.sql(expression, "kind") 2308 kind = f"{kind} " if kind else "" 2309 this = self.sql(expression, "this") 2310 expressions = self.expressions(expression) 2311 collate = self.sql(expression, "collate") 2312 collate = f" COLLATE {collate}" if collate else "" 2313 global_ = "GLOBAL " if expression.args.get("global") else "" 2314 return f"{global_}{kind}{this}{expressions}{collate}"
2324 def lock_sql(self, expression: exp.Lock) -> str: 2325 if not self.LOCKING_READS_SUPPORTED: 2326 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2327 return "" 2328 2329 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2330 expressions = self.expressions(expression, flat=True) 2331 expressions = f" OF {expressions}" if expressions else "" 2332 wait = expression.args.get("wait") 2333 2334 if wait is not None: 2335 if isinstance(wait, exp.Literal): 2336 wait = f" WAIT {self.sql(wait)}" 2337 else: 2338 wait = " NOWAIT" if wait else " SKIP LOCKED" 2339 2340 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2348 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2349 if self.dialect.ESCAPED_SEQUENCES: 2350 to_escaped = self.dialect.ESCAPED_SEQUENCES 2351 text = "".join( 2352 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2353 ) 2354 2355 return self._replace_line_breaks(text).replace( 2356 self.dialect.QUOTE_END, self._escaped_quote_end 2357 )
2359 def loaddata_sql(self, expression: exp.LoadData) -> str: 2360 local = " LOCAL" if expression.args.get("local") else "" 2361 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2362 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2363 this = f" INTO TABLE {self.sql(expression, 'this')}" 2364 partition = self.sql(expression, "partition") 2365 partition = f" {partition}" if partition else "" 2366 input_format = self.sql(expression, "input_format") 2367 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2368 serde = self.sql(expression, "serde") 2369 serde = f" SERDE {serde}" if serde else "" 2370 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2378 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2379 this = self.sql(expression, "this") 2380 this = f"{this} " if this else this 2381 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2382 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2384 def withfill_sql(self, expression: exp.WithFill) -> str: 2385 from_sql = self.sql(expression, "from") 2386 from_sql = f" FROM {from_sql}" if from_sql else "" 2387 to_sql = self.sql(expression, "to") 2388 to_sql = f" TO {to_sql}" if to_sql else "" 2389 step_sql = self.sql(expression, "step") 2390 step_sql = f" STEP {step_sql}" if step_sql else "" 2391 interpolated_values = [ 2392 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2393 if isinstance(e, exp.Alias) 2394 else self.sql(e, "this") 2395 for e in expression.args.get("interpolate") or [] 2396 ] 2397 interpolate = ( 2398 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2399 ) 2400 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2411 def ordered_sql(self, expression: exp.Ordered) -> str: 2412 desc = expression.args.get("desc") 2413 asc = not desc 2414 2415 nulls_first = expression.args.get("nulls_first") 2416 nulls_last = not nulls_first 2417 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2418 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2419 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2420 2421 this = self.sql(expression, "this") 2422 2423 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2424 nulls_sort_change = "" 2425 if nulls_first and ( 2426 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2427 ): 2428 nulls_sort_change = " NULLS FIRST" 2429 elif ( 2430 nulls_last 2431 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2432 and not nulls_are_last 2433 ): 2434 nulls_sort_change = " NULLS LAST" 2435 2436 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2437 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2438 window = expression.find_ancestor(exp.Window, exp.Select) 2439 if isinstance(window, exp.Window) and window.args.get("spec"): 2440 self.unsupported( 2441 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2442 ) 2443 nulls_sort_change = "" 2444 elif self.NULL_ORDERING_SUPPORTED is False and ( 2445 (asc and nulls_sort_change == " NULLS LAST") 2446 or (desc and nulls_sort_change == " NULLS FIRST") 2447 ): 2448 # BigQuery does not allow these ordering/nulls combinations when used under 2449 # an aggregation func or under a window containing one 2450 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2451 2452 if isinstance(ancestor, exp.Window): 2453 ancestor = ancestor.this 2454 if isinstance(ancestor, exp.AggFunc): 2455 self.unsupported( 2456 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2457 ) 2458 nulls_sort_change = "" 2459 elif self.NULL_ORDERING_SUPPORTED is None: 2460 if expression.this.is_int: 2461 self.unsupported( 2462 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2463 ) 2464 elif not isinstance(expression.this, exp.Rand): 2465 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2466 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2467 nulls_sort_change = "" 2468 2469 with_fill = self.sql(expression, "with_fill") 2470 with_fill = f" {with_fill}" if with_fill else "" 2471 2472 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2482 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2483 partition = self.partition_by_sql(expression) 2484 order = self.sql(expression, "order") 2485 measures = self.expressions(expression, key="measures") 2486 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2487 rows = self.sql(expression, "rows") 2488 rows = self.seg(rows) if rows else "" 2489 after = self.sql(expression, "after") 2490 after = self.seg(after) if after else "" 2491 pattern = self.sql(expression, "pattern") 2492 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2493 definition_sqls = [ 2494 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2495 for definition in expression.args.get("define", []) 2496 ] 2497 definitions = self.expressions(sqls=definition_sqls) 2498 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2499 body = "".join( 2500 ( 2501 partition, 2502 order, 2503 measures, 2504 rows, 2505 after, 2506 pattern, 2507 define, 2508 ) 2509 ) 2510 alias = self.sql(expression, "alias") 2511 alias = f" {alias}" if alias else "" 2512 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2514 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2515 limit = expression.args.get("limit") 2516 2517 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2518 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2519 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2520 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2521 2522 return csv( 2523 *sqls, 2524 *[self.sql(join) for join in expression.args.get("joins") or []], 2525 self.sql(expression, "match"), 2526 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2527 self.sql(expression, "prewhere"), 2528 self.sql(expression, "where"), 2529 self.sql(expression, "connect"), 2530 self.sql(expression, "group"), 2531 self.sql(expression, "having"), 2532 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2533 self.sql(expression, "order"), 2534 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2535 *self.after_limit_modifiers(expression), 2536 self.options_modifier(expression), 2537 sep="", 2538 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2547 def offset_limit_modifiers( 2548 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2549 ) -> t.List[str]: 2550 return [ 2551 self.sql(expression, "offset") if fetch else self.sql(limit), 2552 self.sql(limit) if fetch else self.sql(expression, "offset"), 2553 ]
2560 def select_sql(self, expression: exp.Select) -> str: 2561 into = expression.args.get("into") 2562 if not self.SUPPORTS_SELECT_INTO and into: 2563 into.pop() 2564 2565 hint = self.sql(expression, "hint") 2566 distinct = self.sql(expression, "distinct") 2567 distinct = f" {distinct}" if distinct else "" 2568 kind = self.sql(expression, "kind") 2569 2570 limit = expression.args.get("limit") 2571 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2572 top = self.limit_sql(limit, top=True) 2573 limit.pop() 2574 else: 2575 top = "" 2576 2577 expressions = self.expressions(expression) 2578 2579 if kind: 2580 if kind in self.SELECT_KINDS: 2581 kind = f" AS {kind}" 2582 else: 2583 if kind == "STRUCT": 2584 expressions = self.expressions( 2585 sqls=[ 2586 self.sql( 2587 exp.Struct( 2588 expressions=[ 2589 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2590 if isinstance(e, exp.Alias) 2591 else e 2592 for e in expression.expressions 2593 ] 2594 ) 2595 ) 2596 ] 2597 ) 2598 kind = "" 2599 2600 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2601 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2602 2603 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2604 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2605 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2606 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2607 sql = self.query_modifiers( 2608 expression, 2609 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2610 self.sql(expression, "into", comment=False), 2611 self.sql(expression, "from", comment=False), 2612 ) 2613 2614 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2615 if expression.args.get("with"): 2616 sql = self.maybe_comment(sql, expression) 2617 expression.pop_comments() 2618 2619 sql = self.prepend_ctes(expression, sql) 2620 2621 if not self.SUPPORTS_SELECT_INTO and into: 2622 if into.args.get("temporary"): 2623 table_kind = " TEMPORARY" 2624 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2625 table_kind = " UNLOGGED" 2626 else: 2627 table_kind = "" 2628 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2629 2630 return sql
2642 def star_sql(self, expression: exp.Star) -> str: 2643 except_ = self.expressions(expression, key="except", flat=True) 2644 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2645 replace = self.expressions(expression, key="replace", flat=True) 2646 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2647 rename = self.expressions(expression, key="rename", flat=True) 2648 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2649 return f"*{except_}{replace}{rename}"
2665 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2666 alias = self.sql(expression, "alias") 2667 alias = f"{sep}{alias}" if alias else "" 2668 sample = self.sql(expression, "sample") 2669 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2670 alias = f"{sample}{alias}" 2671 2672 # Set to None so it's not generated again by self.query_modifiers() 2673 expression.set("sample", None) 2674 2675 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2676 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2677 return self.prepend_ctes(expression, sql)
2683 def unnest_sql(self, expression: exp.Unnest) -> str: 2684 args = self.expressions(expression, flat=True) 2685 2686 alias = expression.args.get("alias") 2687 offset = expression.args.get("offset") 2688 2689 if self.UNNEST_WITH_ORDINALITY: 2690 if alias and isinstance(offset, exp.Expression): 2691 alias.append("columns", offset) 2692 2693 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2694 columns = alias.columns 2695 alias = self.sql(columns[0]) if columns else "" 2696 else: 2697 alias = self.sql(alias) 2698 2699 alias = f" AS {alias}" if alias else alias 2700 if self.UNNEST_WITH_ORDINALITY: 2701 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2702 else: 2703 if isinstance(offset, exp.Expression): 2704 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2705 elif offset: 2706 suffix = f"{alias} WITH OFFSET" 2707 else: 2708 suffix = alias 2709 2710 return f"UNNEST({args}){suffix}"
2719 def window_sql(self, expression: exp.Window) -> str: 2720 this = self.sql(expression, "this") 2721 partition = self.partition_by_sql(expression) 2722 order = expression.args.get("order") 2723 order = self.order_sql(order, flat=True) if order else "" 2724 spec = self.sql(expression, "spec") 2725 alias = self.sql(expression, "alias") 2726 over = self.sql(expression, "over") or "OVER" 2727 2728 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2729 2730 first = expression.args.get("first") 2731 if first is None: 2732 first = "" 2733 else: 2734 first = "FIRST" if first else "LAST" 2735 2736 if not partition and not order and not spec and alias: 2737 return f"{this} {alias}" 2738 2739 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2740 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2746 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2747 kind = self.sql(expression, "kind") 2748 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2749 end = ( 2750 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2751 or "CURRENT ROW" 2752 ) 2753 return f"{kind} BETWEEN {start} AND {end}"
def
bracket_offset_expressions( self, expression: sqlglot.expressions.Bracket, index_offset: Optional[int] = None) -> List[sqlglot.expressions.Expression]:
2766 def bracket_offset_expressions( 2767 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2768 ) -> t.List[exp.Expression]: 2769 return apply_index_offset( 2770 expression.this, 2771 expression.expressions, 2772 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2773 )
2783 def any_sql(self, expression: exp.Any) -> str: 2784 this = self.sql(expression, "this") 2785 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2786 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2787 this = self.wrap(this) 2788 return f"ANY{this}" 2789 return f"ANY {this}"
2794 def case_sql(self, expression: exp.Case) -> str: 2795 this = self.sql(expression, "this") 2796 statements = [f"CASE {this}" if this else "CASE"] 2797 2798 for e in expression.args["ifs"]: 2799 statements.append(f"WHEN {self.sql(e, 'this')}") 2800 statements.append(f"THEN {self.sql(e, 'true')}") 2801 2802 default = self.sql(expression, "default") 2803 2804 if default: 2805 statements.append(f"ELSE {default}") 2806 2807 statements.append("END") 2808 2809 if self.pretty and self.too_wide(statements): 2810 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2811 2812 return " ".join(statements)
2829 def trim_sql(self, expression: exp.Trim) -> str: 2830 trim_type = self.sql(expression, "position") 2831 2832 if trim_type == "LEADING": 2833 func_name = "LTRIM" 2834 elif trim_type == "TRAILING": 2835 func_name = "RTRIM" 2836 else: 2837 func_name = "TRIM" 2838 2839 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]:
2841 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2842 args = expression.expressions 2843 if isinstance(expression, exp.ConcatWs): 2844 args = args[1:] # Skip the delimiter 2845 2846 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2847 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2848 2849 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2850 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2851 2852 return args
2854 def concat_sql(self, expression: exp.Concat) -> str: 2855 expressions = self.convert_concat_args(expression) 2856 2857 # Some dialects don't allow a single-argument CONCAT call 2858 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2859 return self.sql(expressions[0]) 2860 2861 return self.func("CONCAT", *expressions)
2872 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2873 expressions = self.expressions(expression, flat=True) 2874 expressions = f" ({expressions})" if expressions else "" 2875 reference = self.sql(expression, "reference") 2876 reference = f" {reference}" if reference else "" 2877 delete = self.sql(expression, "delete") 2878 delete = f" ON DELETE {delete}" if delete else "" 2879 update = self.sql(expression, "update") 2880 update = f" ON UPDATE {update}" if update else "" 2881 return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
2883 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2884 expressions = self.expressions(expression, flat=True) 2885 options = self.expressions(expression, key="options", flat=True, sep=" ") 2886 options = f" {options}" if options else "" 2887 return f"PRIMARY KEY ({expressions}){options}"
2900 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2901 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2902 2903 if expression.args.get("escape"): 2904 path = self.escape_str(path) 2905 2906 if self.QUOTE_JSON_PATH: 2907 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2908 2909 return path
2911 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2912 if isinstance(expression, exp.JSONPathPart): 2913 transform = self.TRANSFORMS.get(expression.__class__) 2914 if not callable(transform): 2915 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2916 return "" 2917 2918 return transform(self, expression) 2919 2920 if isinstance(expression, int): 2921 return str(expression) 2922 2923 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2924 escaped = expression.replace("'", "\\'") 2925 escaped = f"\\'{expression}\\'" 2926 else: 2927 escaped = expression.replace('"', '\\"') 2928 escaped = f'"{escaped}"' 2929 2930 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2935 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2936 null_handling = expression.args.get("null_handling") 2937 null_handling = f" {null_handling}" if null_handling else "" 2938 2939 unique_keys = expression.args.get("unique_keys") 2940 if unique_keys is not None: 2941 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2942 else: 2943 unique_keys = "" 2944 2945 return_type = self.sql(expression, "return_type") 2946 return_type = f" RETURNING {return_type}" if return_type else "" 2947 encoding = self.sql(expression, "encoding") 2948 encoding = f" ENCODING {encoding}" if encoding else "" 2949 2950 return self.func( 2951 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2952 *expression.expressions, 2953 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2954 )
2959 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2960 null_handling = expression.args.get("null_handling") 2961 null_handling = f" {null_handling}" if null_handling else "" 2962 return_type = self.sql(expression, "return_type") 2963 return_type = f" RETURNING {return_type}" if return_type else "" 2964 strict = " STRICT" if expression.args.get("strict") else "" 2965 return self.func( 2966 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2967 )
2969 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2970 this = self.sql(expression, "this") 2971 order = self.sql(expression, "order") 2972 null_handling = expression.args.get("null_handling") 2973 null_handling = f" {null_handling}" if null_handling else "" 2974 return_type = self.sql(expression, "return_type") 2975 return_type = f" RETURNING {return_type}" if return_type else "" 2976 strict = " STRICT" if expression.args.get("strict") else "" 2977 return self.func( 2978 "JSON_ARRAYAGG", 2979 this, 2980 suffix=f"{order}{null_handling}{return_type}{strict})", 2981 )
2983 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2984 path = self.sql(expression, "path") 2985 path = f" PATH {path}" if path else "" 2986 nested_schema = self.sql(expression, "nested_schema") 2987 2988 if nested_schema: 2989 return f"NESTED{path} {nested_schema}" 2990 2991 this = self.sql(expression, "this") 2992 kind = self.sql(expression, "kind") 2993 kind = f" {kind}" if kind else "" 2994 return f"{this}{kind}{path}"
2999 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3000 this = self.sql(expression, "this") 3001 path = self.sql(expression, "path") 3002 path = f", {path}" if path else "" 3003 error_handling = expression.args.get("error_handling") 3004 error_handling = f" {error_handling}" if error_handling else "" 3005 empty_handling = expression.args.get("empty_handling") 3006 empty_handling = f" {empty_handling}" if empty_handling else "" 3007 schema = self.sql(expression, "schema") 3008 return self.func( 3009 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3010 )
3012 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3013 this = self.sql(expression, "this") 3014 kind = self.sql(expression, "kind") 3015 path = self.sql(expression, "path") 3016 path = f" {path}" if path else "" 3017 as_json = " AS JSON" if expression.args.get("as_json") else "" 3018 return f"{this} {kind}{path}{as_json}"
3020 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3021 this = self.sql(expression, "this") 3022 path = self.sql(expression, "path") 3023 path = f", {path}" if path else "" 3024 expressions = self.expressions(expression) 3025 with_ = ( 3026 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3027 if expressions 3028 else "" 3029 ) 3030 return f"OPENJSON({this}{path}){with_}"
3032 def in_sql(self, expression: exp.In) -> str: 3033 query = expression.args.get("query") 3034 unnest = expression.args.get("unnest") 3035 field = expression.args.get("field") 3036 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3037 3038 if query: 3039 in_sql = self.sql(query) 3040 elif unnest: 3041 in_sql = self.in_unnest_op(unnest) 3042 elif field: 3043 in_sql = self.sql(field) 3044 else: 3045 in_sql = f"({self.expressions(expression, flat=True)})" 3046 3047 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3052 def interval_sql(self, expression: exp.Interval) -> str: 3053 unit = self.sql(expression, "unit") 3054 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3055 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3056 unit = f" {unit}" if unit else "" 3057 3058 if self.SINGLE_STRING_INTERVAL: 3059 this = expression.this.name if expression.this else "" 3060 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3061 3062 this = self.sql(expression, "this") 3063 if this: 3064 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3065 this = f" {this}" if unwrapped else f" ({this})" 3066 3067 return f"INTERVAL{this}{unit}"
3072 def reference_sql(self, expression: exp.Reference) -> str: 3073 this = self.sql(expression, "this") 3074 expressions = self.expressions(expression, flat=True) 3075 expressions = f"({expressions})" if expressions else "" 3076 options = self.expressions(expression, key="options", flat=True, sep=" ") 3077 options = f" {options}" if options else "" 3078 return f"REFERENCES {this}{expressions}{options}"
3080 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3081 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3082 parent = expression.parent 3083 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3084 return self.func( 3085 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3086 )
3106 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3107 alias = expression.args["alias"] 3108 3109 identifier_alias = isinstance(alias, exp.Identifier) 3110 literal_alias = isinstance(alias, exp.Literal) 3111 3112 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3113 alias.replace(exp.Literal.string(alias.output_name)) 3114 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3115 alias.replace(exp.to_identifier(alias.output_name)) 3116 3117 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:
3155 def connector_sql( 3156 self, 3157 expression: exp.Connector, 3158 op: str, 3159 stack: t.Optional[t.List[str | exp.Expression]] = None, 3160 ) -> str: 3161 if stack is not None: 3162 if expression.expressions: 3163 stack.append(self.expressions(expression, sep=f" {op} ")) 3164 else: 3165 stack.append(expression.right) 3166 if expression.comments and self.comments: 3167 for comment in expression.comments: 3168 if comment: 3169 op += f" /*{self.pad_comment(comment)}*/" 3170 stack.extend((op, expression.left)) 3171 return op 3172 3173 stack = [expression] 3174 sqls: t.List[str] = [] 3175 ops = set() 3176 3177 while stack: 3178 node = stack.pop() 3179 if isinstance(node, exp.Connector): 3180 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3181 else: 3182 sql = self.sql(node) 3183 if sqls and sqls[-1] in ops: 3184 sqls[-1] += f" {sql}" 3185 else: 3186 sqls.append(sql) 3187 3188 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3189 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3209 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3210 format_sql = self.sql(expression, "format") 3211 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3212 to_sql = self.sql(expression, "to") 3213 to_sql = f" {to_sql}" if to_sql else "" 3214 action = self.sql(expression, "action") 3215 action = f" {action}" if action else "" 3216 default = self.sql(expression, "default") 3217 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3218 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3232 def comment_sql(self, expression: exp.Comment) -> str: 3233 this = self.sql(expression, "this") 3234 kind = expression.args["kind"] 3235 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3236 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3237 expression_sql = self.sql(expression, "expression") 3238 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3240 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3241 this = self.sql(expression, "this") 3242 delete = " DELETE" if expression.args.get("delete") else "" 3243 recompress = self.sql(expression, "recompress") 3244 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3245 to_disk = self.sql(expression, "to_disk") 3246 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3247 to_volume = self.sql(expression, "to_volume") 3248 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3249 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3251 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3252 where = self.sql(expression, "where") 3253 group = self.sql(expression, "group") 3254 aggregates = self.expressions(expression, key="aggregates") 3255 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3256 3257 if not (where or group or aggregates) and len(expression.expressions) == 1: 3258 return f"TTL {self.expressions(expression, flat=True)}" 3259 3260 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3277 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3278 this = self.sql(expression, "this") 3279 3280 dtype = self.sql(expression, "dtype") 3281 if dtype: 3282 collate = self.sql(expression, "collate") 3283 collate = f" COLLATE {collate}" if collate else "" 3284 using = self.sql(expression, "using") 3285 using = f" USING {using}" if using else "" 3286 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3287 3288 default = self.sql(expression, "default") 3289 if default: 3290 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3291 3292 comment = self.sql(expression, "comment") 3293 if comment: 3294 return f"ALTER COLUMN {this} COMMENT {comment}" 3295 3296 allow_null = expression.args.get("allow_null") 3297 drop = expression.args.get("drop") 3298 3299 if not drop and not allow_null: 3300 self.unsupported("Unsupported ALTER COLUMN syntax") 3301 3302 if allow_null is not None: 3303 keyword = "DROP" if drop else "SET" 3304 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3305 3306 return f"ALTER COLUMN {this} DROP DEFAULT"
3322 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3323 compound = " COMPOUND" if expression.args.get("compound") else "" 3324 this = self.sql(expression, "this") 3325 expressions = self.expressions(expression, flat=True) 3326 expressions = f"({expressions})" if expressions else "" 3327 return f"ALTER{compound} SORTKEY {this or expressions}"
3329 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3330 if not self.RENAME_TABLE_WITH_DB: 3331 # Remove db from tables 3332 expression = expression.transform( 3333 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3334 ).assert_is(exp.AlterRename) 3335 this = self.sql(expression, "this") 3336 return f"RENAME TO {this}"
3348 def alter_sql(self, expression: exp.Alter) -> str: 3349 actions = expression.args["actions"] 3350 3351 if isinstance(actions[0], exp.ColumnDef): 3352 actions = self.add_column_sql(expression) 3353 elif isinstance(actions[0], exp.Schema): 3354 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3355 elif isinstance(actions[0], exp.Delete): 3356 actions = self.expressions(expression, key="actions", flat=True) 3357 elif isinstance(actions[0], exp.Query): 3358 actions = "AS " + self.expressions(expression, key="actions") 3359 else: 3360 actions = self.expressions(expression, key="actions", flat=True) 3361 3362 exists = " IF EXISTS" if expression.args.get("exists") else "" 3363 on_cluster = self.sql(expression, "cluster") 3364 on_cluster = f" {on_cluster}" if on_cluster else "" 3365 only = " ONLY" if expression.args.get("only") else "" 3366 options = self.expressions(expression, key="options") 3367 options = f", {options}" if options else "" 3368 kind = self.sql(expression, "kind") 3369 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3370 3371 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3373 def add_column_sql(self, expression: exp.Alter) -> str: 3374 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3375 return self.expressions( 3376 expression, 3377 key="actions", 3378 prefix="ADD COLUMN ", 3379 skip_first=True, 3380 ) 3381 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3391 def distinct_sql(self, expression: exp.Distinct) -> str: 3392 this = self.expressions(expression, flat=True) 3393 3394 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3395 case = exp.case() 3396 for arg in expression.expressions: 3397 case = case.when(arg.is_(exp.null()), exp.null()) 3398 this = self.sql(case.else_(f"({this})")) 3399 3400 this = f" {this}" if this else "" 3401 3402 on = self.sql(expression, "on") 3403 on = f" ON {on}" if on else "" 3404 return f"DISTINCT{this}{on}"
3433 def div_sql(self, expression: exp.Div) -> str: 3434 l, r = expression.left, expression.right 3435 3436 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3437 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3438 3439 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3440 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3441 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3442 3443 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3444 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3445 return self.sql( 3446 exp.cast( 3447 l / r, 3448 to=exp.DataType.Type.BIGINT, 3449 ) 3450 ) 3451 3452 return self.binary(expression, "/")
3548 def log_sql(self, expression: exp.Log) -> str: 3549 this = expression.this 3550 expr = expression.expression 3551 3552 if self.dialect.LOG_BASE_FIRST is False: 3553 this, expr = expr, this 3554 elif self.dialect.LOG_BASE_FIRST is None and expr: 3555 if this.name in ("2", "10"): 3556 return self.func(f"LOG{this.name}", expr) 3557 3558 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3559 3560 return self.func("LOG", this, expr)
3569 def binary(self, expression: exp.Binary, op: str) -> str: 3570 sqls: t.List[str] = [] 3571 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3572 binary_type = type(expression) 3573 3574 while stack: 3575 node = stack.pop() 3576 3577 if type(node) is binary_type: 3578 op_func = node.args.get("operator") 3579 if op_func: 3580 op = f"OPERATOR({self.sql(op_func)})" 3581 3582 stack.append(node.right) 3583 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3584 stack.append(node.left) 3585 else: 3586 sqls.append(self.sql(node)) 3587 3588 return "".join(sqls)
3597 def function_fallback_sql(self, expression: exp.Func) -> str: 3598 args = [] 3599 3600 for key in expression.arg_types: 3601 arg_value = expression.args.get(key) 3602 3603 if isinstance(arg_value, list): 3604 for value in arg_value: 3605 args.append(value) 3606 elif arg_value is not None: 3607 args.append(arg_value) 3608 3609 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3610 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3611 else: 3612 name = expression.sql_name() 3613 3614 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:
3616 def func( 3617 self, 3618 name: str, 3619 *args: t.Optional[exp.Expression | str], 3620 prefix: str = "(", 3621 suffix: str = ")", 3622 normalize: bool = True, 3623 ) -> str: 3624 name = self.normalize_func(name) if normalize else name 3625 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3627 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3628 arg_sqls = tuple( 3629 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3630 ) 3631 if self.pretty and self.too_wide(arg_sqls): 3632 return self.indent( 3633 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3634 ) 3635 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]:
3640 def format_time( 3641 self, 3642 expression: exp.Expression, 3643 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3644 inverse_time_trie: t.Optional[t.Dict] = None, 3645 ) -> t.Optional[str]: 3646 return format_time( 3647 self.sql(expression, "format"), 3648 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3649 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3650 )
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:
3652 def expressions( 3653 self, 3654 expression: t.Optional[exp.Expression] = None, 3655 key: t.Optional[str] = None, 3656 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3657 flat: bool = False, 3658 indent: bool = True, 3659 skip_first: bool = False, 3660 skip_last: bool = False, 3661 sep: str = ", ", 3662 prefix: str = "", 3663 dynamic: bool = False, 3664 new_line: bool = False, 3665 ) -> str: 3666 expressions = expression.args.get(key or "expressions") if expression else sqls 3667 3668 if not expressions: 3669 return "" 3670 3671 if flat: 3672 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3673 3674 num_sqls = len(expressions) 3675 result_sqls = [] 3676 3677 for i, e in enumerate(expressions): 3678 sql = self.sql(e, comment=False) 3679 if not sql: 3680 continue 3681 3682 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3683 3684 if self.pretty: 3685 if self.leading_comma: 3686 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3687 else: 3688 result_sqls.append( 3689 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3690 ) 3691 else: 3692 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3693 3694 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3695 if new_line: 3696 result_sqls.insert(0, "") 3697 result_sqls.append("") 3698 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3699 else: 3700 result_sql = "".join(result_sqls) 3701 3702 return ( 3703 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3704 if indent 3705 else result_sql 3706 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3708 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3709 flat = flat or isinstance(expression.parent, exp.Properties) 3710 expressions_sql = self.expressions(expression, flat=flat) 3711 if flat: 3712 return f"{op} {expressions_sql}" 3713 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3715 def naked_property(self, expression: exp.Property) -> str: 3716 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3717 if not property_name: 3718 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3719 return f"{property_name} {self.sql(expression, 'this')}"
3727 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3728 this = self.sql(expression, "this") 3729 expressions = self.no_identify(self.expressions, expression) 3730 expressions = ( 3731 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3732 ) 3733 return f"{this}{expressions}" if expressions.strip() != "" else this
3743 def when_sql(self, expression: exp.When) -> str: 3744 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3745 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3746 condition = self.sql(expression, "condition") 3747 condition = f" AND {condition}" if condition else "" 3748 3749 then_expression = expression.args.get("then") 3750 if isinstance(then_expression, exp.Insert): 3751 this = self.sql(then_expression, "this") 3752 this = f"INSERT {this}" if this else "INSERT" 3753 then = self.sql(then_expression, "expression") 3754 then = f"{this} VALUES {then}" if then else this 3755 elif isinstance(then_expression, exp.Update): 3756 if isinstance(then_expression.args.get("expressions"), exp.Star): 3757 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3758 else: 3759 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3760 else: 3761 then = self.sql(then_expression) 3762 return f"WHEN {matched}{source}{condition} THEN {then}"
3767 def merge_sql(self, expression: exp.Merge) -> str: 3768 table = expression.this 3769 table_alias = "" 3770 3771 hints = table.args.get("hints") 3772 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3773 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3774 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3775 3776 this = self.sql(table) 3777 using = f"USING {self.sql(expression, 'using')}" 3778 on = f"ON {self.sql(expression, 'on')}" 3779 whens = self.sql(expression, "whens") 3780 3781 returning = self.sql(expression, "returning") 3782 if returning: 3783 whens = f"{whens}{returning}" 3784 3785 sep = self.sep() 3786 3787 return self.prepend_ctes( 3788 expression, 3789 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3790 )
3796 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3797 if not self.SUPPORTS_TO_NUMBER: 3798 self.unsupported("Unsupported TO_NUMBER function") 3799 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3800 3801 fmt = expression.args.get("format") 3802 if not fmt: 3803 self.unsupported("Conversion format is required for TO_NUMBER") 3804 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3805 3806 return self.func("TO_NUMBER", expression.this, fmt)
3808 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3809 this = self.sql(expression, "this") 3810 kind = self.sql(expression, "kind") 3811 settings_sql = self.expressions(expression, key="settings", sep=" ") 3812 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3813 return f"{this}({kind}{args})"
3832 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3833 expressions = self.expressions(expression, flat=True) 3834 expressions = f" {self.wrap(expressions)}" if expressions else "" 3835 buckets = self.sql(expression, "buckets") 3836 kind = self.sql(expression, "kind") 3837 buckets = f" BUCKETS {buckets}" if buckets else "" 3838 order = self.sql(expression, "order") 3839 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3844 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3845 expressions = self.expressions(expression, key="expressions", flat=True) 3846 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3847 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3848 buckets = self.sql(expression, "buckets") 3849 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3851 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3852 this = self.sql(expression, "this") 3853 having = self.sql(expression, "having") 3854 3855 if having: 3856 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3857 3858 return self.func("ANY_VALUE", this)
3860 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3861 transform = self.func("TRANSFORM", *expression.expressions) 3862 row_format_before = self.sql(expression, "row_format_before") 3863 row_format_before = f" {row_format_before}" if row_format_before else "" 3864 record_writer = self.sql(expression, "record_writer") 3865 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3866 using = f" USING {self.sql(expression, 'command_script')}" 3867 schema = self.sql(expression, "schema") 3868 schema = f" AS {schema}" if schema else "" 3869 row_format_after = self.sql(expression, "row_format_after") 3870 row_format_after = f" {row_format_after}" if row_format_after else "" 3871 record_reader = self.sql(expression, "record_reader") 3872 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3873 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3875 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3876 key_block_size = self.sql(expression, "key_block_size") 3877 if key_block_size: 3878 return f"KEY_BLOCK_SIZE = {key_block_size}" 3879 3880 using = self.sql(expression, "using") 3881 if using: 3882 return f"USING {using}" 3883 3884 parser = self.sql(expression, "parser") 3885 if parser: 3886 return f"WITH PARSER {parser}" 3887 3888 comment = self.sql(expression, "comment") 3889 if comment: 3890 return f"COMMENT {comment}" 3891 3892 visible = expression.args.get("visible") 3893 if visible is not None: 3894 return "VISIBLE" if visible else "INVISIBLE" 3895 3896 engine_attr = self.sql(expression, "engine_attr") 3897 if engine_attr: 3898 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3899 3900 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3901 if secondary_engine_attr: 3902 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3903 3904 self.unsupported("Unsupported index constraint option.") 3905 return ""
3911 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3912 kind = self.sql(expression, "kind") 3913 kind = f"{kind} INDEX" if kind else "INDEX" 3914 this = self.sql(expression, "this") 3915 this = f" {this}" if this else "" 3916 index_type = self.sql(expression, "index_type") 3917 index_type = f" USING {index_type}" if index_type else "" 3918 expressions = self.expressions(expression, flat=True) 3919 expressions = f" ({expressions})" if expressions else "" 3920 options = self.expressions(expression, key="options", sep=" ") 3921 options = f" {options}" if options else "" 3922 return f"{kind}{this}{index_type}{expressions}{options}"
3924 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3925 if self.NVL2_SUPPORTED: 3926 return self.function_fallback_sql(expression) 3927 3928 case = exp.Case().when( 3929 expression.this.is_(exp.null()).not_(copy=False), 3930 expression.args["true"], 3931 copy=False, 3932 ) 3933 else_cond = expression.args.get("false") 3934 if else_cond: 3935 case.else_(else_cond, copy=False) 3936 3937 return self.sql(case)
3939 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3940 this = self.sql(expression, "this") 3941 expr = self.sql(expression, "expression") 3942 iterator = self.sql(expression, "iterator") 3943 condition = self.sql(expression, "condition") 3944 condition = f" IF {condition}" if condition else "" 3945 return f"{this} FOR {expr} IN {iterator}{condition}"
3953 def predict_sql(self, expression: exp.Predict) -> str: 3954 model = self.sql(expression, "this") 3955 model = f"MODEL {model}" 3956 table = self.sql(expression, "expression") 3957 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3958 parameters = self.sql(expression, "params_struct") 3959 return self.func("PREDICT", model, table, parameters or None)
3971 def toarray_sql(self, expression: exp.ToArray) -> str: 3972 arg = expression.this 3973 if not arg.type: 3974 from sqlglot.optimizer.annotate_types import annotate_types 3975 3976 arg = annotate_types(arg) 3977 3978 if arg.is_type(exp.DataType.Type.ARRAY): 3979 return self.sql(arg) 3980 3981 cond_for_null = arg.is_(exp.null()) 3982 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
3984 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3985 this = expression.this 3986 time_format = self.format_time(expression) 3987 3988 if time_format: 3989 return self.sql( 3990 exp.cast( 3991 exp.StrToTime(this=this, format=expression.args["format"]), 3992 exp.DataType.Type.TIME, 3993 ) 3994 ) 3995 3996 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3997 return self.sql(this) 3998 3999 return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4001 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4002 this = expression.this 4003 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4004 return self.sql(this) 4005 4006 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4008 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4009 this = expression.this 4010 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4011 return self.sql(this) 4012 4013 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4015 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4016 this = expression.this 4017 time_format = self.format_time(expression) 4018 4019 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4020 return self.sql( 4021 exp.cast( 4022 exp.StrToTime(this=this, format=expression.args["format"]), 4023 exp.DataType.Type.DATE, 4024 ) 4025 ) 4026 4027 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4028 return self.sql(this) 4029 4030 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4042 def lastday_sql(self, expression: exp.LastDay) -> str: 4043 if self.LAST_DAY_SUPPORTS_DATE_PART: 4044 return self.function_fallback_sql(expression) 4045 4046 unit = expression.text("unit") 4047 if unit and unit != "MONTH": 4048 self.unsupported("Date parts are not supported in LAST_DAY.") 4049 4050 return self.func("LAST_DAY", expression.this)
4059 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4060 if self.CAN_IMPLEMENT_ARRAY_ANY: 4061 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4062 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4063 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4064 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4065 4066 from sqlglot.dialects import Dialect 4067 4068 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4069 if self.dialect.__class__ != Dialect: 4070 self.unsupported("ARRAY_ANY is unsupported") 4071 4072 return self.function_fallback_sql(expression)
4074 def struct_sql(self, expression: exp.Struct) -> str: 4075 expression.set( 4076 "expressions", 4077 [ 4078 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4079 if isinstance(e, exp.PropertyEQ) 4080 else e 4081 for e in expression.expressions 4082 ], 4083 ) 4084 4085 return self.function_fallback_sql(expression)
4093 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4094 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4095 tables = f" {self.expressions(expression)}" 4096 4097 exists = " IF EXISTS" if expression.args.get("exists") else "" 4098 4099 on_cluster = self.sql(expression, "cluster") 4100 on_cluster = f" {on_cluster}" if on_cluster else "" 4101 4102 identity = self.sql(expression, "identity") 4103 identity = f" {identity} IDENTITY" if identity else "" 4104 4105 option = self.sql(expression, "option") 4106 option = f" {option}" if option else "" 4107 4108 partition = self.sql(expression, "partition") 4109 partition = f" {partition}" if partition else "" 4110 4111 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4115 def convert_sql(self, expression: exp.Convert) -> str: 4116 to = expression.this 4117 value = expression.expression 4118 style = expression.args.get("style") 4119 safe = expression.args.get("safe") 4120 strict = expression.args.get("strict") 4121 4122 if not to or not value: 4123 return "" 4124 4125 # Retrieve length of datatype and override to default if not specified 4126 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4127 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4128 4129 transformed: t.Optional[exp.Expression] = None 4130 cast = exp.Cast if strict else exp.TryCast 4131 4132 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4133 if isinstance(style, exp.Literal) and style.is_int: 4134 from sqlglot.dialects.tsql import TSQL 4135 4136 style_value = style.name 4137 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4138 if not converted_style: 4139 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4140 4141 fmt = exp.Literal.string(converted_style) 4142 4143 if to.this == exp.DataType.Type.DATE: 4144 transformed = exp.StrToDate(this=value, format=fmt) 4145 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4146 transformed = exp.StrToTime(this=value, format=fmt) 4147 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4148 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4149 elif to.this == exp.DataType.Type.TEXT: 4150 transformed = exp.TimeToStr(this=value, format=fmt) 4151 4152 if not transformed: 4153 transformed = cast(this=value, to=to, safe=safe) 4154 4155 return self.sql(transformed)
4215 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4216 option = self.sql(expression, "this") 4217 4218 if expression.expressions: 4219 upper = option.upper() 4220 4221 # Snowflake FILE_FORMAT options are separated by whitespace 4222 sep = " " if upper == "FILE_FORMAT" else ", " 4223 4224 # Databricks copy/format options do not set their list of values with EQ 4225 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4226 values = self.expressions(expression, flat=True, sep=sep) 4227 return f"{option}{op}({values})" 4228 4229 value = self.sql(expression, "expression") 4230 4231 if not value: 4232 return option 4233 4234 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4235 4236 return f"{option}{op}{value}"
4238 def credentials_sql(self, expression: exp.Credentials) -> str: 4239 cred_expr = expression.args.get("credentials") 4240 if isinstance(cred_expr, exp.Literal): 4241 # Redshift case: CREDENTIALS <string> 4242 credentials = self.sql(expression, "credentials") 4243 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4244 else: 4245 # Snowflake case: CREDENTIALS = (...) 4246 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4247 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4248 4249 storage = self.sql(expression, "storage") 4250 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4251 4252 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4253 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4254 4255 iam_role = self.sql(expression, "iam_role") 4256 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4257 4258 region = self.sql(expression, "region") 4259 region = f" REGION {region}" if region else "" 4260 4261 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4263 def copy_sql(self, expression: exp.Copy) -> str: 4264 this = self.sql(expression, "this") 4265 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4266 4267 credentials = self.sql(expression, "credentials") 4268 credentials = self.seg(credentials) if credentials else "" 4269 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4270 files = self.expressions(expression, key="files", flat=True) 4271 4272 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4273 params = self.expressions( 4274 expression, 4275 key="params", 4276 sep=sep, 4277 new_line=True, 4278 skip_last=True, 4279 skip_first=True, 4280 indent=self.COPY_PARAMS_ARE_WRAPPED, 4281 ) 4282 4283 if params: 4284 if self.COPY_PARAMS_ARE_WRAPPED: 4285 params = f" WITH ({params})" 4286 elif not self.pretty: 4287 params = f" {params}" 4288 4289 return f"COPY{this}{kind} {files}{credentials}{params}"
4294 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4295 on_sql = "ON" if expression.args.get("on") else "OFF" 4296 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4297 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4298 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4299 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4300 4301 if filter_col or retention_period: 4302 on_sql = self.func("ON", filter_col, retention_period) 4303 4304 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4306 def maskingpolicycolumnconstraint_sql( 4307 self, expression: exp.MaskingPolicyColumnConstraint 4308 ) -> str: 4309 this = self.sql(expression, "this") 4310 expressions = self.expressions(expression, flat=True) 4311 expressions = f" USING ({expressions})" if expressions else "" 4312 return f"MASKING POLICY {this}{expressions}"
4322 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4323 this = self.sql(expression, "this") 4324 expr = expression.expression 4325 4326 if isinstance(expr, exp.Func): 4327 # T-SQL's CLR functions are case sensitive 4328 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4329 else: 4330 expr = self.sql(expression, "expression") 4331 4332 return self.scope_resolution(expr, this)
4340 def rand_sql(self, expression: exp.Rand) -> str: 4341 lower = self.sql(expression, "lower") 4342 upper = self.sql(expression, "upper") 4343 4344 if lower and upper: 4345 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4346 return self.func("RAND", expression.this)
4348 def changes_sql(self, expression: exp.Changes) -> str: 4349 information = self.sql(expression, "information") 4350 information = f"INFORMATION => {information}" 4351 at_before = self.sql(expression, "at_before") 4352 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4353 end = self.sql(expression, "end") 4354 end = f"{self.seg('')}{end}" if end else "" 4355 4356 return f"CHANGES ({information}){at_before}{end}"
4358 def pad_sql(self, expression: exp.Pad) -> str: 4359 prefix = "L" if expression.args.get("is_left") else "R" 4360 4361 fill_pattern = self.sql(expression, "fill_pattern") or None 4362 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4363 fill_pattern = "' '" 4364 4365 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4371 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4372 generate_series = exp.GenerateSeries(**expression.args) 4373 4374 parent = expression.parent 4375 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4376 parent = parent.parent 4377 4378 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4379 return self.sql(exp.Unnest(expressions=[generate_series])) 4380 4381 if isinstance(parent, exp.Select): 4382 self.unsupported("GenerateSeries projection unnesting is not supported.") 4383 4384 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4386 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4387 exprs = expression.expressions 4388 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4389 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4390 else: 4391 rhs = self.expressions(expression) 4392 4393 return self.func(name, expression.this, rhs or None)
4395 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4396 if self.SUPPORTS_CONVERT_TIMEZONE: 4397 return self.function_fallback_sql(expression) 4398 4399 source_tz = expression.args.get("source_tz") 4400 target_tz = expression.args.get("target_tz") 4401 timestamp = expression.args.get("timestamp") 4402 4403 if source_tz and timestamp: 4404 timestamp = exp.AtTimeZone( 4405 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4406 ) 4407 4408 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4409 4410 return self.sql(expr)
4412 def json_sql(self, expression: exp.JSON) -> str: 4413 this = self.sql(expression, "this") 4414 this = f" {this}" if this else "" 4415 4416 _with = expression.args.get("with") 4417 4418 if _with is None: 4419 with_sql = "" 4420 elif not _with: 4421 with_sql = " WITHOUT" 4422 else: 4423 with_sql = " WITH" 4424 4425 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4426 4427 return f"JSON{this}{with_sql}{unique_sql}"
4429 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4430 def _generate_on_options(arg: t.Any) -> str: 4431 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4432 4433 path = self.sql(expression, "path") 4434 returning = self.sql(expression, "returning") 4435 returning = f" RETURNING {returning}" if returning else "" 4436 4437 on_condition = self.sql(expression, "on_condition") 4438 on_condition = f" {on_condition}" if on_condition else "" 4439 4440 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4442 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4443 else_ = "ELSE " if expression.args.get("else_") else "" 4444 condition = self.sql(expression, "expression") 4445 condition = f"WHEN {condition} THEN " if condition else else_ 4446 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4447 return f"{condition}{insert}"
4455 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4456 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4457 empty = expression.args.get("empty") 4458 empty = ( 4459 f"DEFAULT {empty} ON EMPTY" 4460 if isinstance(empty, exp.Expression) 4461 else self.sql(expression, "empty") 4462 ) 4463 4464 error = expression.args.get("error") 4465 error = ( 4466 f"DEFAULT {error} ON ERROR" 4467 if isinstance(error, exp.Expression) 4468 else self.sql(expression, "error") 4469 ) 4470 4471 if error and empty: 4472 error = ( 4473 f"{empty} {error}" 4474 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4475 else f"{error} {empty}" 4476 ) 4477 empty = "" 4478 4479 null = self.sql(expression, "null") 4480 4481 return f"{empty}{error}{null}"
4487 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4488 this = self.sql(expression, "this") 4489 path = self.sql(expression, "path") 4490 4491 passing = self.expressions(expression, "passing") 4492 passing = f" PASSING {passing}" if passing else "" 4493 4494 on_condition = self.sql(expression, "on_condition") 4495 on_condition = f" {on_condition}" if on_condition else "" 4496 4497 path = f"{path}{passing}{on_condition}" 4498 4499 return self.func("JSON_EXISTS", this, path)
4501 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4502 array_agg = self.function_fallback_sql(expression) 4503 4504 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4505 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4506 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4507 parent = expression.parent 4508 if isinstance(parent, exp.Filter): 4509 parent_cond = parent.expression.this 4510 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4511 else: 4512 this = expression.this 4513 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4514 if this.find(exp.Column): 4515 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4516 this_sql = ( 4517 self.expressions(this) 4518 if isinstance(this, exp.Distinct) 4519 else self.sql(expression, "this") 4520 ) 4521 4522 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4523 4524 return array_agg
4532 def grant_sql(self, expression: exp.Grant) -> str: 4533 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4534 4535 kind = self.sql(expression, "kind") 4536 kind = f" {kind}" if kind else "" 4537 4538 securable = self.sql(expression, "securable") 4539 securable = f" {securable}" if securable else "" 4540 4541 principals = self.expressions(expression, key="principals", flat=True) 4542 4543 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4544 4545 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4569 def overlay_sql(self, expression: exp.Overlay): 4570 this = self.sql(expression, "this") 4571 expr = self.sql(expression, "expression") 4572 from_sql = self.sql(expression, "from") 4573 for_sql = self.sql(expression, "for") 4574 for_sql = f" FOR {for_sql}" if for_sql else "" 4575 4576 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4582 def string_sql(self, expression: exp.String) -> str: 4583 this = expression.this 4584 zone = expression.args.get("zone") 4585 4586 if zone: 4587 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4588 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4589 # set for source_tz to transpile the time conversion before the STRING cast 4590 this = exp.ConvertTimezone( 4591 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4592 ) 4593 4594 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4604 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4605 filler = self.sql(expression, "this") 4606 filler = f" {filler}" if filler else "" 4607 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4608 return f"TRUNCATE{filler} {with_count}"
4610 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4611 if self.SUPPORTS_UNIX_SECONDS: 4612 return self.function_fallback_sql(expression) 4613 4614 start_ts = exp.cast( 4615 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4616 ) 4617 4618 return self.sql( 4619 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4620 )
4622 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4623 dim = expression.expression 4624 4625 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4626 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4627 if not (dim.is_int and dim.name == "1"): 4628 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4629 dim = None 4630 4631 # If dimension is required but not specified, default initialize it 4632 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4633 dim = exp.Literal.number(1) 4634 4635 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4637 def attach_sql(self, expression: exp.Attach) -> str: 4638 this = self.sql(expression, "this") 4639 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4640 expressions = self.expressions(expression) 4641 expressions = f" ({expressions})" if expressions else "" 4642 4643 return f"ATTACH{exists_sql} {this}{expressions}"
4657 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4658 this_sql = self.sql(expression, "this") 4659 if isinstance(expression.this, exp.Table): 4660 this_sql = f"TABLE {this_sql}" 4661 4662 return self.func( 4663 "FEATURES_AT_TIME", 4664 this_sql, 4665 expression.args.get("time"), 4666 expression.args.get("num_rows"), 4667 expression.args.get("ignore_feature_nulls"), 4668 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4675 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4676 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4677 encode = f"{encode} {self.sql(expression, 'this')}" 4678 4679 properties = expression.args.get("properties") 4680 if properties: 4681 encode = f"{encode} {self.properties(properties)}" 4682 4683 return encode
4685 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4686 this = self.sql(expression, "this") 4687 include = f"INCLUDE {this}" 4688 4689 column_def = self.sql(expression, "column_def") 4690 if column_def: 4691 include = f"{include} {column_def}" 4692 4693 alias = self.sql(expression, "alias") 4694 if alias: 4695 include = f"{include} AS {alias}" 4696 4697 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4703 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4704 partitions = self.expressions(expression, "partition_expressions") 4705 create = self.expressions(expression, "create_expressions") 4706 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4708 def partitionbyrangepropertydynamic_sql( 4709 self, expression: exp.PartitionByRangePropertyDynamic 4710 ) -> str: 4711 start = self.sql(expression, "start") 4712 end = self.sql(expression, "end") 4713 4714 every = expression.args["every"] 4715 if isinstance(every, exp.Interval) and every.this.is_string: 4716 every.this.replace(exp.Literal.number(every.name)) 4717 4718 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4731 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4732 kind = self.sql(expression, "kind") 4733 option = self.sql(expression, "option") 4734 option = f" {option}" if option else "" 4735 this = self.sql(expression, "this") 4736 this = f" {this}" if this else "" 4737 columns = self.expressions(expression) 4738 columns = f" {columns}" if columns else "" 4739 return f"{kind}{option} STATISTICS{this}{columns}"
4741 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4742 this = self.sql(expression, "this") 4743 columns = self.expressions(expression) 4744 inner_expression = self.sql(expression, "expression") 4745 inner_expression = f" {inner_expression}" if inner_expression else "" 4746 update_options = self.sql(expression, "update_options") 4747 update_options = f" {update_options} UPDATE" if update_options else "" 4748 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4759 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4760 kind = self.sql(expression, "kind") 4761 this = self.sql(expression, "this") 4762 this = f" {this}" if this else "" 4763 inner_expression = self.sql(expression, "expression") 4764 return f"VALIDATE {kind}{this}{inner_expression}"
4766 def analyze_sql(self, expression: exp.Analyze) -> str: 4767 options = self.expressions(expression, key="options", sep=" ") 4768 options = f" {options}" if options else "" 4769 kind = self.sql(expression, "kind") 4770 kind = f" {kind}" if kind else "" 4771 this = self.sql(expression, "this") 4772 this = f" {this}" if this else "" 4773 mode = self.sql(expression, "mode") 4774 mode = f" {mode}" if mode else "" 4775 properties = self.sql(expression, "properties") 4776 properties = f" {properties}" if properties else "" 4777 partition = self.sql(expression, "partition") 4778 partition = f" {partition}" if partition else "" 4779 inner_expression = self.sql(expression, "expression") 4780 inner_expression = f" {inner_expression}" if inner_expression else "" 4781 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4783 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4784 this = self.sql(expression, "this") 4785 namespaces = self.expressions(expression, key="namespaces") 4786 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4787 passing = self.expressions(expression, key="passing") 4788 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4789 columns = self.expressions(expression, key="columns") 4790 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4791 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4792 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4798 def export_sql(self, expression: exp.Export) -> str: 4799 this = self.sql(expression, "this") 4800 connection = self.sql(expression, "connection") 4801 connection = f"WITH CONNECTION {connection} " if connection else "" 4802 options = self.sql(expression, "options") 4803 return f"EXPORT DATA {connection}{options} AS {this}"
4808 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4809 variable = self.sql(expression, "this") 4810 default = self.sql(expression, "default") 4811 default = f" = {default}" if default else "" 4812 4813 kind = self.sql(expression, "kind") 4814 if isinstance(expression.args.get("kind"), exp.Schema): 4815 kind = f"TABLE {kind}" 4816 4817 return f"{variable} AS {kind}{default}"
4819 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4820 kind = self.sql(expression, "kind") 4821 this = self.sql(expression, "this") 4822 set = self.sql(expression, "expression") 4823 using = self.sql(expression, "using") 4824 using = f" USING {using}" if using else "" 4825 4826 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4827 4828 return f"{kind_sql} {this} SET {set}{using}"
def
combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str: