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.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 195 exp.TemporaryProperty: lambda *_: "TEMPORARY", 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.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 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 exp.ForceProperty: lambda *_: "FORCE", 215 } 216 217 # Whether null ordering is supported in order by 218 # True: Full Support, None: No support, False: No support for certain cases 219 # such as window specifications, aggregate functions etc 220 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 221 222 # Whether ignore nulls is inside the agg or outside. 223 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 224 IGNORE_NULLS_IN_FUNC = False 225 226 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 227 LOCKING_READS_SUPPORTED = False 228 229 # Whether the EXCEPT and INTERSECT operations can return duplicates 230 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 231 232 # Wrap derived values in parens, usually standard but spark doesn't support it 233 WRAP_DERIVED_VALUES = True 234 235 # Whether create function uses an AS before the RETURN 236 CREATE_FUNCTION_RETURN_AS = True 237 238 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 239 MATCHED_BY_SOURCE = True 240 241 # Whether the INTERVAL expression works only with values like '1 day' 242 SINGLE_STRING_INTERVAL = False 243 244 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 245 INTERVAL_ALLOWS_PLURAL_FORM = True 246 247 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 248 LIMIT_FETCH = "ALL" 249 250 # Whether limit and fetch allows expresions or just limits 251 LIMIT_ONLY_LITERALS = False 252 253 # Whether a table is allowed to be renamed with a db 254 RENAME_TABLE_WITH_DB = True 255 256 # The separator for grouping sets and rollups 257 GROUPINGS_SEP = "," 258 259 # The string used for creating an index on a table 260 INDEX_ON = "ON" 261 262 # Whether join hints should be generated 263 JOIN_HINTS = True 264 265 # Whether table hints should be generated 266 TABLE_HINTS = True 267 268 # Whether query hints should be generated 269 QUERY_HINTS = True 270 271 # What kind of separator to use for query hints 272 QUERY_HINT_SEP = ", " 273 274 # Whether comparing against booleans (e.g. x IS TRUE) is supported 275 IS_BOOL_ALLOWED = True 276 277 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 278 DUPLICATE_KEY_UPDATE_WITH_SET = True 279 280 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 281 LIMIT_IS_TOP = False 282 283 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 284 RETURNING_END = True 285 286 # Whether to generate an unquoted value for EXTRACT's date part argument 287 EXTRACT_ALLOWS_QUOTES = True 288 289 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 290 TZ_TO_WITH_TIME_ZONE = False 291 292 # Whether the NVL2 function is supported 293 NVL2_SUPPORTED = True 294 295 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 296 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 297 298 # Whether VALUES statements can be used as derived tables. 299 # MySQL 5 and Redshift do not allow this, so when False, it will convert 300 # SELECT * VALUES into SELECT UNION 301 VALUES_AS_TABLE = True 302 303 # Whether the word COLUMN is included when adding a column with ALTER TABLE 304 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 305 306 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 307 UNNEST_WITH_ORDINALITY = True 308 309 # Whether FILTER (WHERE cond) can be used for conditional aggregation 310 AGGREGATE_FILTER_SUPPORTED = True 311 312 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 313 SEMI_ANTI_JOIN_WITH_SIDE = True 314 315 # Whether to include the type of a computed column in the CREATE DDL 316 COMPUTED_COLUMN_WITH_TYPE = True 317 318 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 319 SUPPORTS_TABLE_COPY = True 320 321 # Whether parentheses are required around the table sample's expression 322 TABLESAMPLE_REQUIRES_PARENS = True 323 324 # Whether a table sample clause's size needs to be followed by the ROWS keyword 325 TABLESAMPLE_SIZE_IS_ROWS = True 326 327 # The keyword(s) to use when generating a sample clause 328 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 329 330 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 331 TABLESAMPLE_WITH_METHOD = True 332 333 # The keyword to use when specifying the seed of a sample clause 334 TABLESAMPLE_SEED_KEYWORD = "SEED" 335 336 # Whether COLLATE is a function instead of a binary operator 337 COLLATE_IS_FUNC = False 338 339 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 340 DATA_TYPE_SPECIFIERS_ALLOWED = False 341 342 # Whether conditions require booleans WHERE x = 0 vs WHERE x 343 ENSURE_BOOLS = False 344 345 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 346 CTE_RECURSIVE_KEYWORD_REQUIRED = True 347 348 # Whether CONCAT requires >1 arguments 349 SUPPORTS_SINGLE_ARG_CONCAT = True 350 351 # Whether LAST_DAY function supports a date part argument 352 LAST_DAY_SUPPORTS_DATE_PART = True 353 354 # Whether named columns are allowed in table aliases 355 SUPPORTS_TABLE_ALIAS_COLUMNS = True 356 357 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 358 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 359 360 # What delimiter to use for separating JSON key/value pairs 361 JSON_KEY_VALUE_PAIR_SEP = ":" 362 363 # INSERT OVERWRITE TABLE x override 364 INSERT_OVERWRITE = " OVERWRITE TABLE" 365 366 # Whether the SELECT .. INTO syntax is used instead of CTAS 367 SUPPORTS_SELECT_INTO = False 368 369 # Whether UNLOGGED tables can be created 370 SUPPORTS_UNLOGGED_TABLES = False 371 372 # Whether the CREATE TABLE LIKE statement is supported 373 SUPPORTS_CREATE_TABLE_LIKE = True 374 375 # Whether the LikeProperty needs to be specified inside of the schema clause 376 LIKE_PROPERTY_INSIDE_SCHEMA = False 377 378 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 379 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 380 MULTI_ARG_DISTINCT = True 381 382 # Whether the JSON extraction operators expect a value of type JSON 383 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 384 385 # Whether bracketed keys like ["foo"] are supported in JSON paths 386 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 387 388 # Whether to escape keys using single quotes in JSON paths 389 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 390 391 # The JSONPathPart expressions supported by this dialect 392 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 393 394 # Whether any(f(x) for x in array) can be implemented by this dialect 395 CAN_IMPLEMENT_ARRAY_ANY = False 396 397 # Whether the function TO_NUMBER is supported 398 SUPPORTS_TO_NUMBER = True 399 400 # Whether or not set op modifiers apply to the outer set op or select. 401 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 402 # True means limit 1 happens after the set op, False means it it happens on y. 403 SET_OP_MODIFIERS = True 404 405 # Whether parameters from COPY statement are wrapped in parentheses 406 COPY_PARAMS_ARE_WRAPPED = True 407 408 # Whether values of params are set with "=" token or empty space 409 COPY_PARAMS_EQ_REQUIRED = False 410 411 # Whether COPY statement has INTO keyword 412 COPY_HAS_INTO_KEYWORD = True 413 414 # Whether the conditional TRY(expression) function is supported 415 TRY_SUPPORTED = True 416 417 # Whether the UESCAPE syntax in unicode strings is supported 418 SUPPORTS_UESCAPE = True 419 420 # The keyword to use when generating a star projection with excluded columns 421 STAR_EXCEPT = "EXCEPT" 422 423 # The HEX function name 424 HEX_FUNC = "HEX" 425 426 # The keywords to use when prefixing & separating WITH based properties 427 WITH_PROPERTIES_PREFIX = "WITH" 428 429 # Whether to quote the generated expression of exp.JsonPath 430 QUOTE_JSON_PATH = True 431 432 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 433 PAD_FILL_PATTERN_IS_REQUIRED = False 434 435 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 436 SUPPORTS_EXPLODING_PROJECTIONS = True 437 438 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 439 ARRAY_CONCAT_IS_VAR_LEN = True 440 441 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 442 SUPPORTS_CONVERT_TIMEZONE = False 443 444 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 445 SUPPORTS_MEDIAN = True 446 447 # Whether UNIX_SECONDS(timestamp) is supported 448 SUPPORTS_UNIX_SECONDS = False 449 450 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 451 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 452 453 # The function name of the exp.ArraySize expression 454 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 455 456 # The syntax to use when altering the type of a column 457 ALTER_SET_TYPE = "SET DATA TYPE" 458 459 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 460 # None -> Doesn't support it at all 461 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 462 # True (Postgres) -> Explicitly requires it 463 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 464 465 TYPE_MAPPING = { 466 exp.DataType.Type.DATETIME2: "TIMESTAMP", 467 exp.DataType.Type.NCHAR: "CHAR", 468 exp.DataType.Type.NVARCHAR: "VARCHAR", 469 exp.DataType.Type.MEDIUMTEXT: "TEXT", 470 exp.DataType.Type.LONGTEXT: "TEXT", 471 exp.DataType.Type.TINYTEXT: "TEXT", 472 exp.DataType.Type.BLOB: "VARBINARY", 473 exp.DataType.Type.MEDIUMBLOB: "BLOB", 474 exp.DataType.Type.LONGBLOB: "BLOB", 475 exp.DataType.Type.TINYBLOB: "BLOB", 476 exp.DataType.Type.INET: "INET", 477 exp.DataType.Type.ROWVERSION: "VARBINARY", 478 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 479 } 480 481 TIME_PART_SINGULARS = { 482 "MICROSECONDS": "MICROSECOND", 483 "SECONDS": "SECOND", 484 "MINUTES": "MINUTE", 485 "HOURS": "HOUR", 486 "DAYS": "DAY", 487 "WEEKS": "WEEK", 488 "MONTHS": "MONTH", 489 "QUARTERS": "QUARTER", 490 "YEARS": "YEAR", 491 } 492 493 AFTER_HAVING_MODIFIER_TRANSFORMS = { 494 "cluster": lambda self, e: self.sql(e, "cluster"), 495 "distribute": lambda self, e: self.sql(e, "distribute"), 496 "sort": lambda self, e: self.sql(e, "sort"), 497 "windows": lambda self, e: ( 498 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 499 if e.args.get("windows") 500 else "" 501 ), 502 "qualify": lambda self, e: self.sql(e, "qualify"), 503 } 504 505 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 506 507 STRUCT_DELIMITER = ("<", ">") 508 509 PARAMETER_TOKEN = "@" 510 NAMED_PLACEHOLDER_TOKEN = ":" 511 512 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 513 514 PROPERTIES_LOCATION = { 515 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 517 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 520 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 521 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 523 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 526 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 527 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 529 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 530 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 532 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 533 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 535 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 539 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 542 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 543 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 544 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 545 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 546 exp.HeapProperty: exp.Properties.Location.POST_WITH, 547 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 549 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 552 exp.JournalProperty: exp.Properties.Location.POST_NAME, 553 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 558 exp.LogProperty: exp.Properties.Location.POST_NAME, 559 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 560 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 561 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 562 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 563 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 564 exp.Order: exp.Properties.Location.POST_SCHEMA, 565 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 567 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 569 exp.Property: exp.Properties.Location.POST_WITH, 570 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 577 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 578 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 579 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 580 exp.Set: exp.Properties.Location.POST_SCHEMA, 581 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 582 exp.SetProperty: exp.Properties.Location.POST_CREATE, 583 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 584 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 585 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 586 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 588 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 589 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 592 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 593 exp.Tags: exp.Properties.Location.POST_WITH, 594 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 595 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 596 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 597 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 598 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 599 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 600 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 601 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 602 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 603 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 604 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 605 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 606 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 607 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 608 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 609 } 610 611 # Keywords that can't be used as unquoted identifier names 612 RESERVED_KEYWORDS: t.Set[str] = set() 613 614 # Expressions whose comments are separated from them for better formatting 615 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 616 exp.Command, 617 exp.Create, 618 exp.Describe, 619 exp.Delete, 620 exp.Drop, 621 exp.From, 622 exp.Insert, 623 exp.Join, 624 exp.MultitableInserts, 625 exp.Select, 626 exp.SetOperation, 627 exp.Update, 628 exp.Where, 629 exp.With, 630 ) 631 632 # Expressions that should not have their comments generated in maybe_comment 633 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 634 exp.Binary, 635 exp.SetOperation, 636 ) 637 638 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 639 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 640 exp.Column, 641 exp.Literal, 642 exp.Neg, 643 exp.Paren, 644 ) 645 646 PARAMETERIZABLE_TEXT_TYPES = { 647 exp.DataType.Type.NVARCHAR, 648 exp.DataType.Type.VARCHAR, 649 exp.DataType.Type.CHAR, 650 exp.DataType.Type.NCHAR, 651 } 652 653 # Expressions that need to have all CTEs under them bubbled up to them 654 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 655 656 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 657 658 __slots__ = ( 659 "pretty", 660 "identify", 661 "normalize", 662 "pad", 663 "_indent", 664 "normalize_functions", 665 "unsupported_level", 666 "max_unsupported", 667 "leading_comma", 668 "max_text_width", 669 "comments", 670 "dialect", 671 "unsupported_messages", 672 "_escaped_quote_end", 673 "_escaped_identifier_end", 674 "_next_name", 675 "_identifier_start", 676 "_identifier_end", 677 "_quote_json_path_key_using_brackets", 678 ) 679 680 def __init__( 681 self, 682 pretty: t.Optional[bool] = None, 683 identify: str | bool = False, 684 normalize: bool = False, 685 pad: int = 2, 686 indent: int = 2, 687 normalize_functions: t.Optional[str | bool] = None, 688 unsupported_level: ErrorLevel = ErrorLevel.WARN, 689 max_unsupported: int = 3, 690 leading_comma: bool = False, 691 max_text_width: int = 80, 692 comments: bool = True, 693 dialect: DialectType = None, 694 ): 695 import sqlglot 696 from sqlglot.dialects import Dialect 697 698 self.pretty = pretty if pretty is not None else sqlglot.pretty 699 self.identify = identify 700 self.normalize = normalize 701 self.pad = pad 702 self._indent = indent 703 self.unsupported_level = unsupported_level 704 self.max_unsupported = max_unsupported 705 self.leading_comma = leading_comma 706 self.max_text_width = max_text_width 707 self.comments = comments 708 self.dialect = Dialect.get_or_raise(dialect) 709 710 # This is both a Dialect property and a Generator argument, so we prioritize the latter 711 self.normalize_functions = ( 712 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 713 ) 714 715 self.unsupported_messages: t.List[str] = [] 716 self._escaped_quote_end: str = ( 717 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 718 ) 719 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 720 721 self._next_name = name_sequence("_t") 722 723 self._identifier_start = self.dialect.IDENTIFIER_START 724 self._identifier_end = self.dialect.IDENTIFIER_END 725 726 self._quote_json_path_key_using_brackets = True 727 728 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 729 """ 730 Generates the SQL string corresponding to the given syntax tree. 731 732 Args: 733 expression: The syntax tree. 734 copy: Whether to copy the expression. The generator performs mutations so 735 it is safer to copy. 736 737 Returns: 738 The SQL string corresponding to `expression`. 739 """ 740 if copy: 741 expression = expression.copy() 742 743 expression = self.preprocess(expression) 744 745 self.unsupported_messages = [] 746 sql = self.sql(expression).strip() 747 748 if self.pretty: 749 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 750 751 if self.unsupported_level == ErrorLevel.IGNORE: 752 return sql 753 754 if self.unsupported_level == ErrorLevel.WARN: 755 for msg in self.unsupported_messages: 756 logger.warning(msg) 757 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 758 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 759 760 return sql 761 762 def preprocess(self, expression: exp.Expression) -> exp.Expression: 763 """Apply generic preprocessing transformations to a given expression.""" 764 expression = self._move_ctes_to_top_level(expression) 765 766 if self.ENSURE_BOOLS: 767 from sqlglot.transforms import ensure_bools 768 769 expression = ensure_bools(expression) 770 771 return expression 772 773 def _move_ctes_to_top_level(self, expression: E) -> E: 774 if ( 775 not expression.parent 776 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 777 and any(node.parent is not expression for node in expression.find_all(exp.With)) 778 ): 779 from sqlglot.transforms import move_ctes_to_top_level 780 781 expression = move_ctes_to_top_level(expression) 782 return expression 783 784 def unsupported(self, message: str) -> None: 785 if self.unsupported_level == ErrorLevel.IMMEDIATE: 786 raise UnsupportedError(message) 787 self.unsupported_messages.append(message) 788 789 def sep(self, sep: str = " ") -> str: 790 return f"{sep.strip()}\n" if self.pretty else sep 791 792 def seg(self, sql: str, sep: str = " ") -> str: 793 return f"{self.sep(sep)}{sql}" 794 795 def pad_comment(self, comment: str) -> str: 796 comment = " " + comment if comment[0].strip() else comment 797 comment = comment + " " if comment[-1].strip() else comment 798 return comment 799 800 def maybe_comment( 801 self, 802 sql: str, 803 expression: t.Optional[exp.Expression] = None, 804 comments: t.Optional[t.List[str]] = None, 805 separated: bool = False, 806 ) -> str: 807 comments = ( 808 ((expression and expression.comments) if comments is None else comments) # type: ignore 809 if self.comments 810 else None 811 ) 812 813 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 814 return sql 815 816 comments_sql = " ".join( 817 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 818 ) 819 820 if not comments_sql: 821 return sql 822 823 comments_sql = self._replace_line_breaks(comments_sql) 824 825 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 826 return ( 827 f"{self.sep()}{comments_sql}{sql}" 828 if not sql or sql[0].isspace() 829 else f"{comments_sql}{self.sep()}{sql}" 830 ) 831 832 return f"{sql} {comments_sql}" 833 834 def wrap(self, expression: exp.Expression | str) -> str: 835 this_sql = ( 836 self.sql(expression) 837 if isinstance(expression, exp.UNWRAPPED_QUERIES) 838 else self.sql(expression, "this") 839 ) 840 if not this_sql: 841 return "()" 842 843 this_sql = self.indent(this_sql, level=1, pad=0) 844 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 845 846 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 847 original = self.identify 848 self.identify = False 849 result = func(*args, **kwargs) 850 self.identify = original 851 return result 852 853 def normalize_func(self, name: str) -> str: 854 if self.normalize_functions == "upper" or self.normalize_functions is True: 855 return name.upper() 856 if self.normalize_functions == "lower": 857 return name.lower() 858 return name 859 860 def indent( 861 self, 862 sql: str, 863 level: int = 0, 864 pad: t.Optional[int] = None, 865 skip_first: bool = False, 866 skip_last: bool = False, 867 ) -> str: 868 if not self.pretty or not sql: 869 return sql 870 871 pad = self.pad if pad is None else pad 872 lines = sql.split("\n") 873 874 return "\n".join( 875 ( 876 line 877 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 878 else f"{' ' * (level * self._indent + pad)}{line}" 879 ) 880 for i, line in enumerate(lines) 881 ) 882 883 def sql( 884 self, 885 expression: t.Optional[str | exp.Expression], 886 key: t.Optional[str] = None, 887 comment: bool = True, 888 ) -> str: 889 if not expression: 890 return "" 891 892 if isinstance(expression, str): 893 return expression 894 895 if key: 896 value = expression.args.get(key) 897 if value: 898 return self.sql(value) 899 return "" 900 901 transform = self.TRANSFORMS.get(expression.__class__) 902 903 if callable(transform): 904 sql = transform(self, expression) 905 elif isinstance(expression, exp.Expression): 906 exp_handler_name = f"{expression.key}_sql" 907 908 if hasattr(self, exp_handler_name): 909 sql = getattr(self, exp_handler_name)(expression) 910 elif isinstance(expression, exp.Func): 911 sql = self.function_fallback_sql(expression) 912 elif isinstance(expression, exp.Property): 913 sql = self.property_sql(expression) 914 else: 915 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 916 else: 917 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 918 919 return self.maybe_comment(sql, expression) if self.comments and comment else sql 920 921 def uncache_sql(self, expression: exp.Uncache) -> str: 922 table = self.sql(expression, "this") 923 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 924 return f"UNCACHE TABLE{exists_sql} {table}" 925 926 def cache_sql(self, expression: exp.Cache) -> str: 927 lazy = " LAZY" if expression.args.get("lazy") else "" 928 table = self.sql(expression, "this") 929 options = expression.args.get("options") 930 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 931 sql = self.sql(expression, "expression") 932 sql = f" AS{self.sep()}{sql}" if sql else "" 933 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 934 return self.prepend_ctes(expression, sql) 935 936 def characterset_sql(self, expression: exp.CharacterSet) -> str: 937 if isinstance(expression.parent, exp.Cast): 938 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 939 default = "DEFAULT " if expression.args.get("default") else "" 940 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 941 942 def column_parts(self, expression: exp.Column) -> str: 943 return ".".join( 944 self.sql(part) 945 for part in ( 946 expression.args.get("catalog"), 947 expression.args.get("db"), 948 expression.args.get("table"), 949 expression.args.get("this"), 950 ) 951 if part 952 ) 953 954 def column_sql(self, expression: exp.Column) -> str: 955 join_mark = " (+)" if expression.args.get("join_mark") else "" 956 957 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 958 join_mark = "" 959 self.unsupported("Outer join syntax using the (+) operator is not supported.") 960 961 return f"{self.column_parts(expression)}{join_mark}" 962 963 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 964 this = self.sql(expression, "this") 965 this = f" {this}" if this else "" 966 position = self.sql(expression, "position") 967 return f"{position}{this}" 968 969 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 970 column = self.sql(expression, "this") 971 kind = self.sql(expression, "kind") 972 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 973 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 974 kind = f"{sep}{kind}" if kind else "" 975 constraints = f" {constraints}" if constraints else "" 976 position = self.sql(expression, "position") 977 position = f" {position}" if position else "" 978 979 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 980 kind = "" 981 982 return f"{exists}{column}{kind}{constraints}{position}" 983 984 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 985 this = self.sql(expression, "this") 986 kind_sql = self.sql(expression, "kind").strip() 987 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 988 989 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 990 this = self.sql(expression, "this") 991 if expression.args.get("not_null"): 992 persisted = " PERSISTED NOT NULL" 993 elif expression.args.get("persisted"): 994 persisted = " PERSISTED" 995 else: 996 persisted = "" 997 return f"AS {this}{persisted}" 998 999 def autoincrementcolumnconstraint_sql(self, _) -> str: 1000 return self.token_sql(TokenType.AUTO_INCREMENT) 1001 1002 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1003 if isinstance(expression.this, list): 1004 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1005 else: 1006 this = self.sql(expression, "this") 1007 1008 return f"COMPRESS {this}" 1009 1010 def generatedasidentitycolumnconstraint_sql( 1011 self, expression: exp.GeneratedAsIdentityColumnConstraint 1012 ) -> str: 1013 this = "" 1014 if expression.this is not None: 1015 on_null = " ON NULL" if expression.args.get("on_null") else "" 1016 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1017 1018 start = expression.args.get("start") 1019 start = f"START WITH {start}" if start else "" 1020 increment = expression.args.get("increment") 1021 increment = f" INCREMENT BY {increment}" if increment else "" 1022 minvalue = expression.args.get("minvalue") 1023 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1024 maxvalue = expression.args.get("maxvalue") 1025 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1026 cycle = expression.args.get("cycle") 1027 cycle_sql = "" 1028 1029 if cycle is not None: 1030 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1031 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1032 1033 sequence_opts = "" 1034 if start or increment or cycle_sql: 1035 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1036 sequence_opts = f" ({sequence_opts.strip()})" 1037 1038 expr = self.sql(expression, "expression") 1039 expr = f"({expr})" if expr else "IDENTITY" 1040 1041 return f"GENERATED{this} AS {expr}{sequence_opts}" 1042 1043 def generatedasrowcolumnconstraint_sql( 1044 self, expression: exp.GeneratedAsRowColumnConstraint 1045 ) -> str: 1046 start = "START" if expression.args.get("start") else "END" 1047 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1048 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1049 1050 def periodforsystemtimeconstraint_sql( 1051 self, expression: exp.PeriodForSystemTimeConstraint 1052 ) -> str: 1053 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1054 1055 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1056 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1057 1058 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1059 return f"AS {self.sql(expression, 'this')}" 1060 1061 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1062 desc = expression.args.get("desc") 1063 if desc is not None: 1064 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1065 return "PRIMARY KEY" 1066 1067 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1068 this = self.sql(expression, "this") 1069 this = f" {this}" if this else "" 1070 index_type = expression.args.get("index_type") 1071 index_type = f" USING {index_type}" if index_type else "" 1072 on_conflict = self.sql(expression, "on_conflict") 1073 on_conflict = f" {on_conflict}" if on_conflict else "" 1074 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1075 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1076 1077 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1078 return self.sql(expression, "this") 1079 1080 def create_sql(self, expression: exp.Create) -> str: 1081 kind = self.sql(expression, "kind") 1082 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1083 properties = expression.args.get("properties") 1084 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1085 1086 this = self.createable_sql(expression, properties_locs) 1087 1088 properties_sql = "" 1089 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1090 exp.Properties.Location.POST_WITH 1091 ): 1092 properties_sql = self.sql( 1093 exp.Properties( 1094 expressions=[ 1095 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1096 *properties_locs[exp.Properties.Location.POST_WITH], 1097 ] 1098 ) 1099 ) 1100 1101 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1102 properties_sql = self.sep() + properties_sql 1103 elif not self.pretty: 1104 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1105 properties_sql = f" {properties_sql}" 1106 1107 begin = " BEGIN" if expression.args.get("begin") else "" 1108 end = " END" if expression.args.get("end") else "" 1109 1110 expression_sql = self.sql(expression, "expression") 1111 if expression_sql: 1112 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1113 1114 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1115 postalias_props_sql = "" 1116 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1117 postalias_props_sql = self.properties( 1118 exp.Properties( 1119 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1120 ), 1121 wrapped=False, 1122 ) 1123 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1124 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1125 1126 postindex_props_sql = "" 1127 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1128 postindex_props_sql = self.properties( 1129 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1130 wrapped=False, 1131 prefix=" ", 1132 ) 1133 1134 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1135 indexes = f" {indexes}" if indexes else "" 1136 index_sql = indexes + postindex_props_sql 1137 1138 replace = " OR REPLACE" if expression.args.get("replace") else "" 1139 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1140 unique = " UNIQUE" if expression.args.get("unique") else "" 1141 1142 clustered = expression.args.get("clustered") 1143 if clustered is None: 1144 clustered_sql = "" 1145 elif clustered: 1146 clustered_sql = " CLUSTERED COLUMNSTORE" 1147 else: 1148 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1149 1150 postcreate_props_sql = "" 1151 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1152 postcreate_props_sql = self.properties( 1153 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1154 sep=" ", 1155 prefix=" ", 1156 wrapped=False, 1157 ) 1158 1159 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1160 1161 postexpression_props_sql = "" 1162 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1163 postexpression_props_sql = self.properties( 1164 exp.Properties( 1165 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1166 ), 1167 sep=" ", 1168 prefix=" ", 1169 wrapped=False, 1170 ) 1171 1172 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1173 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1174 no_schema_binding = ( 1175 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1176 ) 1177 1178 clone = self.sql(expression, "clone") 1179 clone = f" {clone}" if clone else "" 1180 1181 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1182 properties_expression = f"{expression_sql}{properties_sql}" 1183 else: 1184 properties_expression = f"{properties_sql}{expression_sql}" 1185 1186 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1187 return self.prepend_ctes(expression, expression_sql) 1188 1189 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1190 start = self.sql(expression, "start") 1191 start = f"START WITH {start}" if start else "" 1192 increment = self.sql(expression, "increment") 1193 increment = f" INCREMENT BY {increment}" if increment else "" 1194 minvalue = self.sql(expression, "minvalue") 1195 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1196 maxvalue = self.sql(expression, "maxvalue") 1197 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1198 owned = self.sql(expression, "owned") 1199 owned = f" OWNED BY {owned}" if owned else "" 1200 1201 cache = expression.args.get("cache") 1202 if cache is None: 1203 cache_str = "" 1204 elif cache is True: 1205 cache_str = " CACHE" 1206 else: 1207 cache_str = f" CACHE {cache}" 1208 1209 options = self.expressions(expression, key="options", flat=True, sep=" ") 1210 options = f" {options}" if options else "" 1211 1212 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1213 1214 def clone_sql(self, expression: exp.Clone) -> str: 1215 this = self.sql(expression, "this") 1216 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1217 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1218 return f"{shallow}{keyword} {this}" 1219 1220 def describe_sql(self, expression: exp.Describe) -> str: 1221 style = expression.args.get("style") 1222 style = f" {style}" if style else "" 1223 partition = self.sql(expression, "partition") 1224 partition = f" {partition}" if partition else "" 1225 format = self.sql(expression, "format") 1226 format = f" {format}" if format else "" 1227 1228 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1229 1230 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1231 tag = self.sql(expression, "tag") 1232 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1233 1234 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1235 with_ = self.sql(expression, "with") 1236 if with_: 1237 sql = f"{with_}{self.sep()}{sql}" 1238 return sql 1239 1240 def with_sql(self, expression: exp.With) -> str: 1241 sql = self.expressions(expression, flat=True) 1242 recursive = ( 1243 "RECURSIVE " 1244 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1245 else "" 1246 ) 1247 search = self.sql(expression, "search") 1248 search = f" {search}" if search else "" 1249 1250 return f"WITH {recursive}{sql}{search}" 1251 1252 def cte_sql(self, expression: exp.CTE) -> str: 1253 alias = expression.args.get("alias") 1254 if alias: 1255 alias.add_comments(expression.pop_comments()) 1256 1257 alias_sql = self.sql(expression, "alias") 1258 1259 materialized = expression.args.get("materialized") 1260 if materialized is False: 1261 materialized = "NOT MATERIALIZED " 1262 elif materialized: 1263 materialized = "MATERIALIZED " 1264 1265 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1266 1267 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1268 alias = self.sql(expression, "this") 1269 columns = self.expressions(expression, key="columns", flat=True) 1270 columns = f"({columns})" if columns else "" 1271 1272 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1273 columns = "" 1274 self.unsupported("Named columns are not supported in table alias.") 1275 1276 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1277 alias = self._next_name() 1278 1279 return f"{alias}{columns}" 1280 1281 def bitstring_sql(self, expression: exp.BitString) -> str: 1282 this = self.sql(expression, "this") 1283 if self.dialect.BIT_START: 1284 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1285 return f"{int(this, 2)}" 1286 1287 def hexstring_sql( 1288 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1289 ) -> str: 1290 this = self.sql(expression, "this") 1291 is_integer_type = expression.args.get("is_integer") 1292 1293 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1294 not self.dialect.HEX_START and not binary_function_repr 1295 ): 1296 # Integer representation will be returned if: 1297 # - The read dialect treats the hex value as integer literal but not the write 1298 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1299 return f"{int(this, 16)}" 1300 1301 if not is_integer_type: 1302 # Read dialect treats the hex value as BINARY/BLOB 1303 if binary_function_repr: 1304 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1305 return self.func(binary_function_repr, exp.Literal.string(this)) 1306 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1307 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1308 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1309 1310 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1311 1312 def bytestring_sql(self, expression: exp.ByteString) -> str: 1313 this = self.sql(expression, "this") 1314 if self.dialect.BYTE_START: 1315 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1316 return this 1317 1318 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1319 this = self.sql(expression, "this") 1320 escape = expression.args.get("escape") 1321 1322 if self.dialect.UNICODE_START: 1323 escape_substitute = r"\\\1" 1324 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1325 else: 1326 escape_substitute = r"\\u\1" 1327 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1328 1329 if escape: 1330 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1331 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1332 else: 1333 escape_pattern = ESCAPED_UNICODE_RE 1334 escape_sql = "" 1335 1336 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1337 this = escape_pattern.sub(escape_substitute, this) 1338 1339 return f"{left_quote}{this}{right_quote}{escape_sql}" 1340 1341 def rawstring_sql(self, expression: exp.RawString) -> str: 1342 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1343 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1344 1345 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1346 this = self.sql(expression, "this") 1347 specifier = self.sql(expression, "expression") 1348 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1349 return f"{this}{specifier}" 1350 1351 def datatype_sql(self, expression: exp.DataType) -> str: 1352 nested = "" 1353 values = "" 1354 interior = self.expressions(expression, flat=True) 1355 1356 type_value = expression.this 1357 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1358 type_sql = self.sql(expression, "kind") 1359 else: 1360 type_sql = ( 1361 self.TYPE_MAPPING.get(type_value, type_value.value) 1362 if isinstance(type_value, exp.DataType.Type) 1363 else type_value 1364 ) 1365 1366 if interior: 1367 if expression.args.get("nested"): 1368 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1369 if expression.args.get("values") is not None: 1370 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1371 values = self.expressions(expression, key="values", flat=True) 1372 values = f"{delimiters[0]}{values}{delimiters[1]}" 1373 elif type_value == exp.DataType.Type.INTERVAL: 1374 nested = f" {interior}" 1375 else: 1376 nested = f"({interior})" 1377 1378 type_sql = f"{type_sql}{nested}{values}" 1379 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1380 exp.DataType.Type.TIMETZ, 1381 exp.DataType.Type.TIMESTAMPTZ, 1382 ): 1383 type_sql = f"{type_sql} WITH TIME ZONE" 1384 1385 return type_sql 1386 1387 def directory_sql(self, expression: exp.Directory) -> str: 1388 local = "LOCAL " if expression.args.get("local") else "" 1389 row_format = self.sql(expression, "row_format") 1390 row_format = f" {row_format}" if row_format else "" 1391 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1392 1393 def delete_sql(self, expression: exp.Delete) -> str: 1394 this = self.sql(expression, "this") 1395 this = f" FROM {this}" if this else "" 1396 using = self.sql(expression, "using") 1397 using = f" USING {using}" if using else "" 1398 cluster = self.sql(expression, "cluster") 1399 cluster = f" {cluster}" if cluster else "" 1400 where = self.sql(expression, "where") 1401 returning = self.sql(expression, "returning") 1402 limit = self.sql(expression, "limit") 1403 tables = self.expressions(expression, key="tables") 1404 tables = f" {tables}" if tables else "" 1405 if self.RETURNING_END: 1406 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1407 else: 1408 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1409 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1410 1411 def drop_sql(self, expression: exp.Drop) -> str: 1412 this = self.sql(expression, "this") 1413 expressions = self.expressions(expression, flat=True) 1414 expressions = f" ({expressions})" if expressions else "" 1415 kind = expression.args["kind"] 1416 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1417 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1418 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1419 on_cluster = self.sql(expression, "cluster") 1420 on_cluster = f" {on_cluster}" if on_cluster else "" 1421 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1422 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1423 cascade = " CASCADE" if expression.args.get("cascade") else "" 1424 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1425 purge = " PURGE" if expression.args.get("purge") else "" 1426 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1427 1428 def set_operation(self, expression: exp.SetOperation) -> str: 1429 op_type = type(expression) 1430 op_name = op_type.key.upper() 1431 1432 distinct = expression.args.get("distinct") 1433 if ( 1434 distinct is False 1435 and op_type in (exp.Except, exp.Intersect) 1436 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1437 ): 1438 self.unsupported(f"{op_name} ALL is not supported") 1439 1440 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1441 1442 if distinct is None: 1443 distinct = default_distinct 1444 if distinct is None: 1445 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1446 1447 if distinct is default_distinct: 1448 kind = "" 1449 else: 1450 kind = " DISTINCT" if distinct else " ALL" 1451 1452 by_name = " BY NAME" if expression.args.get("by_name") else "" 1453 return f"{op_name}{kind}{by_name}" 1454 1455 def set_operations(self, expression: exp.SetOperation) -> str: 1456 if not self.SET_OP_MODIFIERS: 1457 limit = expression.args.get("limit") 1458 order = expression.args.get("order") 1459 1460 if limit or order: 1461 select = self._move_ctes_to_top_level( 1462 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1463 ) 1464 1465 if limit: 1466 select = select.limit(limit.pop(), copy=False) 1467 if order: 1468 select = select.order_by(order.pop(), copy=False) 1469 return self.sql(select) 1470 1471 sqls: t.List[str] = [] 1472 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1473 1474 while stack: 1475 node = stack.pop() 1476 1477 if isinstance(node, exp.SetOperation): 1478 stack.append(node.expression) 1479 stack.append( 1480 self.maybe_comment( 1481 self.set_operation(node), comments=node.comments, separated=True 1482 ) 1483 ) 1484 stack.append(node.this) 1485 else: 1486 sqls.append(self.sql(node)) 1487 1488 this = self.sep().join(sqls) 1489 this = self.query_modifiers(expression, this) 1490 return self.prepend_ctes(expression, this) 1491 1492 def fetch_sql(self, expression: exp.Fetch) -> str: 1493 direction = expression.args.get("direction") 1494 direction = f" {direction}" if direction else "" 1495 count = self.sql(expression, "count") 1496 count = f" {count}" if count else "" 1497 limit_options = self.sql(expression, "limit_options") 1498 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1499 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1500 1501 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1502 percent = " PERCENT" if expression.args.get("percent") else "" 1503 rows = " ROWS" if expression.args.get("rows") else "" 1504 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1505 if not with_ties and rows: 1506 with_ties = " ONLY" 1507 return f"{percent}{rows}{with_ties}" 1508 1509 def filter_sql(self, expression: exp.Filter) -> str: 1510 if self.AGGREGATE_FILTER_SUPPORTED: 1511 this = self.sql(expression, "this") 1512 where = self.sql(expression, "expression").strip() 1513 return f"{this} FILTER({where})" 1514 1515 agg = expression.this 1516 agg_arg = agg.this 1517 cond = expression.expression.this 1518 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1519 return self.sql(agg) 1520 1521 def hint_sql(self, expression: exp.Hint) -> str: 1522 if not self.QUERY_HINTS: 1523 self.unsupported("Hints are not supported") 1524 return "" 1525 1526 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1527 1528 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1529 using = self.sql(expression, "using") 1530 using = f" USING {using}" if using else "" 1531 columns = self.expressions(expression, key="columns", flat=True) 1532 columns = f"({columns})" if columns else "" 1533 partition_by = self.expressions(expression, key="partition_by", flat=True) 1534 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1535 where = self.sql(expression, "where") 1536 include = self.expressions(expression, key="include", flat=True) 1537 if include: 1538 include = f" INCLUDE ({include})" 1539 with_storage = self.expressions(expression, key="with_storage", flat=True) 1540 with_storage = f" WITH ({with_storage})" if with_storage else "" 1541 tablespace = self.sql(expression, "tablespace") 1542 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1543 on = self.sql(expression, "on") 1544 on = f" ON {on}" if on else "" 1545 1546 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1547 1548 def index_sql(self, expression: exp.Index) -> str: 1549 unique = "UNIQUE " if expression.args.get("unique") else "" 1550 primary = "PRIMARY " if expression.args.get("primary") else "" 1551 amp = "AMP " if expression.args.get("amp") else "" 1552 name = self.sql(expression, "this") 1553 name = f"{name} " if name else "" 1554 table = self.sql(expression, "table") 1555 table = f"{self.INDEX_ON} {table}" if table else "" 1556 1557 index = "INDEX " if not table else "" 1558 1559 params = self.sql(expression, "params") 1560 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1561 1562 def identifier_sql(self, expression: exp.Identifier) -> str: 1563 text = expression.name 1564 lower = text.lower() 1565 text = lower if self.normalize and not expression.quoted else text 1566 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1567 if ( 1568 expression.quoted 1569 or self.dialect.can_identify(text, self.identify) 1570 or lower in self.RESERVED_KEYWORDS 1571 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1572 ): 1573 text = f"{self._identifier_start}{text}{self._identifier_end}" 1574 return text 1575 1576 def hex_sql(self, expression: exp.Hex) -> str: 1577 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1578 if self.dialect.HEX_LOWERCASE: 1579 text = self.func("LOWER", text) 1580 1581 return text 1582 1583 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1584 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1585 if not self.dialect.HEX_LOWERCASE: 1586 text = self.func("LOWER", text) 1587 return text 1588 1589 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1590 input_format = self.sql(expression, "input_format") 1591 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1592 output_format = self.sql(expression, "output_format") 1593 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1594 return self.sep().join((input_format, output_format)) 1595 1596 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1597 string = self.sql(exp.Literal.string(expression.name)) 1598 return f"{prefix}{string}" 1599 1600 def partition_sql(self, expression: exp.Partition) -> str: 1601 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1602 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1603 1604 def properties_sql(self, expression: exp.Properties) -> str: 1605 root_properties = [] 1606 with_properties = [] 1607 1608 for p in expression.expressions: 1609 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1610 if p_loc == exp.Properties.Location.POST_WITH: 1611 with_properties.append(p) 1612 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1613 root_properties.append(p) 1614 1615 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1616 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1617 1618 if root_props and with_props and not self.pretty: 1619 with_props = " " + with_props 1620 1621 return root_props + with_props 1622 1623 def root_properties(self, properties: exp.Properties) -> str: 1624 if properties.expressions: 1625 return self.expressions(properties, indent=False, sep=" ") 1626 return "" 1627 1628 def properties( 1629 self, 1630 properties: exp.Properties, 1631 prefix: str = "", 1632 sep: str = ", ", 1633 suffix: str = "", 1634 wrapped: bool = True, 1635 ) -> str: 1636 if properties.expressions: 1637 expressions = self.expressions(properties, sep=sep, indent=False) 1638 if expressions: 1639 expressions = self.wrap(expressions) if wrapped else expressions 1640 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1641 return "" 1642 1643 def with_properties(self, properties: exp.Properties) -> str: 1644 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1645 1646 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1647 properties_locs = defaultdict(list) 1648 for p in properties.expressions: 1649 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1650 if p_loc != exp.Properties.Location.UNSUPPORTED: 1651 properties_locs[p_loc].append(p) 1652 else: 1653 self.unsupported(f"Unsupported property {p.key}") 1654 1655 return properties_locs 1656 1657 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1658 if isinstance(expression.this, exp.Dot): 1659 return self.sql(expression, "this") 1660 return f"'{expression.name}'" if string_key else expression.name 1661 1662 def property_sql(self, expression: exp.Property) -> str: 1663 property_cls = expression.__class__ 1664 if property_cls == exp.Property: 1665 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1666 1667 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1668 if not property_name: 1669 self.unsupported(f"Unsupported property {expression.key}") 1670 1671 return f"{property_name}={self.sql(expression, 'this')}" 1672 1673 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1674 if self.SUPPORTS_CREATE_TABLE_LIKE: 1675 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1676 options = f" {options}" if options else "" 1677 1678 like = f"LIKE {self.sql(expression, 'this')}{options}" 1679 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1680 like = f"({like})" 1681 1682 return like 1683 1684 if expression.expressions: 1685 self.unsupported("Transpilation of LIKE property options is unsupported") 1686 1687 select = exp.select("*").from_(expression.this).limit(0) 1688 return f"AS {self.sql(select)}" 1689 1690 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1691 no = "NO " if expression.args.get("no") else "" 1692 protection = " PROTECTION" if expression.args.get("protection") else "" 1693 return f"{no}FALLBACK{protection}" 1694 1695 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1696 no = "NO " if expression.args.get("no") else "" 1697 local = expression.args.get("local") 1698 local = f"{local} " if local else "" 1699 dual = "DUAL " if expression.args.get("dual") else "" 1700 before = "BEFORE " if expression.args.get("before") else "" 1701 after = "AFTER " if expression.args.get("after") else "" 1702 return f"{no}{local}{dual}{before}{after}JOURNAL" 1703 1704 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1705 freespace = self.sql(expression, "this") 1706 percent = " PERCENT" if expression.args.get("percent") else "" 1707 return f"FREESPACE={freespace}{percent}" 1708 1709 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1710 if expression.args.get("default"): 1711 property = "DEFAULT" 1712 elif expression.args.get("on"): 1713 property = "ON" 1714 else: 1715 property = "OFF" 1716 return f"CHECKSUM={property}" 1717 1718 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1719 if expression.args.get("no"): 1720 return "NO MERGEBLOCKRATIO" 1721 if expression.args.get("default"): 1722 return "DEFAULT MERGEBLOCKRATIO" 1723 1724 percent = " PERCENT" if expression.args.get("percent") else "" 1725 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1726 1727 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1728 default = expression.args.get("default") 1729 minimum = expression.args.get("minimum") 1730 maximum = expression.args.get("maximum") 1731 if default or minimum or maximum: 1732 if default: 1733 prop = "DEFAULT" 1734 elif minimum: 1735 prop = "MINIMUM" 1736 else: 1737 prop = "MAXIMUM" 1738 return f"{prop} DATABLOCKSIZE" 1739 units = expression.args.get("units") 1740 units = f" {units}" if units else "" 1741 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1742 1743 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1744 autotemp = expression.args.get("autotemp") 1745 always = expression.args.get("always") 1746 default = expression.args.get("default") 1747 manual = expression.args.get("manual") 1748 never = expression.args.get("never") 1749 1750 if autotemp is not None: 1751 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1752 elif always: 1753 prop = "ALWAYS" 1754 elif default: 1755 prop = "DEFAULT" 1756 elif manual: 1757 prop = "MANUAL" 1758 elif never: 1759 prop = "NEVER" 1760 return f"BLOCKCOMPRESSION={prop}" 1761 1762 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1763 no = expression.args.get("no") 1764 no = " NO" if no else "" 1765 concurrent = expression.args.get("concurrent") 1766 concurrent = " CONCURRENT" if concurrent else "" 1767 target = self.sql(expression, "target") 1768 target = f" {target}" if target else "" 1769 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1770 1771 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1772 if isinstance(expression.this, list): 1773 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1774 if expression.this: 1775 modulus = self.sql(expression, "this") 1776 remainder = self.sql(expression, "expression") 1777 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1778 1779 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1780 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1781 return f"FROM ({from_expressions}) TO ({to_expressions})" 1782 1783 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1784 this = self.sql(expression, "this") 1785 1786 for_values_or_default = expression.expression 1787 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1788 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1789 else: 1790 for_values_or_default = " DEFAULT" 1791 1792 return f"PARTITION OF {this}{for_values_or_default}" 1793 1794 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1795 kind = expression.args.get("kind") 1796 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1797 for_or_in = expression.args.get("for_or_in") 1798 for_or_in = f" {for_or_in}" if for_or_in else "" 1799 lock_type = expression.args.get("lock_type") 1800 override = " OVERRIDE" if expression.args.get("override") else "" 1801 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1802 1803 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1804 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1805 statistics = expression.args.get("statistics") 1806 statistics_sql = "" 1807 if statistics is not None: 1808 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1809 return f"{data_sql}{statistics_sql}" 1810 1811 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1812 this = self.sql(expression, "this") 1813 this = f"HISTORY_TABLE={this}" if this else "" 1814 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1815 data_consistency = ( 1816 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1817 ) 1818 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1819 retention_period = ( 1820 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1821 ) 1822 1823 if this: 1824 on_sql = self.func("ON", this, data_consistency, retention_period) 1825 else: 1826 on_sql = "ON" if expression.args.get("on") else "OFF" 1827 1828 sql = f"SYSTEM_VERSIONING={on_sql}" 1829 1830 return f"WITH({sql})" if expression.args.get("with") else sql 1831 1832 def insert_sql(self, expression: exp.Insert) -> str: 1833 hint = self.sql(expression, "hint") 1834 overwrite = expression.args.get("overwrite") 1835 1836 if isinstance(expression.this, exp.Directory): 1837 this = " OVERWRITE" if overwrite else " INTO" 1838 else: 1839 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1840 1841 stored = self.sql(expression, "stored") 1842 stored = f" {stored}" if stored else "" 1843 alternative = expression.args.get("alternative") 1844 alternative = f" OR {alternative}" if alternative else "" 1845 ignore = " IGNORE" if expression.args.get("ignore") else "" 1846 is_function = expression.args.get("is_function") 1847 if is_function: 1848 this = f"{this} FUNCTION" 1849 this = f"{this} {self.sql(expression, 'this')}" 1850 1851 exists = " IF EXISTS" if expression.args.get("exists") else "" 1852 where = self.sql(expression, "where") 1853 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1854 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1855 on_conflict = self.sql(expression, "conflict") 1856 on_conflict = f" {on_conflict}" if on_conflict else "" 1857 by_name = " BY NAME" if expression.args.get("by_name") else "" 1858 returning = self.sql(expression, "returning") 1859 1860 if self.RETURNING_END: 1861 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1862 else: 1863 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1864 1865 partition_by = self.sql(expression, "partition") 1866 partition_by = f" {partition_by}" if partition_by else "" 1867 settings = self.sql(expression, "settings") 1868 settings = f" {settings}" if settings else "" 1869 1870 source = self.sql(expression, "source") 1871 source = f"TABLE {source}" if source else "" 1872 1873 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1874 return self.prepend_ctes(expression, sql) 1875 1876 def introducer_sql(self, expression: exp.Introducer) -> str: 1877 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1878 1879 def kill_sql(self, expression: exp.Kill) -> str: 1880 kind = self.sql(expression, "kind") 1881 kind = f" {kind}" if kind else "" 1882 this = self.sql(expression, "this") 1883 this = f" {this}" if this else "" 1884 return f"KILL{kind}{this}" 1885 1886 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1887 return expression.name 1888 1889 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1890 return expression.name 1891 1892 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1893 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1894 1895 constraint = self.sql(expression, "constraint") 1896 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1897 1898 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1899 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1900 action = self.sql(expression, "action") 1901 1902 expressions = self.expressions(expression, flat=True) 1903 if expressions: 1904 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1905 expressions = f" {set_keyword}{expressions}" 1906 1907 where = self.sql(expression, "where") 1908 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1909 1910 def returning_sql(self, expression: exp.Returning) -> str: 1911 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1912 1913 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1914 fields = self.sql(expression, "fields") 1915 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1916 escaped = self.sql(expression, "escaped") 1917 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1918 items = self.sql(expression, "collection_items") 1919 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1920 keys = self.sql(expression, "map_keys") 1921 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1922 lines = self.sql(expression, "lines") 1923 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1924 null = self.sql(expression, "null") 1925 null = f" NULL DEFINED AS {null}" if null else "" 1926 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1927 1928 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1929 return f"WITH ({self.expressions(expression, flat=True)})" 1930 1931 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1932 this = f"{self.sql(expression, 'this')} INDEX" 1933 target = self.sql(expression, "target") 1934 target = f" FOR {target}" if target else "" 1935 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1936 1937 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1938 this = self.sql(expression, "this") 1939 kind = self.sql(expression, "kind") 1940 expr = self.sql(expression, "expression") 1941 return f"{this} ({kind} => {expr})" 1942 1943 def table_parts(self, expression: exp.Table) -> str: 1944 return ".".join( 1945 self.sql(part) 1946 for part in ( 1947 expression.args.get("catalog"), 1948 expression.args.get("db"), 1949 expression.args.get("this"), 1950 ) 1951 if part is not None 1952 ) 1953 1954 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1955 table = self.table_parts(expression) 1956 only = "ONLY " if expression.args.get("only") else "" 1957 partition = self.sql(expression, "partition") 1958 partition = f" {partition}" if partition else "" 1959 version = self.sql(expression, "version") 1960 version = f" {version}" if version else "" 1961 alias = self.sql(expression, "alias") 1962 alias = f"{sep}{alias}" if alias else "" 1963 1964 sample = self.sql(expression, "sample") 1965 if self.dialect.ALIAS_POST_TABLESAMPLE: 1966 sample_pre_alias = sample 1967 sample_post_alias = "" 1968 else: 1969 sample_pre_alias = "" 1970 sample_post_alias = sample 1971 1972 hints = self.expressions(expression, key="hints", sep=" ") 1973 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1974 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1975 joins = self.indent( 1976 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1977 ) 1978 laterals = self.expressions(expression, key="laterals", sep="") 1979 1980 file_format = self.sql(expression, "format") 1981 if file_format: 1982 pattern = self.sql(expression, "pattern") 1983 pattern = f", PATTERN => {pattern}" if pattern else "" 1984 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1985 1986 ordinality = expression.args.get("ordinality") or "" 1987 if ordinality: 1988 ordinality = f" WITH ORDINALITY{alias}" 1989 alias = "" 1990 1991 when = self.sql(expression, "when") 1992 if when: 1993 table = f"{table} {when}" 1994 1995 changes = self.sql(expression, "changes") 1996 changes = f" {changes}" if changes else "" 1997 1998 rows_from = self.expressions(expression, key="rows_from") 1999 if rows_from: 2000 table = f"ROWS FROM {self.wrap(rows_from)}" 2001 2002 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2003 2004 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2005 table = self.func("TABLE", expression.this) 2006 alias = self.sql(expression, "alias") 2007 alias = f" AS {alias}" if alias else "" 2008 sample = self.sql(expression, "sample") 2009 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2010 joins = self.indent( 2011 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2012 ) 2013 return f"{table}{alias}{pivots}{sample}{joins}" 2014 2015 def tablesample_sql( 2016 self, 2017 expression: exp.TableSample, 2018 tablesample_keyword: t.Optional[str] = None, 2019 ) -> str: 2020 method = self.sql(expression, "method") 2021 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2022 numerator = self.sql(expression, "bucket_numerator") 2023 denominator = self.sql(expression, "bucket_denominator") 2024 field = self.sql(expression, "bucket_field") 2025 field = f" ON {field}" if field else "" 2026 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2027 seed = self.sql(expression, "seed") 2028 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2029 2030 size = self.sql(expression, "size") 2031 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2032 size = f"{size} ROWS" 2033 2034 percent = self.sql(expression, "percent") 2035 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2036 percent = f"{percent} PERCENT" 2037 2038 expr = f"{bucket}{percent}{size}" 2039 if self.TABLESAMPLE_REQUIRES_PARENS: 2040 expr = f"({expr})" 2041 2042 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2043 2044 def pivot_sql(self, expression: exp.Pivot) -> str: 2045 expressions = self.expressions(expression, flat=True) 2046 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2047 2048 if expression.this: 2049 this = self.sql(expression, "this") 2050 if not expressions: 2051 return f"UNPIVOT {this}" 2052 2053 on = f"{self.seg('ON')} {expressions}" 2054 into = self.sql(expression, "into") 2055 into = f"{self.seg('INTO')} {into}" if into else "" 2056 using = self.expressions(expression, key="using", flat=True) 2057 using = f"{self.seg('USING')} {using}" if using else "" 2058 group = self.sql(expression, "group") 2059 return f"{direction} {this}{on}{into}{using}{group}" 2060 2061 alias = self.sql(expression, "alias") 2062 alias = f" AS {alias}" if alias else "" 2063 2064 field = self.sql(expression, "field") 2065 2066 include_nulls = expression.args.get("include_nulls") 2067 if include_nulls is not None: 2068 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2069 else: 2070 nulls = "" 2071 2072 default_on_null = self.sql(expression, "default_on_null") 2073 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2074 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2075 2076 def version_sql(self, expression: exp.Version) -> str: 2077 this = f"FOR {expression.name}" 2078 kind = expression.text("kind") 2079 expr = self.sql(expression, "expression") 2080 return f"{this} {kind} {expr}" 2081 2082 def tuple_sql(self, expression: exp.Tuple) -> str: 2083 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2084 2085 def update_sql(self, expression: exp.Update) -> str: 2086 this = self.sql(expression, "this") 2087 set_sql = self.expressions(expression, flat=True) 2088 from_sql = self.sql(expression, "from") 2089 where_sql = self.sql(expression, "where") 2090 returning = self.sql(expression, "returning") 2091 order = self.sql(expression, "order") 2092 limit = self.sql(expression, "limit") 2093 if self.RETURNING_END: 2094 expression_sql = f"{from_sql}{where_sql}{returning}" 2095 else: 2096 expression_sql = f"{returning}{from_sql}{where_sql}" 2097 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2098 return self.prepend_ctes(expression, sql) 2099 2100 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2101 values_as_table = values_as_table and self.VALUES_AS_TABLE 2102 2103 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2104 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2105 args = self.expressions(expression) 2106 alias = self.sql(expression, "alias") 2107 values = f"VALUES{self.seg('')}{args}" 2108 values = ( 2109 f"({values})" 2110 if self.WRAP_DERIVED_VALUES 2111 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2112 else values 2113 ) 2114 return f"{values} AS {alias}" if alias else values 2115 2116 # Converts `VALUES...` expression into a series of select unions. 2117 alias_node = expression.args.get("alias") 2118 column_names = alias_node and alias_node.columns 2119 2120 selects: t.List[exp.Query] = [] 2121 2122 for i, tup in enumerate(expression.expressions): 2123 row = tup.expressions 2124 2125 if i == 0 and column_names: 2126 row = [ 2127 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2128 ] 2129 2130 selects.append(exp.Select(expressions=row)) 2131 2132 if self.pretty: 2133 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2134 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2135 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2136 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2137 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2138 2139 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2140 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2141 return f"({unions}){alias}" 2142 2143 def var_sql(self, expression: exp.Var) -> str: 2144 return self.sql(expression, "this") 2145 2146 @unsupported_args("expressions") 2147 def into_sql(self, expression: exp.Into) -> str: 2148 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2149 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2150 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2151 2152 def from_sql(self, expression: exp.From) -> str: 2153 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2154 2155 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2156 grouping_sets = self.expressions(expression, indent=False) 2157 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2158 2159 def rollup_sql(self, expression: exp.Rollup) -> str: 2160 expressions = self.expressions(expression, indent=False) 2161 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2162 2163 def cube_sql(self, expression: exp.Cube) -> str: 2164 expressions = self.expressions(expression, indent=False) 2165 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2166 2167 def group_sql(self, expression: exp.Group) -> str: 2168 group_by_all = expression.args.get("all") 2169 if group_by_all is True: 2170 modifier = " ALL" 2171 elif group_by_all is False: 2172 modifier = " DISTINCT" 2173 else: 2174 modifier = "" 2175 2176 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2177 2178 grouping_sets = self.expressions(expression, key="grouping_sets") 2179 cube = self.expressions(expression, key="cube") 2180 rollup = self.expressions(expression, key="rollup") 2181 2182 groupings = csv( 2183 self.seg(grouping_sets) if grouping_sets else "", 2184 self.seg(cube) if cube else "", 2185 self.seg(rollup) if rollup else "", 2186 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2187 sep=self.GROUPINGS_SEP, 2188 ) 2189 2190 if ( 2191 expression.expressions 2192 and groupings 2193 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2194 ): 2195 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2196 2197 return f"{group_by}{groupings}" 2198 2199 def having_sql(self, expression: exp.Having) -> str: 2200 this = self.indent(self.sql(expression, "this")) 2201 return f"{self.seg('HAVING')}{self.sep()}{this}" 2202 2203 def connect_sql(self, expression: exp.Connect) -> str: 2204 start = self.sql(expression, "start") 2205 start = self.seg(f"START WITH {start}") if start else "" 2206 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2207 connect = self.sql(expression, "connect") 2208 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2209 return start + connect 2210 2211 def prior_sql(self, expression: exp.Prior) -> str: 2212 return f"PRIOR {self.sql(expression, 'this')}" 2213 2214 def join_sql(self, expression: exp.Join) -> str: 2215 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2216 side = None 2217 else: 2218 side = expression.side 2219 2220 op_sql = " ".join( 2221 op 2222 for op in ( 2223 expression.method, 2224 "GLOBAL" if expression.args.get("global") else None, 2225 side, 2226 expression.kind, 2227 expression.hint if self.JOIN_HINTS else None, 2228 ) 2229 if op 2230 ) 2231 match_cond = self.sql(expression, "match_condition") 2232 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2233 on_sql = self.sql(expression, "on") 2234 using = expression.args.get("using") 2235 2236 if not on_sql and using: 2237 on_sql = csv(*(self.sql(column) for column in using)) 2238 2239 this = expression.this 2240 this_sql = self.sql(this) 2241 2242 exprs = self.expressions(expression) 2243 if exprs: 2244 this_sql = f"{this_sql},{self.seg(exprs)}" 2245 2246 if on_sql: 2247 on_sql = self.indent(on_sql, skip_first=True) 2248 space = self.seg(" " * self.pad) if self.pretty else " " 2249 if using: 2250 on_sql = f"{space}USING ({on_sql})" 2251 else: 2252 on_sql = f"{space}ON {on_sql}" 2253 elif not op_sql: 2254 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2255 return f" {this_sql}" 2256 2257 return f", {this_sql}" 2258 2259 if op_sql != "STRAIGHT_JOIN": 2260 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2261 2262 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2263 2264 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2265 args = self.expressions(expression, flat=True) 2266 args = f"({args})" if len(args.split(",")) > 1 else args 2267 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2268 2269 def lateral_op(self, expression: exp.Lateral) -> str: 2270 cross_apply = expression.args.get("cross_apply") 2271 2272 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2273 if cross_apply is True: 2274 op = "INNER JOIN " 2275 elif cross_apply is False: 2276 op = "LEFT JOIN " 2277 else: 2278 op = "" 2279 2280 return f"{op}LATERAL" 2281 2282 def lateral_sql(self, expression: exp.Lateral) -> str: 2283 this = self.sql(expression, "this") 2284 2285 if expression.args.get("view"): 2286 alias = expression.args["alias"] 2287 columns = self.expressions(alias, key="columns", flat=True) 2288 table = f" {alias.name}" if alias.name else "" 2289 columns = f" AS {columns}" if columns else "" 2290 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2291 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2292 2293 alias = self.sql(expression, "alias") 2294 alias = f" AS {alias}" if alias else "" 2295 return f"{self.lateral_op(expression)} {this}{alias}" 2296 2297 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2298 this = self.sql(expression, "this") 2299 2300 args = [ 2301 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2302 for e in (expression.args.get(k) for k in ("offset", "expression")) 2303 if e 2304 ] 2305 2306 args_sql = ", ".join(self.sql(e) for e in args) 2307 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2308 expressions = self.expressions(expression, flat=True) 2309 limit_options = self.sql(expression, "limit_options") 2310 expressions = f" BY {expressions}" if expressions else "" 2311 2312 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2313 2314 def offset_sql(self, expression: exp.Offset) -> str: 2315 this = self.sql(expression, "this") 2316 value = expression.expression 2317 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2318 expressions = self.expressions(expression, flat=True) 2319 expressions = f" BY {expressions}" if expressions else "" 2320 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2321 2322 def setitem_sql(self, expression: exp.SetItem) -> str: 2323 kind = self.sql(expression, "kind") 2324 kind = f"{kind} " if kind else "" 2325 this = self.sql(expression, "this") 2326 expressions = self.expressions(expression) 2327 collate = self.sql(expression, "collate") 2328 collate = f" COLLATE {collate}" if collate else "" 2329 global_ = "GLOBAL " if expression.args.get("global") else "" 2330 return f"{global_}{kind}{this}{expressions}{collate}" 2331 2332 def set_sql(self, expression: exp.Set) -> str: 2333 expressions = f" {self.expressions(expression, flat=True)}" 2334 tag = " TAG" if expression.args.get("tag") else "" 2335 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2336 2337 def pragma_sql(self, expression: exp.Pragma) -> str: 2338 return f"PRAGMA {self.sql(expression, 'this')}" 2339 2340 def lock_sql(self, expression: exp.Lock) -> str: 2341 if not self.LOCKING_READS_SUPPORTED: 2342 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2343 return "" 2344 2345 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2346 expressions = self.expressions(expression, flat=True) 2347 expressions = f" OF {expressions}" if expressions else "" 2348 wait = expression.args.get("wait") 2349 2350 if wait is not None: 2351 if isinstance(wait, exp.Literal): 2352 wait = f" WAIT {self.sql(wait)}" 2353 else: 2354 wait = " NOWAIT" if wait else " SKIP LOCKED" 2355 2356 return f"{lock_type}{expressions}{wait or ''}" 2357 2358 def literal_sql(self, expression: exp.Literal) -> str: 2359 text = expression.this or "" 2360 if expression.is_string: 2361 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2362 return text 2363 2364 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2365 if self.dialect.ESCAPED_SEQUENCES: 2366 to_escaped = self.dialect.ESCAPED_SEQUENCES 2367 text = "".join( 2368 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2369 ) 2370 2371 return self._replace_line_breaks(text).replace( 2372 self.dialect.QUOTE_END, self._escaped_quote_end 2373 ) 2374 2375 def loaddata_sql(self, expression: exp.LoadData) -> str: 2376 local = " LOCAL" if expression.args.get("local") else "" 2377 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2378 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2379 this = f" INTO TABLE {self.sql(expression, 'this')}" 2380 partition = self.sql(expression, "partition") 2381 partition = f" {partition}" if partition else "" 2382 input_format = self.sql(expression, "input_format") 2383 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2384 serde = self.sql(expression, "serde") 2385 serde = f" SERDE {serde}" if serde else "" 2386 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2387 2388 def null_sql(self, *_) -> str: 2389 return "NULL" 2390 2391 def boolean_sql(self, expression: exp.Boolean) -> str: 2392 return "TRUE" if expression.this else "FALSE" 2393 2394 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2395 this = self.sql(expression, "this") 2396 this = f"{this} " if this else this 2397 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2398 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2399 2400 def withfill_sql(self, expression: exp.WithFill) -> str: 2401 from_sql = self.sql(expression, "from") 2402 from_sql = f" FROM {from_sql}" if from_sql else "" 2403 to_sql = self.sql(expression, "to") 2404 to_sql = f" TO {to_sql}" if to_sql else "" 2405 step_sql = self.sql(expression, "step") 2406 step_sql = f" STEP {step_sql}" if step_sql else "" 2407 interpolated_values = [ 2408 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2409 if isinstance(e, exp.Alias) 2410 else self.sql(e, "this") 2411 for e in expression.args.get("interpolate") or [] 2412 ] 2413 interpolate = ( 2414 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2415 ) 2416 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2417 2418 def cluster_sql(self, expression: exp.Cluster) -> str: 2419 return self.op_expressions("CLUSTER BY", expression) 2420 2421 def distribute_sql(self, expression: exp.Distribute) -> str: 2422 return self.op_expressions("DISTRIBUTE BY", expression) 2423 2424 def sort_sql(self, expression: exp.Sort) -> str: 2425 return self.op_expressions("SORT BY", expression) 2426 2427 def ordered_sql(self, expression: exp.Ordered) -> str: 2428 desc = expression.args.get("desc") 2429 asc = not desc 2430 2431 nulls_first = expression.args.get("nulls_first") 2432 nulls_last = not nulls_first 2433 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2434 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2435 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2436 2437 this = self.sql(expression, "this") 2438 2439 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2440 nulls_sort_change = "" 2441 if nulls_first and ( 2442 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2443 ): 2444 nulls_sort_change = " NULLS FIRST" 2445 elif ( 2446 nulls_last 2447 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2448 and not nulls_are_last 2449 ): 2450 nulls_sort_change = " NULLS LAST" 2451 2452 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2453 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2454 window = expression.find_ancestor(exp.Window, exp.Select) 2455 if isinstance(window, exp.Window) and window.args.get("spec"): 2456 self.unsupported( 2457 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2458 ) 2459 nulls_sort_change = "" 2460 elif self.NULL_ORDERING_SUPPORTED is False and ( 2461 (asc and nulls_sort_change == " NULLS LAST") 2462 or (desc and nulls_sort_change == " NULLS FIRST") 2463 ): 2464 # BigQuery does not allow these ordering/nulls combinations when used under 2465 # an aggregation func or under a window containing one 2466 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2467 2468 if isinstance(ancestor, exp.Window): 2469 ancestor = ancestor.this 2470 if isinstance(ancestor, exp.AggFunc): 2471 self.unsupported( 2472 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2473 ) 2474 nulls_sort_change = "" 2475 elif self.NULL_ORDERING_SUPPORTED is None: 2476 if expression.this.is_int: 2477 self.unsupported( 2478 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2479 ) 2480 elif not isinstance(expression.this, exp.Rand): 2481 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2482 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2483 nulls_sort_change = "" 2484 2485 with_fill = self.sql(expression, "with_fill") 2486 with_fill = f" {with_fill}" if with_fill else "" 2487 2488 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2489 2490 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2491 window_frame = self.sql(expression, "window_frame") 2492 window_frame = f"{window_frame} " if window_frame else "" 2493 2494 this = self.sql(expression, "this") 2495 2496 return f"{window_frame}{this}" 2497 2498 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2499 partition = self.partition_by_sql(expression) 2500 order = self.sql(expression, "order") 2501 measures = self.expressions(expression, key="measures") 2502 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2503 rows = self.sql(expression, "rows") 2504 rows = self.seg(rows) if rows else "" 2505 after = self.sql(expression, "after") 2506 after = self.seg(after) if after else "" 2507 pattern = self.sql(expression, "pattern") 2508 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2509 definition_sqls = [ 2510 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2511 for definition in expression.args.get("define", []) 2512 ] 2513 definitions = self.expressions(sqls=definition_sqls) 2514 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2515 body = "".join( 2516 ( 2517 partition, 2518 order, 2519 measures, 2520 rows, 2521 after, 2522 pattern, 2523 define, 2524 ) 2525 ) 2526 alias = self.sql(expression, "alias") 2527 alias = f" {alias}" if alias else "" 2528 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2529 2530 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2531 limit = expression.args.get("limit") 2532 2533 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2534 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2535 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2536 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2537 2538 return csv( 2539 *sqls, 2540 *[self.sql(join) for join in expression.args.get("joins") or []], 2541 self.sql(expression, "match"), 2542 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2543 self.sql(expression, "prewhere"), 2544 self.sql(expression, "where"), 2545 self.sql(expression, "connect"), 2546 self.sql(expression, "group"), 2547 self.sql(expression, "having"), 2548 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2549 self.sql(expression, "order"), 2550 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2551 *self.after_limit_modifiers(expression), 2552 self.options_modifier(expression), 2553 sep="", 2554 ) 2555 2556 def options_modifier(self, expression: exp.Expression) -> str: 2557 options = self.expressions(expression, key="options") 2558 return f" {options}" if options else "" 2559 2560 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2561 return "" 2562 2563 def offset_limit_modifiers( 2564 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2565 ) -> t.List[str]: 2566 return [ 2567 self.sql(expression, "offset") if fetch else self.sql(limit), 2568 self.sql(limit) if fetch else self.sql(expression, "offset"), 2569 ] 2570 2571 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2572 locks = self.expressions(expression, key="locks", sep=" ") 2573 locks = f" {locks}" if locks else "" 2574 return [locks, self.sql(expression, "sample")] 2575 2576 def select_sql(self, expression: exp.Select) -> str: 2577 into = expression.args.get("into") 2578 if not self.SUPPORTS_SELECT_INTO and into: 2579 into.pop() 2580 2581 hint = self.sql(expression, "hint") 2582 distinct = self.sql(expression, "distinct") 2583 distinct = f" {distinct}" if distinct else "" 2584 kind = self.sql(expression, "kind") 2585 2586 limit = expression.args.get("limit") 2587 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2588 top = self.limit_sql(limit, top=True) 2589 limit.pop() 2590 else: 2591 top = "" 2592 2593 expressions = self.expressions(expression) 2594 2595 if kind: 2596 if kind in self.SELECT_KINDS: 2597 kind = f" AS {kind}" 2598 else: 2599 if kind == "STRUCT": 2600 expressions = self.expressions( 2601 sqls=[ 2602 self.sql( 2603 exp.Struct( 2604 expressions=[ 2605 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2606 if isinstance(e, exp.Alias) 2607 else e 2608 for e in expression.expressions 2609 ] 2610 ) 2611 ) 2612 ] 2613 ) 2614 kind = "" 2615 2616 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2617 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2618 2619 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2620 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2621 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2622 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2623 sql = self.query_modifiers( 2624 expression, 2625 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2626 self.sql(expression, "into", comment=False), 2627 self.sql(expression, "from", comment=False), 2628 ) 2629 2630 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2631 if expression.args.get("with"): 2632 sql = self.maybe_comment(sql, expression) 2633 expression.pop_comments() 2634 2635 sql = self.prepend_ctes(expression, sql) 2636 2637 if not self.SUPPORTS_SELECT_INTO and into: 2638 if into.args.get("temporary"): 2639 table_kind = " TEMPORARY" 2640 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2641 table_kind = " UNLOGGED" 2642 else: 2643 table_kind = "" 2644 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2645 2646 return sql 2647 2648 def schema_sql(self, expression: exp.Schema) -> str: 2649 this = self.sql(expression, "this") 2650 sql = self.schema_columns_sql(expression) 2651 return f"{this} {sql}" if this and sql else this or sql 2652 2653 def schema_columns_sql(self, expression: exp.Schema) -> str: 2654 if expression.expressions: 2655 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2656 return "" 2657 2658 def star_sql(self, expression: exp.Star) -> str: 2659 except_ = self.expressions(expression, key="except", flat=True) 2660 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2661 replace = self.expressions(expression, key="replace", flat=True) 2662 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2663 rename = self.expressions(expression, key="rename", flat=True) 2664 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2665 return f"*{except_}{replace}{rename}" 2666 2667 def parameter_sql(self, expression: exp.Parameter) -> str: 2668 this = self.sql(expression, "this") 2669 return f"{self.PARAMETER_TOKEN}{this}" 2670 2671 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2672 this = self.sql(expression, "this") 2673 kind = expression.text("kind") 2674 if kind: 2675 kind = f"{kind}." 2676 return f"@@{kind}{this}" 2677 2678 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2679 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2680 2681 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2682 alias = self.sql(expression, "alias") 2683 alias = f"{sep}{alias}" if alias else "" 2684 sample = self.sql(expression, "sample") 2685 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2686 alias = f"{sample}{alias}" 2687 2688 # Set to None so it's not generated again by self.query_modifiers() 2689 expression.set("sample", None) 2690 2691 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2692 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2693 return self.prepend_ctes(expression, sql) 2694 2695 def qualify_sql(self, expression: exp.Qualify) -> str: 2696 this = self.indent(self.sql(expression, "this")) 2697 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2698 2699 def unnest_sql(self, expression: exp.Unnest) -> str: 2700 args = self.expressions(expression, flat=True) 2701 2702 alias = expression.args.get("alias") 2703 offset = expression.args.get("offset") 2704 2705 if self.UNNEST_WITH_ORDINALITY: 2706 if alias and isinstance(offset, exp.Expression): 2707 alias.append("columns", offset) 2708 2709 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2710 columns = alias.columns 2711 alias = self.sql(columns[0]) if columns else "" 2712 else: 2713 alias = self.sql(alias) 2714 2715 alias = f" AS {alias}" if alias else alias 2716 if self.UNNEST_WITH_ORDINALITY: 2717 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2718 else: 2719 if isinstance(offset, exp.Expression): 2720 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2721 elif offset: 2722 suffix = f"{alias} WITH OFFSET" 2723 else: 2724 suffix = alias 2725 2726 return f"UNNEST({args}){suffix}" 2727 2728 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2729 return "" 2730 2731 def where_sql(self, expression: exp.Where) -> str: 2732 this = self.indent(self.sql(expression, "this")) 2733 return f"{self.seg('WHERE')}{self.sep()}{this}" 2734 2735 def window_sql(self, expression: exp.Window) -> str: 2736 this = self.sql(expression, "this") 2737 partition = self.partition_by_sql(expression) 2738 order = expression.args.get("order") 2739 order = self.order_sql(order, flat=True) if order else "" 2740 spec = self.sql(expression, "spec") 2741 alias = self.sql(expression, "alias") 2742 over = self.sql(expression, "over") or "OVER" 2743 2744 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2745 2746 first = expression.args.get("first") 2747 if first is None: 2748 first = "" 2749 else: 2750 first = "FIRST" if first else "LAST" 2751 2752 if not partition and not order and not spec and alias: 2753 return f"{this} {alias}" 2754 2755 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2756 return f"{this} ({args})" 2757 2758 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2759 partition = self.expressions(expression, key="partition_by", flat=True) 2760 return f"PARTITION BY {partition}" if partition else "" 2761 2762 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2763 kind = self.sql(expression, "kind") 2764 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2765 end = ( 2766 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2767 or "CURRENT ROW" 2768 ) 2769 return f"{kind} BETWEEN {start} AND {end}" 2770 2771 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2772 this = self.sql(expression, "this") 2773 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2774 return f"{this} WITHIN GROUP ({expression_sql})" 2775 2776 def between_sql(self, expression: exp.Between) -> str: 2777 this = self.sql(expression, "this") 2778 low = self.sql(expression, "low") 2779 high = self.sql(expression, "high") 2780 return f"{this} BETWEEN {low} AND {high}" 2781 2782 def bracket_offset_expressions( 2783 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2784 ) -> t.List[exp.Expression]: 2785 return apply_index_offset( 2786 expression.this, 2787 expression.expressions, 2788 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2789 ) 2790 2791 def bracket_sql(self, expression: exp.Bracket) -> str: 2792 expressions = self.bracket_offset_expressions(expression) 2793 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2794 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2795 2796 def all_sql(self, expression: exp.All) -> str: 2797 return f"ALL {self.wrap(expression)}" 2798 2799 def any_sql(self, expression: exp.Any) -> str: 2800 this = self.sql(expression, "this") 2801 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2802 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2803 this = self.wrap(this) 2804 return f"ANY{this}" 2805 return f"ANY {this}" 2806 2807 def exists_sql(self, expression: exp.Exists) -> str: 2808 return f"EXISTS{self.wrap(expression)}" 2809 2810 def case_sql(self, expression: exp.Case) -> str: 2811 this = self.sql(expression, "this") 2812 statements = [f"CASE {this}" if this else "CASE"] 2813 2814 for e in expression.args["ifs"]: 2815 statements.append(f"WHEN {self.sql(e, 'this')}") 2816 statements.append(f"THEN {self.sql(e, 'true')}") 2817 2818 default = self.sql(expression, "default") 2819 2820 if default: 2821 statements.append(f"ELSE {default}") 2822 2823 statements.append("END") 2824 2825 if self.pretty and self.too_wide(statements): 2826 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2827 2828 return " ".join(statements) 2829 2830 def constraint_sql(self, expression: exp.Constraint) -> str: 2831 this = self.sql(expression, "this") 2832 expressions = self.expressions(expression, flat=True) 2833 return f"CONSTRAINT {this} {expressions}" 2834 2835 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2836 order = expression.args.get("order") 2837 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2838 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2839 2840 def extract_sql(self, expression: exp.Extract) -> str: 2841 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2842 expression_sql = self.sql(expression, "expression") 2843 return f"EXTRACT({this} FROM {expression_sql})" 2844 2845 def trim_sql(self, expression: exp.Trim) -> str: 2846 trim_type = self.sql(expression, "position") 2847 2848 if trim_type == "LEADING": 2849 func_name = "LTRIM" 2850 elif trim_type == "TRAILING": 2851 func_name = "RTRIM" 2852 else: 2853 func_name = "TRIM" 2854 2855 return self.func(func_name, expression.this, expression.expression) 2856 2857 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2858 args = expression.expressions 2859 if isinstance(expression, exp.ConcatWs): 2860 args = args[1:] # Skip the delimiter 2861 2862 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2863 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2864 2865 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2866 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2867 2868 return args 2869 2870 def concat_sql(self, expression: exp.Concat) -> str: 2871 expressions = self.convert_concat_args(expression) 2872 2873 # Some dialects don't allow a single-argument CONCAT call 2874 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2875 return self.sql(expressions[0]) 2876 2877 return self.func("CONCAT", *expressions) 2878 2879 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2880 return self.func( 2881 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2882 ) 2883 2884 def check_sql(self, expression: exp.Check) -> str: 2885 this = self.sql(expression, key="this") 2886 return f"CHECK ({this})" 2887 2888 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2889 expressions = self.expressions(expression, flat=True) 2890 expressions = f" ({expressions})" if expressions else "" 2891 reference = self.sql(expression, "reference") 2892 reference = f" {reference}" if reference else "" 2893 delete = self.sql(expression, "delete") 2894 delete = f" ON DELETE {delete}" if delete else "" 2895 update = self.sql(expression, "update") 2896 update = f" ON UPDATE {update}" if update else "" 2897 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2898 2899 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2900 expressions = self.expressions(expression, flat=True) 2901 options = self.expressions(expression, key="options", flat=True, sep=" ") 2902 options = f" {options}" if options else "" 2903 return f"PRIMARY KEY ({expressions}){options}" 2904 2905 def if_sql(self, expression: exp.If) -> str: 2906 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2907 2908 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2909 modifier = expression.args.get("modifier") 2910 modifier = f" {modifier}" if modifier else "" 2911 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2912 2913 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2914 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2915 2916 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2917 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2918 2919 if expression.args.get("escape"): 2920 path = self.escape_str(path) 2921 2922 if self.QUOTE_JSON_PATH: 2923 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2924 2925 return path 2926 2927 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2928 if isinstance(expression, exp.JSONPathPart): 2929 transform = self.TRANSFORMS.get(expression.__class__) 2930 if not callable(transform): 2931 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2932 return "" 2933 2934 return transform(self, expression) 2935 2936 if isinstance(expression, int): 2937 return str(expression) 2938 2939 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2940 escaped = expression.replace("'", "\\'") 2941 escaped = f"\\'{expression}\\'" 2942 else: 2943 escaped = expression.replace('"', '\\"') 2944 escaped = f'"{escaped}"' 2945 2946 return escaped 2947 2948 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2949 return f"{self.sql(expression, 'this')} FORMAT JSON" 2950 2951 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2952 null_handling = expression.args.get("null_handling") 2953 null_handling = f" {null_handling}" if null_handling else "" 2954 2955 unique_keys = expression.args.get("unique_keys") 2956 if unique_keys is not None: 2957 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2958 else: 2959 unique_keys = "" 2960 2961 return_type = self.sql(expression, "return_type") 2962 return_type = f" RETURNING {return_type}" if return_type else "" 2963 encoding = self.sql(expression, "encoding") 2964 encoding = f" ENCODING {encoding}" if encoding else "" 2965 2966 return self.func( 2967 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2968 *expression.expressions, 2969 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2970 ) 2971 2972 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2973 return self.jsonobject_sql(expression) 2974 2975 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2976 null_handling = expression.args.get("null_handling") 2977 null_handling = f" {null_handling}" if null_handling else "" 2978 return_type = self.sql(expression, "return_type") 2979 return_type = f" RETURNING {return_type}" if return_type else "" 2980 strict = " STRICT" if expression.args.get("strict") else "" 2981 return self.func( 2982 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2983 ) 2984 2985 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2986 this = self.sql(expression, "this") 2987 order = self.sql(expression, "order") 2988 null_handling = expression.args.get("null_handling") 2989 null_handling = f" {null_handling}" if null_handling else "" 2990 return_type = self.sql(expression, "return_type") 2991 return_type = f" RETURNING {return_type}" if return_type else "" 2992 strict = " STRICT" if expression.args.get("strict") else "" 2993 return self.func( 2994 "JSON_ARRAYAGG", 2995 this, 2996 suffix=f"{order}{null_handling}{return_type}{strict})", 2997 ) 2998 2999 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3000 path = self.sql(expression, "path") 3001 path = f" PATH {path}" if path else "" 3002 nested_schema = self.sql(expression, "nested_schema") 3003 3004 if nested_schema: 3005 return f"NESTED{path} {nested_schema}" 3006 3007 this = self.sql(expression, "this") 3008 kind = self.sql(expression, "kind") 3009 kind = f" {kind}" if kind else "" 3010 return f"{this}{kind}{path}" 3011 3012 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3013 return self.func("COLUMNS", *expression.expressions) 3014 3015 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3016 this = self.sql(expression, "this") 3017 path = self.sql(expression, "path") 3018 path = f", {path}" if path else "" 3019 error_handling = expression.args.get("error_handling") 3020 error_handling = f" {error_handling}" if error_handling else "" 3021 empty_handling = expression.args.get("empty_handling") 3022 empty_handling = f" {empty_handling}" if empty_handling else "" 3023 schema = self.sql(expression, "schema") 3024 return self.func( 3025 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3026 ) 3027 3028 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3029 this = self.sql(expression, "this") 3030 kind = self.sql(expression, "kind") 3031 path = self.sql(expression, "path") 3032 path = f" {path}" if path else "" 3033 as_json = " AS JSON" if expression.args.get("as_json") else "" 3034 return f"{this} {kind}{path}{as_json}" 3035 3036 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3037 this = self.sql(expression, "this") 3038 path = self.sql(expression, "path") 3039 path = f", {path}" if path else "" 3040 expressions = self.expressions(expression) 3041 with_ = ( 3042 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3043 if expressions 3044 else "" 3045 ) 3046 return f"OPENJSON({this}{path}){with_}" 3047 3048 def in_sql(self, expression: exp.In) -> str: 3049 query = expression.args.get("query") 3050 unnest = expression.args.get("unnest") 3051 field = expression.args.get("field") 3052 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3053 3054 if query: 3055 in_sql = self.sql(query) 3056 elif unnest: 3057 in_sql = self.in_unnest_op(unnest) 3058 elif field: 3059 in_sql = self.sql(field) 3060 else: 3061 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3062 3063 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3064 3065 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3066 return f"(SELECT {self.sql(unnest)})" 3067 3068 def interval_sql(self, expression: exp.Interval) -> str: 3069 unit = self.sql(expression, "unit") 3070 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3071 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3072 unit = f" {unit}" if unit else "" 3073 3074 if self.SINGLE_STRING_INTERVAL: 3075 this = expression.this.name if expression.this else "" 3076 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3077 3078 this = self.sql(expression, "this") 3079 if this: 3080 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3081 this = f" {this}" if unwrapped else f" ({this})" 3082 3083 return f"INTERVAL{this}{unit}" 3084 3085 def return_sql(self, expression: exp.Return) -> str: 3086 return f"RETURN {self.sql(expression, 'this')}" 3087 3088 def reference_sql(self, expression: exp.Reference) -> str: 3089 this = self.sql(expression, "this") 3090 expressions = self.expressions(expression, flat=True) 3091 expressions = f"({expressions})" if expressions else "" 3092 options = self.expressions(expression, key="options", flat=True, sep=" ") 3093 options = f" {options}" if options else "" 3094 return f"REFERENCES {this}{expressions}{options}" 3095 3096 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3097 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3098 parent = expression.parent 3099 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3100 return self.func( 3101 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3102 ) 3103 3104 def paren_sql(self, expression: exp.Paren) -> str: 3105 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3106 return f"({sql}{self.seg(')', sep='')}" 3107 3108 def neg_sql(self, expression: exp.Neg) -> str: 3109 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3110 this_sql = self.sql(expression, "this") 3111 sep = " " if this_sql[0] == "-" else "" 3112 return f"-{sep}{this_sql}" 3113 3114 def not_sql(self, expression: exp.Not) -> str: 3115 return f"NOT {self.sql(expression, 'this')}" 3116 3117 def alias_sql(self, expression: exp.Alias) -> str: 3118 alias = self.sql(expression, "alias") 3119 alias = f" AS {alias}" if alias else "" 3120 return f"{self.sql(expression, 'this')}{alias}" 3121 3122 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3123 alias = expression.args["alias"] 3124 3125 parent = expression.parent 3126 pivot = parent and parent.parent 3127 3128 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3129 identifier_alias = isinstance(alias, exp.Identifier) 3130 literal_alias = isinstance(alias, exp.Literal) 3131 3132 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3133 alias.replace(exp.Literal.string(alias.output_name)) 3134 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3135 alias.replace(exp.to_identifier(alias.output_name)) 3136 3137 return self.alias_sql(expression) 3138 3139 def aliases_sql(self, expression: exp.Aliases) -> str: 3140 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3141 3142 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3143 this = self.sql(expression, "this") 3144 index = self.sql(expression, "expression") 3145 return f"{this} AT {index}" 3146 3147 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3148 this = self.sql(expression, "this") 3149 zone = self.sql(expression, "zone") 3150 return f"{this} AT TIME ZONE {zone}" 3151 3152 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3153 this = self.sql(expression, "this") 3154 zone = self.sql(expression, "zone") 3155 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3156 3157 def add_sql(self, expression: exp.Add) -> str: 3158 return self.binary(expression, "+") 3159 3160 def and_sql( 3161 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3162 ) -> str: 3163 return self.connector_sql(expression, "AND", stack) 3164 3165 def or_sql( 3166 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3167 ) -> str: 3168 return self.connector_sql(expression, "OR", stack) 3169 3170 def xor_sql( 3171 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3172 ) -> str: 3173 return self.connector_sql(expression, "XOR", stack) 3174 3175 def connector_sql( 3176 self, 3177 expression: exp.Connector, 3178 op: str, 3179 stack: t.Optional[t.List[str | exp.Expression]] = None, 3180 ) -> str: 3181 if stack is not None: 3182 if expression.expressions: 3183 stack.append(self.expressions(expression, sep=f" {op} ")) 3184 else: 3185 stack.append(expression.right) 3186 if expression.comments and self.comments: 3187 for comment in expression.comments: 3188 if comment: 3189 op += f" /*{self.pad_comment(comment)}*/" 3190 stack.extend((op, expression.left)) 3191 return op 3192 3193 stack = [expression] 3194 sqls: t.List[str] = [] 3195 ops = set() 3196 3197 while stack: 3198 node = stack.pop() 3199 if isinstance(node, exp.Connector): 3200 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3201 else: 3202 sql = self.sql(node) 3203 if sqls and sqls[-1] in ops: 3204 sqls[-1] += f" {sql}" 3205 else: 3206 sqls.append(sql) 3207 3208 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3209 return sep.join(sqls) 3210 3211 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3212 return self.binary(expression, "&") 3213 3214 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3215 return self.binary(expression, "<<") 3216 3217 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3218 return f"~{self.sql(expression, 'this')}" 3219 3220 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3221 return self.binary(expression, "|") 3222 3223 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3224 return self.binary(expression, ">>") 3225 3226 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3227 return self.binary(expression, "^") 3228 3229 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3230 format_sql = self.sql(expression, "format") 3231 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3232 to_sql = self.sql(expression, "to") 3233 to_sql = f" {to_sql}" if to_sql else "" 3234 action = self.sql(expression, "action") 3235 action = f" {action}" if action else "" 3236 default = self.sql(expression, "default") 3237 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3238 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3239 3240 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3241 zone = self.sql(expression, "this") 3242 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3243 3244 def collate_sql(self, expression: exp.Collate) -> str: 3245 if self.COLLATE_IS_FUNC: 3246 return self.function_fallback_sql(expression) 3247 return self.binary(expression, "COLLATE") 3248 3249 def command_sql(self, expression: exp.Command) -> str: 3250 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3251 3252 def comment_sql(self, expression: exp.Comment) -> str: 3253 this = self.sql(expression, "this") 3254 kind = expression.args["kind"] 3255 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3256 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3257 expression_sql = self.sql(expression, "expression") 3258 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3259 3260 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3261 this = self.sql(expression, "this") 3262 delete = " DELETE" if expression.args.get("delete") else "" 3263 recompress = self.sql(expression, "recompress") 3264 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3265 to_disk = self.sql(expression, "to_disk") 3266 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3267 to_volume = self.sql(expression, "to_volume") 3268 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3269 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3270 3271 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3272 where = self.sql(expression, "where") 3273 group = self.sql(expression, "group") 3274 aggregates = self.expressions(expression, key="aggregates") 3275 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3276 3277 if not (where or group or aggregates) and len(expression.expressions) == 1: 3278 return f"TTL {self.expressions(expression, flat=True)}" 3279 3280 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3281 3282 def transaction_sql(self, expression: exp.Transaction) -> str: 3283 return "BEGIN" 3284 3285 def commit_sql(self, expression: exp.Commit) -> str: 3286 chain = expression.args.get("chain") 3287 if chain is not None: 3288 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3289 3290 return f"COMMIT{chain or ''}" 3291 3292 def rollback_sql(self, expression: exp.Rollback) -> str: 3293 savepoint = expression.args.get("savepoint") 3294 savepoint = f" TO {savepoint}" if savepoint else "" 3295 return f"ROLLBACK{savepoint}" 3296 3297 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3298 this = self.sql(expression, "this") 3299 3300 dtype = self.sql(expression, "dtype") 3301 if dtype: 3302 collate = self.sql(expression, "collate") 3303 collate = f" COLLATE {collate}" if collate else "" 3304 using = self.sql(expression, "using") 3305 using = f" USING {using}" if using else "" 3306 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3307 3308 default = self.sql(expression, "default") 3309 if default: 3310 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3311 3312 comment = self.sql(expression, "comment") 3313 if comment: 3314 return f"ALTER COLUMN {this} COMMENT {comment}" 3315 3316 visible = expression.args.get("visible") 3317 if visible: 3318 return f"ALTER COLUMN {this} SET {visible}" 3319 3320 allow_null = expression.args.get("allow_null") 3321 drop = expression.args.get("drop") 3322 3323 if not drop and not allow_null: 3324 self.unsupported("Unsupported ALTER COLUMN syntax") 3325 3326 if allow_null is not None: 3327 keyword = "DROP" if drop else "SET" 3328 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3329 3330 return f"ALTER COLUMN {this} DROP DEFAULT" 3331 3332 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3333 this = self.sql(expression, "this") 3334 3335 visible = expression.args.get("visible") 3336 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3337 3338 return f"ALTER INDEX {this} {visible_sql}" 3339 3340 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3341 this = self.sql(expression, "this") 3342 if not isinstance(expression.this, exp.Var): 3343 this = f"KEY DISTKEY {this}" 3344 return f"ALTER DISTSTYLE {this}" 3345 3346 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3347 compound = " COMPOUND" if expression.args.get("compound") else "" 3348 this = self.sql(expression, "this") 3349 expressions = self.expressions(expression, flat=True) 3350 expressions = f"({expressions})" if expressions else "" 3351 return f"ALTER{compound} SORTKEY {this or expressions}" 3352 3353 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3354 if not self.RENAME_TABLE_WITH_DB: 3355 # Remove db from tables 3356 expression = expression.transform( 3357 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3358 ).assert_is(exp.AlterRename) 3359 this = self.sql(expression, "this") 3360 return f"RENAME TO {this}" 3361 3362 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3363 exists = " IF EXISTS" if expression.args.get("exists") else "" 3364 old_column = self.sql(expression, "this") 3365 new_column = self.sql(expression, "to") 3366 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3367 3368 def alterset_sql(self, expression: exp.AlterSet) -> str: 3369 exprs = self.expressions(expression, flat=True) 3370 return f"SET {exprs}" 3371 3372 def alter_sql(self, expression: exp.Alter) -> str: 3373 actions = expression.args["actions"] 3374 3375 if isinstance(actions[0], exp.ColumnDef): 3376 actions = self.add_column_sql(expression) 3377 elif isinstance(actions[0], exp.Schema): 3378 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3379 elif isinstance(actions[0], exp.Delete): 3380 actions = self.expressions(expression, key="actions", flat=True) 3381 elif isinstance(actions[0], exp.Query): 3382 actions = "AS " + self.expressions(expression, key="actions") 3383 else: 3384 actions = self.expressions(expression, key="actions", flat=True) 3385 3386 exists = " IF EXISTS" if expression.args.get("exists") else "" 3387 on_cluster = self.sql(expression, "cluster") 3388 on_cluster = f" {on_cluster}" if on_cluster else "" 3389 only = " ONLY" if expression.args.get("only") else "" 3390 options = self.expressions(expression, key="options") 3391 options = f", {options}" if options else "" 3392 kind = self.sql(expression, "kind") 3393 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3394 3395 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3396 3397 def add_column_sql(self, expression: exp.Alter) -> str: 3398 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3399 return self.expressions( 3400 expression, 3401 key="actions", 3402 prefix="ADD COLUMN ", 3403 skip_first=True, 3404 ) 3405 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3406 3407 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3408 expressions = self.expressions(expression) 3409 exists = " IF EXISTS " if expression.args.get("exists") else " " 3410 return f"DROP{exists}{expressions}" 3411 3412 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3413 return f"ADD {self.expressions(expression)}" 3414 3415 def distinct_sql(self, expression: exp.Distinct) -> str: 3416 this = self.expressions(expression, flat=True) 3417 3418 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3419 case = exp.case() 3420 for arg in expression.expressions: 3421 case = case.when(arg.is_(exp.null()), exp.null()) 3422 this = self.sql(case.else_(f"({this})")) 3423 3424 this = f" {this}" if this else "" 3425 3426 on = self.sql(expression, "on") 3427 on = f" ON {on}" if on else "" 3428 return f"DISTINCT{this}{on}" 3429 3430 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3431 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3432 3433 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3434 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3435 3436 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3437 this_sql = self.sql(expression, "this") 3438 expression_sql = self.sql(expression, "expression") 3439 kind = "MAX" if expression.args.get("max") else "MIN" 3440 return f"{this_sql} HAVING {kind} {expression_sql}" 3441 3442 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3443 return self.sql( 3444 exp.Cast( 3445 this=exp.Div(this=expression.this, expression=expression.expression), 3446 to=exp.DataType(this=exp.DataType.Type.INT), 3447 ) 3448 ) 3449 3450 def dpipe_sql(self, expression: exp.DPipe) -> str: 3451 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3452 return self.func( 3453 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3454 ) 3455 return self.binary(expression, "||") 3456 3457 def div_sql(self, expression: exp.Div) -> str: 3458 l, r = expression.left, expression.right 3459 3460 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3461 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3462 3463 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3464 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3465 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3466 3467 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3468 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3469 return self.sql( 3470 exp.cast( 3471 l / r, 3472 to=exp.DataType.Type.BIGINT, 3473 ) 3474 ) 3475 3476 return self.binary(expression, "/") 3477 3478 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3479 n = exp._wrap(expression.this, exp.Binary) 3480 d = exp._wrap(expression.expression, exp.Binary) 3481 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3482 3483 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3484 return self.binary(expression, "OVERLAPS") 3485 3486 def distance_sql(self, expression: exp.Distance) -> str: 3487 return self.binary(expression, "<->") 3488 3489 def dot_sql(self, expression: exp.Dot) -> str: 3490 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3491 3492 def eq_sql(self, expression: exp.EQ) -> str: 3493 return self.binary(expression, "=") 3494 3495 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3496 return self.binary(expression, ":=") 3497 3498 def escape_sql(self, expression: exp.Escape) -> str: 3499 return self.binary(expression, "ESCAPE") 3500 3501 def glob_sql(self, expression: exp.Glob) -> str: 3502 return self.binary(expression, "GLOB") 3503 3504 def gt_sql(self, expression: exp.GT) -> str: 3505 return self.binary(expression, ">") 3506 3507 def gte_sql(self, expression: exp.GTE) -> str: 3508 return self.binary(expression, ">=") 3509 3510 def ilike_sql(self, expression: exp.ILike) -> str: 3511 return self.binary(expression, "ILIKE") 3512 3513 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3514 return self.binary(expression, "ILIKE ANY") 3515 3516 def is_sql(self, expression: exp.Is) -> str: 3517 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3518 return self.sql( 3519 expression.this if expression.expression.this else exp.not_(expression.this) 3520 ) 3521 return self.binary(expression, "IS") 3522 3523 def like_sql(self, expression: exp.Like) -> str: 3524 return self.binary(expression, "LIKE") 3525 3526 def likeany_sql(self, expression: exp.LikeAny) -> str: 3527 return self.binary(expression, "LIKE ANY") 3528 3529 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3530 return self.binary(expression, "SIMILAR TO") 3531 3532 def lt_sql(self, expression: exp.LT) -> str: 3533 return self.binary(expression, "<") 3534 3535 def lte_sql(self, expression: exp.LTE) -> str: 3536 return self.binary(expression, "<=") 3537 3538 def mod_sql(self, expression: exp.Mod) -> str: 3539 return self.binary(expression, "%") 3540 3541 def mul_sql(self, expression: exp.Mul) -> str: 3542 return self.binary(expression, "*") 3543 3544 def neq_sql(self, expression: exp.NEQ) -> str: 3545 return self.binary(expression, "<>") 3546 3547 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3548 return self.binary(expression, "IS NOT DISTINCT FROM") 3549 3550 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3551 return self.binary(expression, "IS DISTINCT FROM") 3552 3553 def slice_sql(self, expression: exp.Slice) -> str: 3554 return self.binary(expression, ":") 3555 3556 def sub_sql(self, expression: exp.Sub) -> str: 3557 return self.binary(expression, "-") 3558 3559 def trycast_sql(self, expression: exp.TryCast) -> str: 3560 return self.cast_sql(expression, safe_prefix="TRY_") 3561 3562 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3563 return self.cast_sql(expression) 3564 3565 def try_sql(self, expression: exp.Try) -> str: 3566 if not self.TRY_SUPPORTED: 3567 self.unsupported("Unsupported TRY function") 3568 return self.sql(expression, "this") 3569 3570 return self.func("TRY", expression.this) 3571 3572 def log_sql(self, expression: exp.Log) -> str: 3573 this = expression.this 3574 expr = expression.expression 3575 3576 if self.dialect.LOG_BASE_FIRST is False: 3577 this, expr = expr, this 3578 elif self.dialect.LOG_BASE_FIRST is None and expr: 3579 if this.name in ("2", "10"): 3580 return self.func(f"LOG{this.name}", expr) 3581 3582 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3583 3584 return self.func("LOG", this, expr) 3585 3586 def use_sql(self, expression: exp.Use) -> str: 3587 kind = self.sql(expression, "kind") 3588 kind = f" {kind}" if kind else "" 3589 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3590 this = f" {this}" if this else "" 3591 return f"USE{kind}{this}" 3592 3593 def binary(self, expression: exp.Binary, op: str) -> str: 3594 sqls: t.List[str] = [] 3595 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3596 binary_type = type(expression) 3597 3598 while stack: 3599 node = stack.pop() 3600 3601 if type(node) is binary_type: 3602 op_func = node.args.get("operator") 3603 if op_func: 3604 op = f"OPERATOR({self.sql(op_func)})" 3605 3606 stack.append(node.right) 3607 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3608 stack.append(node.left) 3609 else: 3610 sqls.append(self.sql(node)) 3611 3612 return "".join(sqls) 3613 3614 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3615 to_clause = self.sql(expression, "to") 3616 if to_clause: 3617 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3618 3619 return self.function_fallback_sql(expression) 3620 3621 def function_fallback_sql(self, expression: exp.Func) -> str: 3622 args = [] 3623 3624 for key in expression.arg_types: 3625 arg_value = expression.args.get(key) 3626 3627 if isinstance(arg_value, list): 3628 for value in arg_value: 3629 args.append(value) 3630 elif arg_value is not None: 3631 args.append(arg_value) 3632 3633 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3634 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3635 else: 3636 name = expression.sql_name() 3637 3638 return self.func(name, *args) 3639 3640 def func( 3641 self, 3642 name: str, 3643 *args: t.Optional[exp.Expression | str], 3644 prefix: str = "(", 3645 suffix: str = ")", 3646 normalize: bool = True, 3647 ) -> str: 3648 name = self.normalize_func(name) if normalize else name 3649 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3650 3651 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3652 arg_sqls = tuple( 3653 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3654 ) 3655 if self.pretty and self.too_wide(arg_sqls): 3656 return self.indent( 3657 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3658 ) 3659 return sep.join(arg_sqls) 3660 3661 def too_wide(self, args: t.Iterable) -> bool: 3662 return sum(len(arg) for arg in args) > self.max_text_width 3663 3664 def format_time( 3665 self, 3666 expression: exp.Expression, 3667 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3668 inverse_time_trie: t.Optional[t.Dict] = None, 3669 ) -> t.Optional[str]: 3670 return format_time( 3671 self.sql(expression, "format"), 3672 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3673 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3674 ) 3675 3676 def expressions( 3677 self, 3678 expression: t.Optional[exp.Expression] = None, 3679 key: t.Optional[str] = None, 3680 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3681 flat: bool = False, 3682 indent: bool = True, 3683 skip_first: bool = False, 3684 skip_last: bool = False, 3685 sep: str = ", ", 3686 prefix: str = "", 3687 dynamic: bool = False, 3688 new_line: bool = False, 3689 ) -> str: 3690 expressions = expression.args.get(key or "expressions") if expression else sqls 3691 3692 if not expressions: 3693 return "" 3694 3695 if flat: 3696 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3697 3698 num_sqls = len(expressions) 3699 result_sqls = [] 3700 3701 for i, e in enumerate(expressions): 3702 sql = self.sql(e, comment=False) 3703 if not sql: 3704 continue 3705 3706 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3707 3708 if self.pretty: 3709 if self.leading_comma: 3710 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3711 else: 3712 result_sqls.append( 3713 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3714 ) 3715 else: 3716 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3717 3718 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3719 if new_line: 3720 result_sqls.insert(0, "") 3721 result_sqls.append("") 3722 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3723 else: 3724 result_sql = "".join(result_sqls) 3725 3726 return ( 3727 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3728 if indent 3729 else result_sql 3730 ) 3731 3732 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3733 flat = flat or isinstance(expression.parent, exp.Properties) 3734 expressions_sql = self.expressions(expression, flat=flat) 3735 if flat: 3736 return f"{op} {expressions_sql}" 3737 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3738 3739 def naked_property(self, expression: exp.Property) -> str: 3740 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3741 if not property_name: 3742 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3743 return f"{property_name} {self.sql(expression, 'this')}" 3744 3745 def tag_sql(self, expression: exp.Tag) -> str: 3746 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3747 3748 def token_sql(self, token_type: TokenType) -> str: 3749 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3750 3751 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3752 this = self.sql(expression, "this") 3753 expressions = self.no_identify(self.expressions, expression) 3754 expressions = ( 3755 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3756 ) 3757 return f"{this}{expressions}" if expressions.strip() != "" else this 3758 3759 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3760 this = self.sql(expression, "this") 3761 expressions = self.expressions(expression, flat=True) 3762 return f"{this}({expressions})" 3763 3764 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3765 return self.binary(expression, "=>") 3766 3767 def when_sql(self, expression: exp.When) -> str: 3768 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3769 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3770 condition = self.sql(expression, "condition") 3771 condition = f" AND {condition}" if condition else "" 3772 3773 then_expression = expression.args.get("then") 3774 if isinstance(then_expression, exp.Insert): 3775 this = self.sql(then_expression, "this") 3776 this = f"INSERT {this}" if this else "INSERT" 3777 then = self.sql(then_expression, "expression") 3778 then = f"{this} VALUES {then}" if then else this 3779 elif isinstance(then_expression, exp.Update): 3780 if isinstance(then_expression.args.get("expressions"), exp.Star): 3781 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3782 else: 3783 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3784 else: 3785 then = self.sql(then_expression) 3786 return f"WHEN {matched}{source}{condition} THEN {then}" 3787 3788 def whens_sql(self, expression: exp.Whens) -> str: 3789 return self.expressions(expression, sep=" ", indent=False) 3790 3791 def merge_sql(self, expression: exp.Merge) -> str: 3792 table = expression.this 3793 table_alias = "" 3794 3795 hints = table.args.get("hints") 3796 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3797 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3798 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3799 3800 this = self.sql(table) 3801 using = f"USING {self.sql(expression, 'using')}" 3802 on = f"ON {self.sql(expression, 'on')}" 3803 whens = self.sql(expression, "whens") 3804 3805 returning = self.sql(expression, "returning") 3806 if returning: 3807 whens = f"{whens}{returning}" 3808 3809 sep = self.sep() 3810 3811 return self.prepend_ctes( 3812 expression, 3813 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3814 ) 3815 3816 @unsupported_args("format") 3817 def tochar_sql(self, expression: exp.ToChar) -> str: 3818 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3819 3820 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3821 if not self.SUPPORTS_TO_NUMBER: 3822 self.unsupported("Unsupported TO_NUMBER function") 3823 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3824 3825 fmt = expression.args.get("format") 3826 if not fmt: 3827 self.unsupported("Conversion format is required for TO_NUMBER") 3828 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3829 3830 return self.func("TO_NUMBER", expression.this, fmt) 3831 3832 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3833 this = self.sql(expression, "this") 3834 kind = self.sql(expression, "kind") 3835 settings_sql = self.expressions(expression, key="settings", sep=" ") 3836 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3837 return f"{this}({kind}{args})" 3838 3839 def dictrange_sql(self, expression: exp.DictRange) -> str: 3840 this = self.sql(expression, "this") 3841 max = self.sql(expression, "max") 3842 min = self.sql(expression, "min") 3843 return f"{this}(MIN {min} MAX {max})" 3844 3845 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3846 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3847 3848 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3849 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3850 3851 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3852 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3853 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3854 3855 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3856 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3857 expressions = self.expressions(expression, flat=True) 3858 expressions = f" {self.wrap(expressions)}" if expressions else "" 3859 buckets = self.sql(expression, "buckets") 3860 kind = self.sql(expression, "kind") 3861 buckets = f" BUCKETS {buckets}" if buckets else "" 3862 order = self.sql(expression, "order") 3863 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3864 3865 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3866 return "" 3867 3868 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3869 expressions = self.expressions(expression, key="expressions", flat=True) 3870 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3871 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3872 buckets = self.sql(expression, "buckets") 3873 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3874 3875 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3876 this = self.sql(expression, "this") 3877 having = self.sql(expression, "having") 3878 3879 if having: 3880 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3881 3882 return self.func("ANY_VALUE", this) 3883 3884 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3885 transform = self.func("TRANSFORM", *expression.expressions) 3886 row_format_before = self.sql(expression, "row_format_before") 3887 row_format_before = f" {row_format_before}" if row_format_before else "" 3888 record_writer = self.sql(expression, "record_writer") 3889 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3890 using = f" USING {self.sql(expression, 'command_script')}" 3891 schema = self.sql(expression, "schema") 3892 schema = f" AS {schema}" if schema else "" 3893 row_format_after = self.sql(expression, "row_format_after") 3894 row_format_after = f" {row_format_after}" if row_format_after else "" 3895 record_reader = self.sql(expression, "record_reader") 3896 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3897 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3898 3899 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3900 key_block_size = self.sql(expression, "key_block_size") 3901 if key_block_size: 3902 return f"KEY_BLOCK_SIZE = {key_block_size}" 3903 3904 using = self.sql(expression, "using") 3905 if using: 3906 return f"USING {using}" 3907 3908 parser = self.sql(expression, "parser") 3909 if parser: 3910 return f"WITH PARSER {parser}" 3911 3912 comment = self.sql(expression, "comment") 3913 if comment: 3914 return f"COMMENT {comment}" 3915 3916 visible = expression.args.get("visible") 3917 if visible is not None: 3918 return "VISIBLE" if visible else "INVISIBLE" 3919 3920 engine_attr = self.sql(expression, "engine_attr") 3921 if engine_attr: 3922 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3923 3924 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3925 if secondary_engine_attr: 3926 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3927 3928 self.unsupported("Unsupported index constraint option.") 3929 return "" 3930 3931 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3932 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3933 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3934 3935 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3936 kind = self.sql(expression, "kind") 3937 kind = f"{kind} INDEX" if kind else "INDEX" 3938 this = self.sql(expression, "this") 3939 this = f" {this}" if this else "" 3940 index_type = self.sql(expression, "index_type") 3941 index_type = f" USING {index_type}" if index_type else "" 3942 expressions = self.expressions(expression, flat=True) 3943 expressions = f" ({expressions})" if expressions else "" 3944 options = self.expressions(expression, key="options", sep=" ") 3945 options = f" {options}" if options else "" 3946 return f"{kind}{this}{index_type}{expressions}{options}" 3947 3948 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3949 if self.NVL2_SUPPORTED: 3950 return self.function_fallback_sql(expression) 3951 3952 case = exp.Case().when( 3953 expression.this.is_(exp.null()).not_(copy=False), 3954 expression.args["true"], 3955 copy=False, 3956 ) 3957 else_cond = expression.args.get("false") 3958 if else_cond: 3959 case.else_(else_cond, copy=False) 3960 3961 return self.sql(case) 3962 3963 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3964 this = self.sql(expression, "this") 3965 expr = self.sql(expression, "expression") 3966 iterator = self.sql(expression, "iterator") 3967 condition = self.sql(expression, "condition") 3968 condition = f" IF {condition}" if condition else "" 3969 return f"{this} FOR {expr} IN {iterator}{condition}" 3970 3971 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3972 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3973 3974 def opclass_sql(self, expression: exp.Opclass) -> str: 3975 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3976 3977 def predict_sql(self, expression: exp.Predict) -> str: 3978 model = self.sql(expression, "this") 3979 model = f"MODEL {model}" 3980 table = self.sql(expression, "expression") 3981 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3982 parameters = self.sql(expression, "params_struct") 3983 return self.func("PREDICT", model, table, parameters or None) 3984 3985 def forin_sql(self, expression: exp.ForIn) -> str: 3986 this = self.sql(expression, "this") 3987 expression_sql = self.sql(expression, "expression") 3988 return f"FOR {this} DO {expression_sql}" 3989 3990 def refresh_sql(self, expression: exp.Refresh) -> str: 3991 this = self.sql(expression, "this") 3992 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3993 return f"REFRESH {table}{this}" 3994 3995 def toarray_sql(self, expression: exp.ToArray) -> str: 3996 arg = expression.this 3997 if not arg.type: 3998 from sqlglot.optimizer.annotate_types import annotate_types 3999 4000 arg = annotate_types(arg) 4001 4002 if arg.is_type(exp.DataType.Type.ARRAY): 4003 return self.sql(arg) 4004 4005 cond_for_null = arg.is_(exp.null()) 4006 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4007 4008 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4009 this = expression.this 4010 time_format = self.format_time(expression) 4011 4012 if time_format: 4013 return self.sql( 4014 exp.cast( 4015 exp.StrToTime(this=this, format=expression.args["format"]), 4016 exp.DataType.Type.TIME, 4017 ) 4018 ) 4019 4020 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4021 return self.sql(this) 4022 4023 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4024 4025 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4026 this = expression.this 4027 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4028 return self.sql(this) 4029 4030 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4031 4032 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4033 this = expression.this 4034 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4035 return self.sql(this) 4036 4037 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4038 4039 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4040 this = expression.this 4041 time_format = self.format_time(expression) 4042 4043 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4044 return self.sql( 4045 exp.cast( 4046 exp.StrToTime(this=this, format=expression.args["format"]), 4047 exp.DataType.Type.DATE, 4048 ) 4049 ) 4050 4051 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4052 return self.sql(this) 4053 4054 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4055 4056 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4057 return self.sql( 4058 exp.func( 4059 "DATEDIFF", 4060 expression.this, 4061 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4062 "day", 4063 ) 4064 ) 4065 4066 def lastday_sql(self, expression: exp.LastDay) -> str: 4067 if self.LAST_DAY_SUPPORTS_DATE_PART: 4068 return self.function_fallback_sql(expression) 4069 4070 unit = expression.text("unit") 4071 if unit and unit != "MONTH": 4072 self.unsupported("Date parts are not supported in LAST_DAY.") 4073 4074 return self.func("LAST_DAY", expression.this) 4075 4076 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4077 from sqlglot.dialects.dialect import unit_to_str 4078 4079 return self.func( 4080 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4081 ) 4082 4083 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4084 if self.CAN_IMPLEMENT_ARRAY_ANY: 4085 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4086 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4087 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4088 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4089 4090 from sqlglot.dialects import Dialect 4091 4092 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4093 if self.dialect.__class__ != Dialect: 4094 self.unsupported("ARRAY_ANY is unsupported") 4095 4096 return self.function_fallback_sql(expression) 4097 4098 def struct_sql(self, expression: exp.Struct) -> str: 4099 expression.set( 4100 "expressions", 4101 [ 4102 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4103 if isinstance(e, exp.PropertyEQ) 4104 else e 4105 for e in expression.expressions 4106 ], 4107 ) 4108 4109 return self.function_fallback_sql(expression) 4110 4111 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4112 low = self.sql(expression, "this") 4113 high = self.sql(expression, "expression") 4114 4115 return f"{low} TO {high}" 4116 4117 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4118 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4119 tables = f" {self.expressions(expression)}" 4120 4121 exists = " IF EXISTS" if expression.args.get("exists") else "" 4122 4123 on_cluster = self.sql(expression, "cluster") 4124 on_cluster = f" {on_cluster}" if on_cluster else "" 4125 4126 identity = self.sql(expression, "identity") 4127 identity = f" {identity} IDENTITY" if identity else "" 4128 4129 option = self.sql(expression, "option") 4130 option = f" {option}" if option else "" 4131 4132 partition = self.sql(expression, "partition") 4133 partition = f" {partition}" if partition else "" 4134 4135 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4136 4137 # This transpiles T-SQL's CONVERT function 4138 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4139 def convert_sql(self, expression: exp.Convert) -> str: 4140 to = expression.this 4141 value = expression.expression 4142 style = expression.args.get("style") 4143 safe = expression.args.get("safe") 4144 strict = expression.args.get("strict") 4145 4146 if not to or not value: 4147 return "" 4148 4149 # Retrieve length of datatype and override to default if not specified 4150 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4151 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4152 4153 transformed: t.Optional[exp.Expression] = None 4154 cast = exp.Cast if strict else exp.TryCast 4155 4156 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4157 if isinstance(style, exp.Literal) and style.is_int: 4158 from sqlglot.dialects.tsql import TSQL 4159 4160 style_value = style.name 4161 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4162 if not converted_style: 4163 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4164 4165 fmt = exp.Literal.string(converted_style) 4166 4167 if to.this == exp.DataType.Type.DATE: 4168 transformed = exp.StrToDate(this=value, format=fmt) 4169 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4170 transformed = exp.StrToTime(this=value, format=fmt) 4171 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4172 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4173 elif to.this == exp.DataType.Type.TEXT: 4174 transformed = exp.TimeToStr(this=value, format=fmt) 4175 4176 if not transformed: 4177 transformed = cast(this=value, to=to, safe=safe) 4178 4179 return self.sql(transformed) 4180 4181 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4182 this = expression.this 4183 if isinstance(this, exp.JSONPathWildcard): 4184 this = self.json_path_part(this) 4185 return f".{this}" if this else "" 4186 4187 if exp.SAFE_IDENTIFIER_RE.match(this): 4188 return f".{this}" 4189 4190 this = self.json_path_part(this) 4191 return ( 4192 f"[{this}]" 4193 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4194 else f".{this}" 4195 ) 4196 4197 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4198 this = self.json_path_part(expression.this) 4199 return f"[{this}]" if this else "" 4200 4201 def _simplify_unless_literal(self, expression: E) -> E: 4202 if not isinstance(expression, exp.Literal): 4203 from sqlglot.optimizer.simplify import simplify 4204 4205 expression = simplify(expression, dialect=self.dialect) 4206 4207 return expression 4208 4209 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4210 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4211 # The first modifier here will be the one closest to the AggFunc's arg 4212 mods = sorted( 4213 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4214 key=lambda x: 0 4215 if isinstance(x, exp.HavingMax) 4216 else (1 if isinstance(x, exp.Order) else 2), 4217 ) 4218 4219 if mods: 4220 mod = mods[0] 4221 this = expression.__class__(this=mod.this.copy()) 4222 this.meta["inline"] = True 4223 mod.this.replace(this) 4224 return self.sql(expression.this) 4225 4226 agg_func = expression.find(exp.AggFunc) 4227 4228 if agg_func: 4229 return self.sql(agg_func)[:-1] + f" {text})" 4230 4231 return f"{self.sql(expression, 'this')} {text}" 4232 4233 def _replace_line_breaks(self, string: str) -> str: 4234 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4235 if self.pretty: 4236 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4237 return string 4238 4239 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4240 option = self.sql(expression, "this") 4241 4242 if expression.expressions: 4243 upper = option.upper() 4244 4245 # Snowflake FILE_FORMAT options are separated by whitespace 4246 sep = " " if upper == "FILE_FORMAT" else ", " 4247 4248 # Databricks copy/format options do not set their list of values with EQ 4249 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4250 values = self.expressions(expression, flat=True, sep=sep) 4251 return f"{option}{op}({values})" 4252 4253 value = self.sql(expression, "expression") 4254 4255 if not value: 4256 return option 4257 4258 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4259 4260 return f"{option}{op}{value}" 4261 4262 def credentials_sql(self, expression: exp.Credentials) -> str: 4263 cred_expr = expression.args.get("credentials") 4264 if isinstance(cred_expr, exp.Literal): 4265 # Redshift case: CREDENTIALS <string> 4266 credentials = self.sql(expression, "credentials") 4267 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4268 else: 4269 # Snowflake case: CREDENTIALS = (...) 4270 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4271 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4272 4273 storage = self.sql(expression, "storage") 4274 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4275 4276 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4277 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4278 4279 iam_role = self.sql(expression, "iam_role") 4280 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4281 4282 region = self.sql(expression, "region") 4283 region = f" REGION {region}" if region else "" 4284 4285 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4286 4287 def copy_sql(self, expression: exp.Copy) -> str: 4288 this = self.sql(expression, "this") 4289 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4290 4291 credentials = self.sql(expression, "credentials") 4292 credentials = self.seg(credentials) if credentials else "" 4293 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4294 files = self.expressions(expression, key="files", flat=True) 4295 4296 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4297 params = self.expressions( 4298 expression, 4299 key="params", 4300 sep=sep, 4301 new_line=True, 4302 skip_last=True, 4303 skip_first=True, 4304 indent=self.COPY_PARAMS_ARE_WRAPPED, 4305 ) 4306 4307 if params: 4308 if self.COPY_PARAMS_ARE_WRAPPED: 4309 params = f" WITH ({params})" 4310 elif not self.pretty: 4311 params = f" {params}" 4312 4313 return f"COPY{this}{kind} {files}{credentials}{params}" 4314 4315 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4316 return "" 4317 4318 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4319 on_sql = "ON" if expression.args.get("on") else "OFF" 4320 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4321 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4322 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4323 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4324 4325 if filter_col or retention_period: 4326 on_sql = self.func("ON", filter_col, retention_period) 4327 4328 return f"DATA_DELETION={on_sql}" 4329 4330 def maskingpolicycolumnconstraint_sql( 4331 self, expression: exp.MaskingPolicyColumnConstraint 4332 ) -> str: 4333 this = self.sql(expression, "this") 4334 expressions = self.expressions(expression, flat=True) 4335 expressions = f" USING ({expressions})" if expressions else "" 4336 return f"MASKING POLICY {this}{expressions}" 4337 4338 def gapfill_sql(self, expression: exp.GapFill) -> str: 4339 this = self.sql(expression, "this") 4340 this = f"TABLE {this}" 4341 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4342 4343 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4344 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4345 4346 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4347 this = self.sql(expression, "this") 4348 expr = expression.expression 4349 4350 if isinstance(expr, exp.Func): 4351 # T-SQL's CLR functions are case sensitive 4352 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4353 else: 4354 expr = self.sql(expression, "expression") 4355 4356 return self.scope_resolution(expr, this) 4357 4358 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4359 if self.PARSE_JSON_NAME is None: 4360 return self.sql(expression.this) 4361 4362 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4363 4364 def rand_sql(self, expression: exp.Rand) -> str: 4365 lower = self.sql(expression, "lower") 4366 upper = self.sql(expression, "upper") 4367 4368 if lower and upper: 4369 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4370 return self.func("RAND", expression.this) 4371 4372 def changes_sql(self, expression: exp.Changes) -> str: 4373 information = self.sql(expression, "information") 4374 information = f"INFORMATION => {information}" 4375 at_before = self.sql(expression, "at_before") 4376 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4377 end = self.sql(expression, "end") 4378 end = f"{self.seg('')}{end}" if end else "" 4379 4380 return f"CHANGES ({information}){at_before}{end}" 4381 4382 def pad_sql(self, expression: exp.Pad) -> str: 4383 prefix = "L" if expression.args.get("is_left") else "R" 4384 4385 fill_pattern = self.sql(expression, "fill_pattern") or None 4386 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4387 fill_pattern = "' '" 4388 4389 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4390 4391 def summarize_sql(self, expression: exp.Summarize) -> str: 4392 table = " TABLE" if expression.args.get("table") else "" 4393 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4394 4395 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4396 generate_series = exp.GenerateSeries(**expression.args) 4397 4398 parent = expression.parent 4399 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4400 parent = parent.parent 4401 4402 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4403 return self.sql(exp.Unnest(expressions=[generate_series])) 4404 4405 if isinstance(parent, exp.Select): 4406 self.unsupported("GenerateSeries projection unnesting is not supported.") 4407 4408 return self.sql(generate_series) 4409 4410 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4411 exprs = expression.expressions 4412 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4413 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4414 else: 4415 rhs = self.expressions(expression) 4416 4417 return self.func(name, expression.this, rhs or None) 4418 4419 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4420 if self.SUPPORTS_CONVERT_TIMEZONE: 4421 return self.function_fallback_sql(expression) 4422 4423 source_tz = expression.args.get("source_tz") 4424 target_tz = expression.args.get("target_tz") 4425 timestamp = expression.args.get("timestamp") 4426 4427 if source_tz and timestamp: 4428 timestamp = exp.AtTimeZone( 4429 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4430 ) 4431 4432 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4433 4434 return self.sql(expr) 4435 4436 def json_sql(self, expression: exp.JSON) -> str: 4437 this = self.sql(expression, "this") 4438 this = f" {this}" if this else "" 4439 4440 _with = expression.args.get("with") 4441 4442 if _with is None: 4443 with_sql = "" 4444 elif not _with: 4445 with_sql = " WITHOUT" 4446 else: 4447 with_sql = " WITH" 4448 4449 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4450 4451 return f"JSON{this}{with_sql}{unique_sql}" 4452 4453 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4454 def _generate_on_options(arg: t.Any) -> str: 4455 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4456 4457 path = self.sql(expression, "path") 4458 returning = self.sql(expression, "returning") 4459 returning = f" RETURNING {returning}" if returning else "" 4460 4461 on_condition = self.sql(expression, "on_condition") 4462 on_condition = f" {on_condition}" if on_condition else "" 4463 4464 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4465 4466 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4467 else_ = "ELSE " if expression.args.get("else_") else "" 4468 condition = self.sql(expression, "expression") 4469 condition = f"WHEN {condition} THEN " if condition else else_ 4470 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4471 return f"{condition}{insert}" 4472 4473 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4474 kind = self.sql(expression, "kind") 4475 expressions = self.seg(self.expressions(expression, sep=" ")) 4476 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4477 return res 4478 4479 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4480 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4481 empty = expression.args.get("empty") 4482 empty = ( 4483 f"DEFAULT {empty} ON EMPTY" 4484 if isinstance(empty, exp.Expression) 4485 else self.sql(expression, "empty") 4486 ) 4487 4488 error = expression.args.get("error") 4489 error = ( 4490 f"DEFAULT {error} ON ERROR" 4491 if isinstance(error, exp.Expression) 4492 else self.sql(expression, "error") 4493 ) 4494 4495 if error and empty: 4496 error = ( 4497 f"{empty} {error}" 4498 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4499 else f"{error} {empty}" 4500 ) 4501 empty = "" 4502 4503 null = self.sql(expression, "null") 4504 4505 return f"{empty}{error}{null}" 4506 4507 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4508 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4509 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4510 4511 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4512 this = self.sql(expression, "this") 4513 path = self.sql(expression, "path") 4514 4515 passing = self.expressions(expression, "passing") 4516 passing = f" PASSING {passing}" if passing else "" 4517 4518 on_condition = self.sql(expression, "on_condition") 4519 on_condition = f" {on_condition}" if on_condition else "" 4520 4521 path = f"{path}{passing}{on_condition}" 4522 4523 return self.func("JSON_EXISTS", this, path) 4524 4525 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4526 array_agg = self.function_fallback_sql(expression) 4527 4528 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4529 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4530 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4531 parent = expression.parent 4532 if isinstance(parent, exp.Filter): 4533 parent_cond = parent.expression.this 4534 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4535 else: 4536 this = expression.this 4537 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4538 if this.find(exp.Column): 4539 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4540 this_sql = ( 4541 self.expressions(this) 4542 if isinstance(this, exp.Distinct) 4543 else self.sql(expression, "this") 4544 ) 4545 4546 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4547 4548 return array_agg 4549 4550 def apply_sql(self, expression: exp.Apply) -> str: 4551 this = self.sql(expression, "this") 4552 expr = self.sql(expression, "expression") 4553 4554 return f"{this} APPLY({expr})" 4555 4556 def grant_sql(self, expression: exp.Grant) -> str: 4557 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4558 4559 kind = self.sql(expression, "kind") 4560 kind = f" {kind}" if kind else "" 4561 4562 securable = self.sql(expression, "securable") 4563 securable = f" {securable}" if securable else "" 4564 4565 principals = self.expressions(expression, key="principals", flat=True) 4566 4567 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4568 4569 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4570 4571 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4572 this = self.sql(expression, "this") 4573 columns = self.expressions(expression, flat=True) 4574 columns = f"({columns})" if columns else "" 4575 4576 return f"{this}{columns}" 4577 4578 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4579 this = self.sql(expression, "this") 4580 4581 kind = self.sql(expression, "kind") 4582 kind = f"{kind} " if kind else "" 4583 4584 return f"{kind}{this}" 4585 4586 def columns_sql(self, expression: exp.Columns): 4587 func = self.function_fallback_sql(expression) 4588 if expression.args.get("unpack"): 4589 func = f"*{func}" 4590 4591 return func 4592 4593 def overlay_sql(self, expression: exp.Overlay): 4594 this = self.sql(expression, "this") 4595 expr = self.sql(expression, "expression") 4596 from_sql = self.sql(expression, "from") 4597 for_sql = self.sql(expression, "for") 4598 for_sql = f" FOR {for_sql}" if for_sql else "" 4599 4600 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4601 4602 @unsupported_args("format") 4603 def todouble_sql(self, expression: exp.ToDouble) -> str: 4604 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4605 4606 def string_sql(self, expression: exp.String) -> str: 4607 this = expression.this 4608 zone = expression.args.get("zone") 4609 4610 if zone: 4611 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4612 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4613 # set for source_tz to transpile the time conversion before the STRING cast 4614 this = exp.ConvertTimezone( 4615 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4616 ) 4617 4618 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4619 4620 def median_sql(self, expression: exp.Median): 4621 if not self.SUPPORTS_MEDIAN: 4622 return self.sql( 4623 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4624 ) 4625 4626 return self.function_fallback_sql(expression) 4627 4628 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4629 filler = self.sql(expression, "this") 4630 filler = f" {filler}" if filler else "" 4631 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4632 return f"TRUNCATE{filler} {with_count}" 4633 4634 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4635 if self.SUPPORTS_UNIX_SECONDS: 4636 return self.function_fallback_sql(expression) 4637 4638 start_ts = exp.cast( 4639 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4640 ) 4641 4642 return self.sql( 4643 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4644 ) 4645 4646 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4647 dim = expression.expression 4648 4649 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4650 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4651 if not (dim.is_int and dim.name == "1"): 4652 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4653 dim = None 4654 4655 # If dimension is required but not specified, default initialize it 4656 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4657 dim = exp.Literal.number(1) 4658 4659 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4660 4661 def attach_sql(self, expression: exp.Attach) -> str: 4662 this = self.sql(expression, "this") 4663 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4664 expressions = self.expressions(expression) 4665 expressions = f" ({expressions})" if expressions else "" 4666 4667 return f"ATTACH{exists_sql} {this}{expressions}" 4668 4669 def detach_sql(self, expression: exp.Detach) -> str: 4670 this = self.sql(expression, "this") 4671 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4672 4673 return f"DETACH{exists_sql} {this}" 4674 4675 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4676 this = self.sql(expression, "this") 4677 value = self.sql(expression, "expression") 4678 value = f" {value}" if value else "" 4679 return f"{this}{value}" 4680 4681 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4682 this_sql = self.sql(expression, "this") 4683 if isinstance(expression.this, exp.Table): 4684 this_sql = f"TABLE {this_sql}" 4685 4686 return self.func( 4687 "FEATURES_AT_TIME", 4688 this_sql, 4689 expression.args.get("time"), 4690 expression.args.get("num_rows"), 4691 expression.args.get("ignore_feature_nulls"), 4692 ) 4693 4694 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4695 return ( 4696 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4697 ) 4698 4699 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4700 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4701 encode = f"{encode} {self.sql(expression, 'this')}" 4702 4703 properties = expression.args.get("properties") 4704 if properties: 4705 encode = f"{encode} {self.properties(properties)}" 4706 4707 return encode 4708 4709 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4710 this = self.sql(expression, "this") 4711 include = f"INCLUDE {this}" 4712 4713 column_def = self.sql(expression, "column_def") 4714 if column_def: 4715 include = f"{include} {column_def}" 4716 4717 alias = self.sql(expression, "alias") 4718 if alias: 4719 include = f"{include} AS {alias}" 4720 4721 return include 4722 4723 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4724 name = f"NAME {self.sql(expression, 'this')}" 4725 return self.func("XMLELEMENT", name, *expression.expressions) 4726 4727 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4728 partitions = self.expressions(expression, "partition_expressions") 4729 create = self.expressions(expression, "create_expressions") 4730 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4731 4732 def partitionbyrangepropertydynamic_sql( 4733 self, expression: exp.PartitionByRangePropertyDynamic 4734 ) -> str: 4735 start = self.sql(expression, "start") 4736 end = self.sql(expression, "end") 4737 4738 every = expression.args["every"] 4739 if isinstance(every, exp.Interval) and every.this.is_string: 4740 every.this.replace(exp.Literal.number(every.name)) 4741 4742 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4743 4744 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4745 name = self.sql(expression, "this") 4746 values = self.expressions(expression, flat=True) 4747 4748 return f"NAME {name} VALUE {values}" 4749 4750 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4751 kind = self.sql(expression, "kind") 4752 sample = self.sql(expression, "sample") 4753 return f"SAMPLE {sample} {kind}" 4754 4755 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4756 kind = self.sql(expression, "kind") 4757 option = self.sql(expression, "option") 4758 option = f" {option}" if option else "" 4759 this = self.sql(expression, "this") 4760 this = f" {this}" if this else "" 4761 columns = self.expressions(expression) 4762 columns = f" {columns}" if columns else "" 4763 return f"{kind}{option} STATISTICS{this}{columns}" 4764 4765 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4766 this = self.sql(expression, "this") 4767 columns = self.expressions(expression) 4768 inner_expression = self.sql(expression, "expression") 4769 inner_expression = f" {inner_expression}" if inner_expression else "" 4770 update_options = self.sql(expression, "update_options") 4771 update_options = f" {update_options} UPDATE" if update_options else "" 4772 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4773 4774 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4775 kind = self.sql(expression, "kind") 4776 kind = f" {kind}" if kind else "" 4777 return f"DELETE{kind} STATISTICS" 4778 4779 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4780 inner_expression = self.sql(expression, "expression") 4781 return f"LIST CHAINED ROWS{inner_expression}" 4782 4783 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4784 kind = self.sql(expression, "kind") 4785 this = self.sql(expression, "this") 4786 this = f" {this}" if this else "" 4787 inner_expression = self.sql(expression, "expression") 4788 return f"VALIDATE {kind}{this}{inner_expression}" 4789 4790 def analyze_sql(self, expression: exp.Analyze) -> str: 4791 options = self.expressions(expression, key="options", sep=" ") 4792 options = f" {options}" if options else "" 4793 kind = self.sql(expression, "kind") 4794 kind = f" {kind}" if kind else "" 4795 this = self.sql(expression, "this") 4796 this = f" {this}" if this else "" 4797 mode = self.sql(expression, "mode") 4798 mode = f" {mode}" if mode else "" 4799 properties = self.sql(expression, "properties") 4800 properties = f" {properties}" if properties else "" 4801 partition = self.sql(expression, "partition") 4802 partition = f" {partition}" if partition else "" 4803 inner_expression = self.sql(expression, "expression") 4804 inner_expression = f" {inner_expression}" if inner_expression else "" 4805 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4806 4807 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4808 this = self.sql(expression, "this") 4809 namespaces = self.expressions(expression, key="namespaces") 4810 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4811 passing = self.expressions(expression, key="passing") 4812 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4813 columns = self.expressions(expression, key="columns") 4814 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4815 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4816 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4817 4818 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4819 this = self.sql(expression, "this") 4820 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4821 4822 def export_sql(self, expression: exp.Export) -> str: 4823 this = self.sql(expression, "this") 4824 connection = self.sql(expression, "connection") 4825 connection = f"WITH CONNECTION {connection} " if connection else "" 4826 options = self.sql(expression, "options") 4827 return f"EXPORT DATA {connection}{options} AS {this}" 4828 4829 def declare_sql(self, expression: exp.Declare) -> str: 4830 return f"DECLARE {self.expressions(expression, flat=True)}" 4831 4832 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4833 variable = self.sql(expression, "this") 4834 default = self.sql(expression, "default") 4835 default = f" = {default}" if default else "" 4836 4837 kind = self.sql(expression, "kind") 4838 if isinstance(expression.args.get("kind"), exp.Schema): 4839 kind = f"TABLE {kind}" 4840 4841 return f"{variable} AS {kind}{default}" 4842 4843 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4844 kind = self.sql(expression, "kind") 4845 this = self.sql(expression, "this") 4846 set = self.sql(expression, "expression") 4847 using = self.sql(expression, "using") 4848 using = f" USING {using}" if using else "" 4849 4850 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4851 4852 return f"{kind_sql} {this} SET {set}{using}" 4853 4854 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4855 params = self.expressions(expression, key="params", flat=True) 4856 return self.func(expression.name, *expression.expressions) + f"({params})" 4857 4858 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4859 return self.func(expression.name, *expression.expressions) 4860 4861 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4862 return self.anonymousaggfunc_sql(expression) 4863 4864 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4865 return self.parameterizedagg_sql(expression) 4866 4867 def show_sql(self, expression: exp.Show) -> str: 4868 self.unsupported("Unsupported SHOW statement") 4869 return "" 4870 4871 def put_sql(self, expression: exp.Put) -> str: 4872 props = expression.args.get("properties") 4873 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4874 this = self.sql(expression, "this") 4875 target = self.sql(expression, "target") 4876 return f"PUT {this} {target}{props_sql}"
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.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 196 exp.TemporaryProperty: lambda *_: "TEMPORARY", 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.UsingTemplateProperty: lambda self, e: f"USING TEMPLATE {self.sql(e, 'this')}", 205 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 206 exp.Uuid: lambda *_: "UUID()", 207 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 208 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 209 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 210 exp.VolatileProperty: lambda *_: "VOLATILE", 211 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 212 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 213 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 214 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 215 exp.ForceProperty: lambda *_: "FORCE", 216 } 217 218 # Whether null ordering is supported in order by 219 # True: Full Support, None: No support, False: No support for certain cases 220 # such as window specifications, aggregate functions etc 221 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 222 223 # Whether ignore nulls is inside the agg or outside. 224 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 225 IGNORE_NULLS_IN_FUNC = False 226 227 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 228 LOCKING_READS_SUPPORTED = False 229 230 # Whether the EXCEPT and INTERSECT operations can return duplicates 231 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 232 233 # Wrap derived values in parens, usually standard but spark doesn't support it 234 WRAP_DERIVED_VALUES = True 235 236 # Whether create function uses an AS before the RETURN 237 CREATE_FUNCTION_RETURN_AS = True 238 239 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 240 MATCHED_BY_SOURCE = True 241 242 # Whether the INTERVAL expression works only with values like '1 day' 243 SINGLE_STRING_INTERVAL = False 244 245 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 246 INTERVAL_ALLOWS_PLURAL_FORM = True 247 248 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 249 LIMIT_FETCH = "ALL" 250 251 # Whether limit and fetch allows expresions or just limits 252 LIMIT_ONLY_LITERALS = False 253 254 # Whether a table is allowed to be renamed with a db 255 RENAME_TABLE_WITH_DB = True 256 257 # The separator for grouping sets and rollups 258 GROUPINGS_SEP = "," 259 260 # The string used for creating an index on a table 261 INDEX_ON = "ON" 262 263 # Whether join hints should be generated 264 JOIN_HINTS = True 265 266 # Whether table hints should be generated 267 TABLE_HINTS = True 268 269 # Whether query hints should be generated 270 QUERY_HINTS = True 271 272 # What kind of separator to use for query hints 273 QUERY_HINT_SEP = ", " 274 275 # Whether comparing against booleans (e.g. x IS TRUE) is supported 276 IS_BOOL_ALLOWED = True 277 278 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 279 DUPLICATE_KEY_UPDATE_WITH_SET = True 280 281 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 282 LIMIT_IS_TOP = False 283 284 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 285 RETURNING_END = True 286 287 # Whether to generate an unquoted value for EXTRACT's date part argument 288 EXTRACT_ALLOWS_QUOTES = True 289 290 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 291 TZ_TO_WITH_TIME_ZONE = False 292 293 # Whether the NVL2 function is supported 294 NVL2_SUPPORTED = True 295 296 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 297 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 298 299 # Whether VALUES statements can be used as derived tables. 300 # MySQL 5 and Redshift do not allow this, so when False, it will convert 301 # SELECT * VALUES into SELECT UNION 302 VALUES_AS_TABLE = True 303 304 # Whether the word COLUMN is included when adding a column with ALTER TABLE 305 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 306 307 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 308 UNNEST_WITH_ORDINALITY = True 309 310 # Whether FILTER (WHERE cond) can be used for conditional aggregation 311 AGGREGATE_FILTER_SUPPORTED = True 312 313 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 314 SEMI_ANTI_JOIN_WITH_SIDE = True 315 316 # Whether to include the type of a computed column in the CREATE DDL 317 COMPUTED_COLUMN_WITH_TYPE = True 318 319 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 320 SUPPORTS_TABLE_COPY = True 321 322 # Whether parentheses are required around the table sample's expression 323 TABLESAMPLE_REQUIRES_PARENS = True 324 325 # Whether a table sample clause's size needs to be followed by the ROWS keyword 326 TABLESAMPLE_SIZE_IS_ROWS = True 327 328 # The keyword(s) to use when generating a sample clause 329 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 330 331 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 332 TABLESAMPLE_WITH_METHOD = True 333 334 # The keyword to use when specifying the seed of a sample clause 335 TABLESAMPLE_SEED_KEYWORD = "SEED" 336 337 # Whether COLLATE is a function instead of a binary operator 338 COLLATE_IS_FUNC = False 339 340 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 341 DATA_TYPE_SPECIFIERS_ALLOWED = False 342 343 # Whether conditions require booleans WHERE x = 0 vs WHERE x 344 ENSURE_BOOLS = False 345 346 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 347 CTE_RECURSIVE_KEYWORD_REQUIRED = True 348 349 # Whether CONCAT requires >1 arguments 350 SUPPORTS_SINGLE_ARG_CONCAT = True 351 352 # Whether LAST_DAY function supports a date part argument 353 LAST_DAY_SUPPORTS_DATE_PART = True 354 355 # Whether named columns are allowed in table aliases 356 SUPPORTS_TABLE_ALIAS_COLUMNS = True 357 358 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 359 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 360 361 # What delimiter to use for separating JSON key/value pairs 362 JSON_KEY_VALUE_PAIR_SEP = ":" 363 364 # INSERT OVERWRITE TABLE x override 365 INSERT_OVERWRITE = " OVERWRITE TABLE" 366 367 # Whether the SELECT .. INTO syntax is used instead of CTAS 368 SUPPORTS_SELECT_INTO = False 369 370 # Whether UNLOGGED tables can be created 371 SUPPORTS_UNLOGGED_TABLES = False 372 373 # Whether the CREATE TABLE LIKE statement is supported 374 SUPPORTS_CREATE_TABLE_LIKE = True 375 376 # Whether the LikeProperty needs to be specified inside of the schema clause 377 LIKE_PROPERTY_INSIDE_SCHEMA = False 378 379 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 380 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 381 MULTI_ARG_DISTINCT = True 382 383 # Whether the JSON extraction operators expect a value of type JSON 384 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 385 386 # Whether bracketed keys like ["foo"] are supported in JSON paths 387 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 388 389 # Whether to escape keys using single quotes in JSON paths 390 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 391 392 # The JSONPathPart expressions supported by this dialect 393 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 394 395 # Whether any(f(x) for x in array) can be implemented by this dialect 396 CAN_IMPLEMENT_ARRAY_ANY = False 397 398 # Whether the function TO_NUMBER is supported 399 SUPPORTS_TO_NUMBER = True 400 401 # Whether or not set op modifiers apply to the outer set op or select. 402 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 403 # True means limit 1 happens after the set op, False means it it happens on y. 404 SET_OP_MODIFIERS = True 405 406 # Whether parameters from COPY statement are wrapped in parentheses 407 COPY_PARAMS_ARE_WRAPPED = True 408 409 # Whether values of params are set with "=" token or empty space 410 COPY_PARAMS_EQ_REQUIRED = False 411 412 # Whether COPY statement has INTO keyword 413 COPY_HAS_INTO_KEYWORD = True 414 415 # Whether the conditional TRY(expression) function is supported 416 TRY_SUPPORTED = True 417 418 # Whether the UESCAPE syntax in unicode strings is supported 419 SUPPORTS_UESCAPE = True 420 421 # The keyword to use when generating a star projection with excluded columns 422 STAR_EXCEPT = "EXCEPT" 423 424 # The HEX function name 425 HEX_FUNC = "HEX" 426 427 # The keywords to use when prefixing & separating WITH based properties 428 WITH_PROPERTIES_PREFIX = "WITH" 429 430 # Whether to quote the generated expression of exp.JsonPath 431 QUOTE_JSON_PATH = True 432 433 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 434 PAD_FILL_PATTERN_IS_REQUIRED = False 435 436 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 437 SUPPORTS_EXPLODING_PROJECTIONS = True 438 439 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 440 ARRAY_CONCAT_IS_VAR_LEN = True 441 442 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 443 SUPPORTS_CONVERT_TIMEZONE = False 444 445 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 446 SUPPORTS_MEDIAN = True 447 448 # Whether UNIX_SECONDS(timestamp) is supported 449 SUPPORTS_UNIX_SECONDS = False 450 451 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 452 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 453 454 # The function name of the exp.ArraySize expression 455 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 456 457 # The syntax to use when altering the type of a column 458 ALTER_SET_TYPE = "SET DATA TYPE" 459 460 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 461 # None -> Doesn't support it at all 462 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 463 # True (Postgres) -> Explicitly requires it 464 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 465 466 TYPE_MAPPING = { 467 exp.DataType.Type.DATETIME2: "TIMESTAMP", 468 exp.DataType.Type.NCHAR: "CHAR", 469 exp.DataType.Type.NVARCHAR: "VARCHAR", 470 exp.DataType.Type.MEDIUMTEXT: "TEXT", 471 exp.DataType.Type.LONGTEXT: "TEXT", 472 exp.DataType.Type.TINYTEXT: "TEXT", 473 exp.DataType.Type.BLOB: "VARBINARY", 474 exp.DataType.Type.MEDIUMBLOB: "BLOB", 475 exp.DataType.Type.LONGBLOB: "BLOB", 476 exp.DataType.Type.TINYBLOB: "BLOB", 477 exp.DataType.Type.INET: "INET", 478 exp.DataType.Type.ROWVERSION: "VARBINARY", 479 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 480 } 481 482 TIME_PART_SINGULARS = { 483 "MICROSECONDS": "MICROSECOND", 484 "SECONDS": "SECOND", 485 "MINUTES": "MINUTE", 486 "HOURS": "HOUR", 487 "DAYS": "DAY", 488 "WEEKS": "WEEK", 489 "MONTHS": "MONTH", 490 "QUARTERS": "QUARTER", 491 "YEARS": "YEAR", 492 } 493 494 AFTER_HAVING_MODIFIER_TRANSFORMS = { 495 "cluster": lambda self, e: self.sql(e, "cluster"), 496 "distribute": lambda self, e: self.sql(e, "distribute"), 497 "sort": lambda self, e: self.sql(e, "sort"), 498 "windows": lambda self, e: ( 499 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 500 if e.args.get("windows") 501 else "" 502 ), 503 "qualify": lambda self, e: self.sql(e, "qualify"), 504 } 505 506 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 507 508 STRUCT_DELIMITER = ("<", ">") 509 510 PARAMETER_TOKEN = "@" 511 NAMED_PLACEHOLDER_TOKEN = ":" 512 513 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 514 515 PROPERTIES_LOCATION = { 516 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 518 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 520 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 522 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 524 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 527 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 529 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 530 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 531 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 532 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 533 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 534 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 536 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 538 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 540 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 541 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 542 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 543 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 544 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 545 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 546 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 547 exp.HeapProperty: exp.Properties.Location.POST_WITH, 548 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 550 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 553 exp.JournalProperty: exp.Properties.Location.POST_NAME, 554 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 558 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 559 exp.LogProperty: exp.Properties.Location.POST_NAME, 560 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 561 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 562 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 563 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 564 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 565 exp.Order: exp.Properties.Location.POST_SCHEMA, 566 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 568 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 570 exp.Property: exp.Properties.Location.POST_WITH, 571 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 577 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 578 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 579 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 580 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 581 exp.Set: exp.Properties.Location.POST_SCHEMA, 582 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 583 exp.SetProperty: exp.Properties.Location.POST_CREATE, 584 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 585 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 586 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 587 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 588 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 590 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 593 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 594 exp.Tags: exp.Properties.Location.POST_WITH, 595 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 596 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 597 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 598 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 599 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 600 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 601 exp.UsingTemplateProperty: exp.Properties.Location.POST_SCHEMA, 602 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 603 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 604 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 605 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 606 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 607 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 608 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 609 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 610 } 611 612 # Keywords that can't be used as unquoted identifier names 613 RESERVED_KEYWORDS: t.Set[str] = set() 614 615 # Expressions whose comments are separated from them for better formatting 616 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 617 exp.Command, 618 exp.Create, 619 exp.Describe, 620 exp.Delete, 621 exp.Drop, 622 exp.From, 623 exp.Insert, 624 exp.Join, 625 exp.MultitableInserts, 626 exp.Select, 627 exp.SetOperation, 628 exp.Update, 629 exp.Where, 630 exp.With, 631 ) 632 633 # Expressions that should not have their comments generated in maybe_comment 634 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 635 exp.Binary, 636 exp.SetOperation, 637 ) 638 639 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 640 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 641 exp.Column, 642 exp.Literal, 643 exp.Neg, 644 exp.Paren, 645 ) 646 647 PARAMETERIZABLE_TEXT_TYPES = { 648 exp.DataType.Type.NVARCHAR, 649 exp.DataType.Type.VARCHAR, 650 exp.DataType.Type.CHAR, 651 exp.DataType.Type.NCHAR, 652 } 653 654 # Expressions that need to have all CTEs under them bubbled up to them 655 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 656 657 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 658 659 __slots__ = ( 660 "pretty", 661 "identify", 662 "normalize", 663 "pad", 664 "_indent", 665 "normalize_functions", 666 "unsupported_level", 667 "max_unsupported", 668 "leading_comma", 669 "max_text_width", 670 "comments", 671 "dialect", 672 "unsupported_messages", 673 "_escaped_quote_end", 674 "_escaped_identifier_end", 675 "_next_name", 676 "_identifier_start", 677 "_identifier_end", 678 "_quote_json_path_key_using_brackets", 679 ) 680 681 def __init__( 682 self, 683 pretty: t.Optional[bool] = None, 684 identify: str | bool = False, 685 normalize: bool = False, 686 pad: int = 2, 687 indent: int = 2, 688 normalize_functions: t.Optional[str | bool] = None, 689 unsupported_level: ErrorLevel = ErrorLevel.WARN, 690 max_unsupported: int = 3, 691 leading_comma: bool = False, 692 max_text_width: int = 80, 693 comments: bool = True, 694 dialect: DialectType = None, 695 ): 696 import sqlglot 697 from sqlglot.dialects import Dialect 698 699 self.pretty = pretty if pretty is not None else sqlglot.pretty 700 self.identify = identify 701 self.normalize = normalize 702 self.pad = pad 703 self._indent = indent 704 self.unsupported_level = unsupported_level 705 self.max_unsupported = max_unsupported 706 self.leading_comma = leading_comma 707 self.max_text_width = max_text_width 708 self.comments = comments 709 self.dialect = Dialect.get_or_raise(dialect) 710 711 # This is both a Dialect property and a Generator argument, so we prioritize the latter 712 self.normalize_functions = ( 713 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 714 ) 715 716 self.unsupported_messages: t.List[str] = [] 717 self._escaped_quote_end: str = ( 718 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 719 ) 720 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 721 722 self._next_name = name_sequence("_t") 723 724 self._identifier_start = self.dialect.IDENTIFIER_START 725 self._identifier_end = self.dialect.IDENTIFIER_END 726 727 self._quote_json_path_key_using_brackets = True 728 729 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 730 """ 731 Generates the SQL string corresponding to the given syntax tree. 732 733 Args: 734 expression: The syntax tree. 735 copy: Whether to copy the expression. The generator performs mutations so 736 it is safer to copy. 737 738 Returns: 739 The SQL string corresponding to `expression`. 740 """ 741 if copy: 742 expression = expression.copy() 743 744 expression = self.preprocess(expression) 745 746 self.unsupported_messages = [] 747 sql = self.sql(expression).strip() 748 749 if self.pretty: 750 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 751 752 if self.unsupported_level == ErrorLevel.IGNORE: 753 return sql 754 755 if self.unsupported_level == ErrorLevel.WARN: 756 for msg in self.unsupported_messages: 757 logger.warning(msg) 758 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 759 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 760 761 return sql 762 763 def preprocess(self, expression: exp.Expression) -> exp.Expression: 764 """Apply generic preprocessing transformations to a given expression.""" 765 expression = self._move_ctes_to_top_level(expression) 766 767 if self.ENSURE_BOOLS: 768 from sqlglot.transforms import ensure_bools 769 770 expression = ensure_bools(expression) 771 772 return expression 773 774 def _move_ctes_to_top_level(self, expression: E) -> E: 775 if ( 776 not expression.parent 777 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 778 and any(node.parent is not expression for node in expression.find_all(exp.With)) 779 ): 780 from sqlglot.transforms import move_ctes_to_top_level 781 782 expression = move_ctes_to_top_level(expression) 783 return expression 784 785 def unsupported(self, message: str) -> None: 786 if self.unsupported_level == ErrorLevel.IMMEDIATE: 787 raise UnsupportedError(message) 788 self.unsupported_messages.append(message) 789 790 def sep(self, sep: str = " ") -> str: 791 return f"{sep.strip()}\n" if self.pretty else sep 792 793 def seg(self, sql: str, sep: str = " ") -> str: 794 return f"{self.sep(sep)}{sql}" 795 796 def pad_comment(self, comment: str) -> str: 797 comment = " " + comment if comment[0].strip() else comment 798 comment = comment + " " if comment[-1].strip() else comment 799 return comment 800 801 def maybe_comment( 802 self, 803 sql: str, 804 expression: t.Optional[exp.Expression] = None, 805 comments: t.Optional[t.List[str]] = None, 806 separated: bool = False, 807 ) -> str: 808 comments = ( 809 ((expression and expression.comments) if comments is None else comments) # type: ignore 810 if self.comments 811 else None 812 ) 813 814 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 815 return sql 816 817 comments_sql = " ".join( 818 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 819 ) 820 821 if not comments_sql: 822 return sql 823 824 comments_sql = self._replace_line_breaks(comments_sql) 825 826 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 827 return ( 828 f"{self.sep()}{comments_sql}{sql}" 829 if not sql or sql[0].isspace() 830 else f"{comments_sql}{self.sep()}{sql}" 831 ) 832 833 return f"{sql} {comments_sql}" 834 835 def wrap(self, expression: exp.Expression | str) -> str: 836 this_sql = ( 837 self.sql(expression) 838 if isinstance(expression, exp.UNWRAPPED_QUERIES) 839 else self.sql(expression, "this") 840 ) 841 if not this_sql: 842 return "()" 843 844 this_sql = self.indent(this_sql, level=1, pad=0) 845 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 846 847 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 848 original = self.identify 849 self.identify = False 850 result = func(*args, **kwargs) 851 self.identify = original 852 return result 853 854 def normalize_func(self, name: str) -> str: 855 if self.normalize_functions == "upper" or self.normalize_functions is True: 856 return name.upper() 857 if self.normalize_functions == "lower": 858 return name.lower() 859 return name 860 861 def indent( 862 self, 863 sql: str, 864 level: int = 0, 865 pad: t.Optional[int] = None, 866 skip_first: bool = False, 867 skip_last: bool = False, 868 ) -> str: 869 if not self.pretty or not sql: 870 return sql 871 872 pad = self.pad if pad is None else pad 873 lines = sql.split("\n") 874 875 return "\n".join( 876 ( 877 line 878 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 879 else f"{' ' * (level * self._indent + pad)}{line}" 880 ) 881 for i, line in enumerate(lines) 882 ) 883 884 def sql( 885 self, 886 expression: t.Optional[str | exp.Expression], 887 key: t.Optional[str] = None, 888 comment: bool = True, 889 ) -> str: 890 if not expression: 891 return "" 892 893 if isinstance(expression, str): 894 return expression 895 896 if key: 897 value = expression.args.get(key) 898 if value: 899 return self.sql(value) 900 return "" 901 902 transform = self.TRANSFORMS.get(expression.__class__) 903 904 if callable(transform): 905 sql = transform(self, expression) 906 elif isinstance(expression, exp.Expression): 907 exp_handler_name = f"{expression.key}_sql" 908 909 if hasattr(self, exp_handler_name): 910 sql = getattr(self, exp_handler_name)(expression) 911 elif isinstance(expression, exp.Func): 912 sql = self.function_fallback_sql(expression) 913 elif isinstance(expression, exp.Property): 914 sql = self.property_sql(expression) 915 else: 916 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 917 else: 918 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 919 920 return self.maybe_comment(sql, expression) if self.comments and comment else sql 921 922 def uncache_sql(self, expression: exp.Uncache) -> str: 923 table = self.sql(expression, "this") 924 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 925 return f"UNCACHE TABLE{exists_sql} {table}" 926 927 def cache_sql(self, expression: exp.Cache) -> str: 928 lazy = " LAZY" if expression.args.get("lazy") else "" 929 table = self.sql(expression, "this") 930 options = expression.args.get("options") 931 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 932 sql = self.sql(expression, "expression") 933 sql = f" AS{self.sep()}{sql}" if sql else "" 934 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 935 return self.prepend_ctes(expression, sql) 936 937 def characterset_sql(self, expression: exp.CharacterSet) -> str: 938 if isinstance(expression.parent, exp.Cast): 939 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 940 default = "DEFAULT " if expression.args.get("default") else "" 941 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 942 943 def column_parts(self, expression: exp.Column) -> str: 944 return ".".join( 945 self.sql(part) 946 for part in ( 947 expression.args.get("catalog"), 948 expression.args.get("db"), 949 expression.args.get("table"), 950 expression.args.get("this"), 951 ) 952 if part 953 ) 954 955 def column_sql(self, expression: exp.Column) -> str: 956 join_mark = " (+)" if expression.args.get("join_mark") else "" 957 958 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 959 join_mark = "" 960 self.unsupported("Outer join syntax using the (+) operator is not supported.") 961 962 return f"{self.column_parts(expression)}{join_mark}" 963 964 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 965 this = self.sql(expression, "this") 966 this = f" {this}" if this else "" 967 position = self.sql(expression, "position") 968 return f"{position}{this}" 969 970 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 971 column = self.sql(expression, "this") 972 kind = self.sql(expression, "kind") 973 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 974 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 975 kind = f"{sep}{kind}" if kind else "" 976 constraints = f" {constraints}" if constraints else "" 977 position = self.sql(expression, "position") 978 position = f" {position}" if position else "" 979 980 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 981 kind = "" 982 983 return f"{exists}{column}{kind}{constraints}{position}" 984 985 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 986 this = self.sql(expression, "this") 987 kind_sql = self.sql(expression, "kind").strip() 988 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 989 990 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 991 this = self.sql(expression, "this") 992 if expression.args.get("not_null"): 993 persisted = " PERSISTED NOT NULL" 994 elif expression.args.get("persisted"): 995 persisted = " PERSISTED" 996 else: 997 persisted = "" 998 return f"AS {this}{persisted}" 999 1000 def autoincrementcolumnconstraint_sql(self, _) -> str: 1001 return self.token_sql(TokenType.AUTO_INCREMENT) 1002 1003 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1004 if isinstance(expression.this, list): 1005 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1006 else: 1007 this = self.sql(expression, "this") 1008 1009 return f"COMPRESS {this}" 1010 1011 def generatedasidentitycolumnconstraint_sql( 1012 self, expression: exp.GeneratedAsIdentityColumnConstraint 1013 ) -> str: 1014 this = "" 1015 if expression.this is not None: 1016 on_null = " ON NULL" if expression.args.get("on_null") else "" 1017 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1018 1019 start = expression.args.get("start") 1020 start = f"START WITH {start}" if start else "" 1021 increment = expression.args.get("increment") 1022 increment = f" INCREMENT BY {increment}" if increment else "" 1023 minvalue = expression.args.get("minvalue") 1024 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1025 maxvalue = expression.args.get("maxvalue") 1026 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1027 cycle = expression.args.get("cycle") 1028 cycle_sql = "" 1029 1030 if cycle is not None: 1031 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1032 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1033 1034 sequence_opts = "" 1035 if start or increment or cycle_sql: 1036 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1037 sequence_opts = f" ({sequence_opts.strip()})" 1038 1039 expr = self.sql(expression, "expression") 1040 expr = f"({expr})" if expr else "IDENTITY" 1041 1042 return f"GENERATED{this} AS {expr}{sequence_opts}" 1043 1044 def generatedasrowcolumnconstraint_sql( 1045 self, expression: exp.GeneratedAsRowColumnConstraint 1046 ) -> str: 1047 start = "START" if expression.args.get("start") else "END" 1048 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1049 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1050 1051 def periodforsystemtimeconstraint_sql( 1052 self, expression: exp.PeriodForSystemTimeConstraint 1053 ) -> str: 1054 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1055 1056 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1057 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1058 1059 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1060 return f"AS {self.sql(expression, 'this')}" 1061 1062 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1063 desc = expression.args.get("desc") 1064 if desc is not None: 1065 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1066 return "PRIMARY KEY" 1067 1068 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1069 this = self.sql(expression, "this") 1070 this = f" {this}" if this else "" 1071 index_type = expression.args.get("index_type") 1072 index_type = f" USING {index_type}" if index_type else "" 1073 on_conflict = self.sql(expression, "on_conflict") 1074 on_conflict = f" {on_conflict}" if on_conflict else "" 1075 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1076 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1077 1078 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1079 return self.sql(expression, "this") 1080 1081 def create_sql(self, expression: exp.Create) -> str: 1082 kind = self.sql(expression, "kind") 1083 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1084 properties = expression.args.get("properties") 1085 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1086 1087 this = self.createable_sql(expression, properties_locs) 1088 1089 properties_sql = "" 1090 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1091 exp.Properties.Location.POST_WITH 1092 ): 1093 properties_sql = self.sql( 1094 exp.Properties( 1095 expressions=[ 1096 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1097 *properties_locs[exp.Properties.Location.POST_WITH], 1098 ] 1099 ) 1100 ) 1101 1102 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1103 properties_sql = self.sep() + properties_sql 1104 elif not self.pretty: 1105 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1106 properties_sql = f" {properties_sql}" 1107 1108 begin = " BEGIN" if expression.args.get("begin") else "" 1109 end = " END" if expression.args.get("end") else "" 1110 1111 expression_sql = self.sql(expression, "expression") 1112 if expression_sql: 1113 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1114 1115 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1116 postalias_props_sql = "" 1117 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1118 postalias_props_sql = self.properties( 1119 exp.Properties( 1120 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1121 ), 1122 wrapped=False, 1123 ) 1124 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1125 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1126 1127 postindex_props_sql = "" 1128 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1129 postindex_props_sql = self.properties( 1130 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1131 wrapped=False, 1132 prefix=" ", 1133 ) 1134 1135 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1136 indexes = f" {indexes}" if indexes else "" 1137 index_sql = indexes + postindex_props_sql 1138 1139 replace = " OR REPLACE" if expression.args.get("replace") else "" 1140 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1141 unique = " UNIQUE" if expression.args.get("unique") else "" 1142 1143 clustered = expression.args.get("clustered") 1144 if clustered is None: 1145 clustered_sql = "" 1146 elif clustered: 1147 clustered_sql = " CLUSTERED COLUMNSTORE" 1148 else: 1149 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1150 1151 postcreate_props_sql = "" 1152 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1153 postcreate_props_sql = self.properties( 1154 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1155 sep=" ", 1156 prefix=" ", 1157 wrapped=False, 1158 ) 1159 1160 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1161 1162 postexpression_props_sql = "" 1163 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1164 postexpression_props_sql = self.properties( 1165 exp.Properties( 1166 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1167 ), 1168 sep=" ", 1169 prefix=" ", 1170 wrapped=False, 1171 ) 1172 1173 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1174 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1175 no_schema_binding = ( 1176 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1177 ) 1178 1179 clone = self.sql(expression, "clone") 1180 clone = f" {clone}" if clone else "" 1181 1182 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1183 properties_expression = f"{expression_sql}{properties_sql}" 1184 else: 1185 properties_expression = f"{properties_sql}{expression_sql}" 1186 1187 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1188 return self.prepend_ctes(expression, expression_sql) 1189 1190 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1191 start = self.sql(expression, "start") 1192 start = f"START WITH {start}" if start else "" 1193 increment = self.sql(expression, "increment") 1194 increment = f" INCREMENT BY {increment}" if increment else "" 1195 minvalue = self.sql(expression, "minvalue") 1196 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1197 maxvalue = self.sql(expression, "maxvalue") 1198 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1199 owned = self.sql(expression, "owned") 1200 owned = f" OWNED BY {owned}" if owned else "" 1201 1202 cache = expression.args.get("cache") 1203 if cache is None: 1204 cache_str = "" 1205 elif cache is True: 1206 cache_str = " CACHE" 1207 else: 1208 cache_str = f" CACHE {cache}" 1209 1210 options = self.expressions(expression, key="options", flat=True, sep=" ") 1211 options = f" {options}" if options else "" 1212 1213 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1214 1215 def clone_sql(self, expression: exp.Clone) -> str: 1216 this = self.sql(expression, "this") 1217 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1218 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1219 return f"{shallow}{keyword} {this}" 1220 1221 def describe_sql(self, expression: exp.Describe) -> str: 1222 style = expression.args.get("style") 1223 style = f" {style}" if style else "" 1224 partition = self.sql(expression, "partition") 1225 partition = f" {partition}" if partition else "" 1226 format = self.sql(expression, "format") 1227 format = f" {format}" if format else "" 1228 1229 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1230 1231 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1232 tag = self.sql(expression, "tag") 1233 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1234 1235 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1236 with_ = self.sql(expression, "with") 1237 if with_: 1238 sql = f"{with_}{self.sep()}{sql}" 1239 return sql 1240 1241 def with_sql(self, expression: exp.With) -> str: 1242 sql = self.expressions(expression, flat=True) 1243 recursive = ( 1244 "RECURSIVE " 1245 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1246 else "" 1247 ) 1248 search = self.sql(expression, "search") 1249 search = f" {search}" if search else "" 1250 1251 return f"WITH {recursive}{sql}{search}" 1252 1253 def cte_sql(self, expression: exp.CTE) -> str: 1254 alias = expression.args.get("alias") 1255 if alias: 1256 alias.add_comments(expression.pop_comments()) 1257 1258 alias_sql = self.sql(expression, "alias") 1259 1260 materialized = expression.args.get("materialized") 1261 if materialized is False: 1262 materialized = "NOT MATERIALIZED " 1263 elif materialized: 1264 materialized = "MATERIALIZED " 1265 1266 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1267 1268 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1269 alias = self.sql(expression, "this") 1270 columns = self.expressions(expression, key="columns", flat=True) 1271 columns = f"({columns})" if columns else "" 1272 1273 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1274 columns = "" 1275 self.unsupported("Named columns are not supported in table alias.") 1276 1277 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1278 alias = self._next_name() 1279 1280 return f"{alias}{columns}" 1281 1282 def bitstring_sql(self, expression: exp.BitString) -> str: 1283 this = self.sql(expression, "this") 1284 if self.dialect.BIT_START: 1285 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1286 return f"{int(this, 2)}" 1287 1288 def hexstring_sql( 1289 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1290 ) -> str: 1291 this = self.sql(expression, "this") 1292 is_integer_type = expression.args.get("is_integer") 1293 1294 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1295 not self.dialect.HEX_START and not binary_function_repr 1296 ): 1297 # Integer representation will be returned if: 1298 # - The read dialect treats the hex value as integer literal but not the write 1299 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1300 return f"{int(this, 16)}" 1301 1302 if not is_integer_type: 1303 # Read dialect treats the hex value as BINARY/BLOB 1304 if binary_function_repr: 1305 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1306 return self.func(binary_function_repr, exp.Literal.string(this)) 1307 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1308 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1309 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1310 1311 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1312 1313 def bytestring_sql(self, expression: exp.ByteString) -> str: 1314 this = self.sql(expression, "this") 1315 if self.dialect.BYTE_START: 1316 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1317 return this 1318 1319 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1320 this = self.sql(expression, "this") 1321 escape = expression.args.get("escape") 1322 1323 if self.dialect.UNICODE_START: 1324 escape_substitute = r"\\\1" 1325 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1326 else: 1327 escape_substitute = r"\\u\1" 1328 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1329 1330 if escape: 1331 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1332 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1333 else: 1334 escape_pattern = ESCAPED_UNICODE_RE 1335 escape_sql = "" 1336 1337 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1338 this = escape_pattern.sub(escape_substitute, this) 1339 1340 return f"{left_quote}{this}{right_quote}{escape_sql}" 1341 1342 def rawstring_sql(self, expression: exp.RawString) -> str: 1343 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1344 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1345 1346 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1347 this = self.sql(expression, "this") 1348 specifier = self.sql(expression, "expression") 1349 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1350 return f"{this}{specifier}" 1351 1352 def datatype_sql(self, expression: exp.DataType) -> str: 1353 nested = "" 1354 values = "" 1355 interior = self.expressions(expression, flat=True) 1356 1357 type_value = expression.this 1358 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1359 type_sql = self.sql(expression, "kind") 1360 else: 1361 type_sql = ( 1362 self.TYPE_MAPPING.get(type_value, type_value.value) 1363 if isinstance(type_value, exp.DataType.Type) 1364 else type_value 1365 ) 1366 1367 if interior: 1368 if expression.args.get("nested"): 1369 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1370 if expression.args.get("values") is not None: 1371 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1372 values = self.expressions(expression, key="values", flat=True) 1373 values = f"{delimiters[0]}{values}{delimiters[1]}" 1374 elif type_value == exp.DataType.Type.INTERVAL: 1375 nested = f" {interior}" 1376 else: 1377 nested = f"({interior})" 1378 1379 type_sql = f"{type_sql}{nested}{values}" 1380 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1381 exp.DataType.Type.TIMETZ, 1382 exp.DataType.Type.TIMESTAMPTZ, 1383 ): 1384 type_sql = f"{type_sql} WITH TIME ZONE" 1385 1386 return type_sql 1387 1388 def directory_sql(self, expression: exp.Directory) -> str: 1389 local = "LOCAL " if expression.args.get("local") else "" 1390 row_format = self.sql(expression, "row_format") 1391 row_format = f" {row_format}" if row_format else "" 1392 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1393 1394 def delete_sql(self, expression: exp.Delete) -> str: 1395 this = self.sql(expression, "this") 1396 this = f" FROM {this}" if this else "" 1397 using = self.sql(expression, "using") 1398 using = f" USING {using}" if using else "" 1399 cluster = self.sql(expression, "cluster") 1400 cluster = f" {cluster}" if cluster else "" 1401 where = self.sql(expression, "where") 1402 returning = self.sql(expression, "returning") 1403 limit = self.sql(expression, "limit") 1404 tables = self.expressions(expression, key="tables") 1405 tables = f" {tables}" if tables else "" 1406 if self.RETURNING_END: 1407 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1408 else: 1409 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1410 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1411 1412 def drop_sql(self, expression: exp.Drop) -> str: 1413 this = self.sql(expression, "this") 1414 expressions = self.expressions(expression, flat=True) 1415 expressions = f" ({expressions})" if expressions else "" 1416 kind = expression.args["kind"] 1417 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1418 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1419 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1420 on_cluster = self.sql(expression, "cluster") 1421 on_cluster = f" {on_cluster}" if on_cluster else "" 1422 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1423 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1424 cascade = " CASCADE" if expression.args.get("cascade") else "" 1425 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1426 purge = " PURGE" if expression.args.get("purge") else "" 1427 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1428 1429 def set_operation(self, expression: exp.SetOperation) -> str: 1430 op_type = type(expression) 1431 op_name = op_type.key.upper() 1432 1433 distinct = expression.args.get("distinct") 1434 if ( 1435 distinct is False 1436 and op_type in (exp.Except, exp.Intersect) 1437 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1438 ): 1439 self.unsupported(f"{op_name} ALL is not supported") 1440 1441 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1442 1443 if distinct is None: 1444 distinct = default_distinct 1445 if distinct is None: 1446 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1447 1448 if distinct is default_distinct: 1449 kind = "" 1450 else: 1451 kind = " DISTINCT" if distinct else " ALL" 1452 1453 by_name = " BY NAME" if expression.args.get("by_name") else "" 1454 return f"{op_name}{kind}{by_name}" 1455 1456 def set_operations(self, expression: exp.SetOperation) -> str: 1457 if not self.SET_OP_MODIFIERS: 1458 limit = expression.args.get("limit") 1459 order = expression.args.get("order") 1460 1461 if limit or order: 1462 select = self._move_ctes_to_top_level( 1463 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1464 ) 1465 1466 if limit: 1467 select = select.limit(limit.pop(), copy=False) 1468 if order: 1469 select = select.order_by(order.pop(), copy=False) 1470 return self.sql(select) 1471 1472 sqls: t.List[str] = [] 1473 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1474 1475 while stack: 1476 node = stack.pop() 1477 1478 if isinstance(node, exp.SetOperation): 1479 stack.append(node.expression) 1480 stack.append( 1481 self.maybe_comment( 1482 self.set_operation(node), comments=node.comments, separated=True 1483 ) 1484 ) 1485 stack.append(node.this) 1486 else: 1487 sqls.append(self.sql(node)) 1488 1489 this = self.sep().join(sqls) 1490 this = self.query_modifiers(expression, this) 1491 return self.prepend_ctes(expression, this) 1492 1493 def fetch_sql(self, expression: exp.Fetch) -> str: 1494 direction = expression.args.get("direction") 1495 direction = f" {direction}" if direction else "" 1496 count = self.sql(expression, "count") 1497 count = f" {count}" if count else "" 1498 limit_options = self.sql(expression, "limit_options") 1499 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1500 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1501 1502 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1503 percent = " PERCENT" if expression.args.get("percent") else "" 1504 rows = " ROWS" if expression.args.get("rows") else "" 1505 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1506 if not with_ties and rows: 1507 with_ties = " ONLY" 1508 return f"{percent}{rows}{with_ties}" 1509 1510 def filter_sql(self, expression: exp.Filter) -> str: 1511 if self.AGGREGATE_FILTER_SUPPORTED: 1512 this = self.sql(expression, "this") 1513 where = self.sql(expression, "expression").strip() 1514 return f"{this} FILTER({where})" 1515 1516 agg = expression.this 1517 agg_arg = agg.this 1518 cond = expression.expression.this 1519 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1520 return self.sql(agg) 1521 1522 def hint_sql(self, expression: exp.Hint) -> str: 1523 if not self.QUERY_HINTS: 1524 self.unsupported("Hints are not supported") 1525 return "" 1526 1527 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1528 1529 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1530 using = self.sql(expression, "using") 1531 using = f" USING {using}" if using else "" 1532 columns = self.expressions(expression, key="columns", flat=True) 1533 columns = f"({columns})" if columns else "" 1534 partition_by = self.expressions(expression, key="partition_by", flat=True) 1535 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1536 where = self.sql(expression, "where") 1537 include = self.expressions(expression, key="include", flat=True) 1538 if include: 1539 include = f" INCLUDE ({include})" 1540 with_storage = self.expressions(expression, key="with_storage", flat=True) 1541 with_storage = f" WITH ({with_storage})" if with_storage else "" 1542 tablespace = self.sql(expression, "tablespace") 1543 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1544 on = self.sql(expression, "on") 1545 on = f" ON {on}" if on else "" 1546 1547 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1548 1549 def index_sql(self, expression: exp.Index) -> str: 1550 unique = "UNIQUE " if expression.args.get("unique") else "" 1551 primary = "PRIMARY " if expression.args.get("primary") else "" 1552 amp = "AMP " if expression.args.get("amp") else "" 1553 name = self.sql(expression, "this") 1554 name = f"{name} " if name else "" 1555 table = self.sql(expression, "table") 1556 table = f"{self.INDEX_ON} {table}" if table else "" 1557 1558 index = "INDEX " if not table else "" 1559 1560 params = self.sql(expression, "params") 1561 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1562 1563 def identifier_sql(self, expression: exp.Identifier) -> str: 1564 text = expression.name 1565 lower = text.lower() 1566 text = lower if self.normalize and not expression.quoted else text 1567 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1568 if ( 1569 expression.quoted 1570 or self.dialect.can_identify(text, self.identify) 1571 or lower in self.RESERVED_KEYWORDS 1572 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1573 ): 1574 text = f"{self._identifier_start}{text}{self._identifier_end}" 1575 return text 1576 1577 def hex_sql(self, expression: exp.Hex) -> str: 1578 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1579 if self.dialect.HEX_LOWERCASE: 1580 text = self.func("LOWER", text) 1581 1582 return text 1583 1584 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1585 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1586 if not self.dialect.HEX_LOWERCASE: 1587 text = self.func("LOWER", text) 1588 return text 1589 1590 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1591 input_format = self.sql(expression, "input_format") 1592 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1593 output_format = self.sql(expression, "output_format") 1594 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1595 return self.sep().join((input_format, output_format)) 1596 1597 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1598 string = self.sql(exp.Literal.string(expression.name)) 1599 return f"{prefix}{string}" 1600 1601 def partition_sql(self, expression: exp.Partition) -> str: 1602 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1603 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1604 1605 def properties_sql(self, expression: exp.Properties) -> str: 1606 root_properties = [] 1607 with_properties = [] 1608 1609 for p in expression.expressions: 1610 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1611 if p_loc == exp.Properties.Location.POST_WITH: 1612 with_properties.append(p) 1613 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1614 root_properties.append(p) 1615 1616 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1617 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1618 1619 if root_props and with_props and not self.pretty: 1620 with_props = " " + with_props 1621 1622 return root_props + with_props 1623 1624 def root_properties(self, properties: exp.Properties) -> str: 1625 if properties.expressions: 1626 return self.expressions(properties, indent=False, sep=" ") 1627 return "" 1628 1629 def properties( 1630 self, 1631 properties: exp.Properties, 1632 prefix: str = "", 1633 sep: str = ", ", 1634 suffix: str = "", 1635 wrapped: bool = True, 1636 ) -> str: 1637 if properties.expressions: 1638 expressions = self.expressions(properties, sep=sep, indent=False) 1639 if expressions: 1640 expressions = self.wrap(expressions) if wrapped else expressions 1641 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1642 return "" 1643 1644 def with_properties(self, properties: exp.Properties) -> str: 1645 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1646 1647 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1648 properties_locs = defaultdict(list) 1649 for p in properties.expressions: 1650 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1651 if p_loc != exp.Properties.Location.UNSUPPORTED: 1652 properties_locs[p_loc].append(p) 1653 else: 1654 self.unsupported(f"Unsupported property {p.key}") 1655 1656 return properties_locs 1657 1658 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1659 if isinstance(expression.this, exp.Dot): 1660 return self.sql(expression, "this") 1661 return f"'{expression.name}'" if string_key else expression.name 1662 1663 def property_sql(self, expression: exp.Property) -> str: 1664 property_cls = expression.__class__ 1665 if property_cls == exp.Property: 1666 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1667 1668 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1669 if not property_name: 1670 self.unsupported(f"Unsupported property {expression.key}") 1671 1672 return f"{property_name}={self.sql(expression, 'this')}" 1673 1674 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1675 if self.SUPPORTS_CREATE_TABLE_LIKE: 1676 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1677 options = f" {options}" if options else "" 1678 1679 like = f"LIKE {self.sql(expression, 'this')}{options}" 1680 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1681 like = f"({like})" 1682 1683 return like 1684 1685 if expression.expressions: 1686 self.unsupported("Transpilation of LIKE property options is unsupported") 1687 1688 select = exp.select("*").from_(expression.this).limit(0) 1689 return f"AS {self.sql(select)}" 1690 1691 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1692 no = "NO " if expression.args.get("no") else "" 1693 protection = " PROTECTION" if expression.args.get("protection") else "" 1694 return f"{no}FALLBACK{protection}" 1695 1696 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1697 no = "NO " if expression.args.get("no") else "" 1698 local = expression.args.get("local") 1699 local = f"{local} " if local else "" 1700 dual = "DUAL " if expression.args.get("dual") else "" 1701 before = "BEFORE " if expression.args.get("before") else "" 1702 after = "AFTER " if expression.args.get("after") else "" 1703 return f"{no}{local}{dual}{before}{after}JOURNAL" 1704 1705 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1706 freespace = self.sql(expression, "this") 1707 percent = " PERCENT" if expression.args.get("percent") else "" 1708 return f"FREESPACE={freespace}{percent}" 1709 1710 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1711 if expression.args.get("default"): 1712 property = "DEFAULT" 1713 elif expression.args.get("on"): 1714 property = "ON" 1715 else: 1716 property = "OFF" 1717 return f"CHECKSUM={property}" 1718 1719 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1720 if expression.args.get("no"): 1721 return "NO MERGEBLOCKRATIO" 1722 if expression.args.get("default"): 1723 return "DEFAULT MERGEBLOCKRATIO" 1724 1725 percent = " PERCENT" if expression.args.get("percent") else "" 1726 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1727 1728 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1729 default = expression.args.get("default") 1730 minimum = expression.args.get("minimum") 1731 maximum = expression.args.get("maximum") 1732 if default or minimum or maximum: 1733 if default: 1734 prop = "DEFAULT" 1735 elif minimum: 1736 prop = "MINIMUM" 1737 else: 1738 prop = "MAXIMUM" 1739 return f"{prop} DATABLOCKSIZE" 1740 units = expression.args.get("units") 1741 units = f" {units}" if units else "" 1742 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1743 1744 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1745 autotemp = expression.args.get("autotemp") 1746 always = expression.args.get("always") 1747 default = expression.args.get("default") 1748 manual = expression.args.get("manual") 1749 never = expression.args.get("never") 1750 1751 if autotemp is not None: 1752 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1753 elif always: 1754 prop = "ALWAYS" 1755 elif default: 1756 prop = "DEFAULT" 1757 elif manual: 1758 prop = "MANUAL" 1759 elif never: 1760 prop = "NEVER" 1761 return f"BLOCKCOMPRESSION={prop}" 1762 1763 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1764 no = expression.args.get("no") 1765 no = " NO" if no else "" 1766 concurrent = expression.args.get("concurrent") 1767 concurrent = " CONCURRENT" if concurrent else "" 1768 target = self.sql(expression, "target") 1769 target = f" {target}" if target else "" 1770 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1771 1772 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1773 if isinstance(expression.this, list): 1774 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1775 if expression.this: 1776 modulus = self.sql(expression, "this") 1777 remainder = self.sql(expression, "expression") 1778 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1779 1780 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1781 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1782 return f"FROM ({from_expressions}) TO ({to_expressions})" 1783 1784 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1785 this = self.sql(expression, "this") 1786 1787 for_values_or_default = expression.expression 1788 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1789 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1790 else: 1791 for_values_or_default = " DEFAULT" 1792 1793 return f"PARTITION OF {this}{for_values_or_default}" 1794 1795 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1796 kind = expression.args.get("kind") 1797 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1798 for_or_in = expression.args.get("for_or_in") 1799 for_or_in = f" {for_or_in}" if for_or_in else "" 1800 lock_type = expression.args.get("lock_type") 1801 override = " OVERRIDE" if expression.args.get("override") else "" 1802 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1803 1804 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1805 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1806 statistics = expression.args.get("statistics") 1807 statistics_sql = "" 1808 if statistics is not None: 1809 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1810 return f"{data_sql}{statistics_sql}" 1811 1812 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1813 this = self.sql(expression, "this") 1814 this = f"HISTORY_TABLE={this}" if this else "" 1815 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1816 data_consistency = ( 1817 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1818 ) 1819 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1820 retention_period = ( 1821 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1822 ) 1823 1824 if this: 1825 on_sql = self.func("ON", this, data_consistency, retention_period) 1826 else: 1827 on_sql = "ON" if expression.args.get("on") else "OFF" 1828 1829 sql = f"SYSTEM_VERSIONING={on_sql}" 1830 1831 return f"WITH({sql})" if expression.args.get("with") else sql 1832 1833 def insert_sql(self, expression: exp.Insert) -> str: 1834 hint = self.sql(expression, "hint") 1835 overwrite = expression.args.get("overwrite") 1836 1837 if isinstance(expression.this, exp.Directory): 1838 this = " OVERWRITE" if overwrite else " INTO" 1839 else: 1840 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1841 1842 stored = self.sql(expression, "stored") 1843 stored = f" {stored}" if stored else "" 1844 alternative = expression.args.get("alternative") 1845 alternative = f" OR {alternative}" if alternative else "" 1846 ignore = " IGNORE" if expression.args.get("ignore") else "" 1847 is_function = expression.args.get("is_function") 1848 if is_function: 1849 this = f"{this} FUNCTION" 1850 this = f"{this} {self.sql(expression, 'this')}" 1851 1852 exists = " IF EXISTS" if expression.args.get("exists") else "" 1853 where = self.sql(expression, "where") 1854 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1855 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1856 on_conflict = self.sql(expression, "conflict") 1857 on_conflict = f" {on_conflict}" if on_conflict else "" 1858 by_name = " BY NAME" if expression.args.get("by_name") else "" 1859 returning = self.sql(expression, "returning") 1860 1861 if self.RETURNING_END: 1862 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1863 else: 1864 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1865 1866 partition_by = self.sql(expression, "partition") 1867 partition_by = f" {partition_by}" if partition_by else "" 1868 settings = self.sql(expression, "settings") 1869 settings = f" {settings}" if settings else "" 1870 1871 source = self.sql(expression, "source") 1872 source = f"TABLE {source}" if source else "" 1873 1874 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1875 return self.prepend_ctes(expression, sql) 1876 1877 def introducer_sql(self, expression: exp.Introducer) -> str: 1878 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1879 1880 def kill_sql(self, expression: exp.Kill) -> str: 1881 kind = self.sql(expression, "kind") 1882 kind = f" {kind}" if kind else "" 1883 this = self.sql(expression, "this") 1884 this = f" {this}" if this else "" 1885 return f"KILL{kind}{this}" 1886 1887 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1888 return expression.name 1889 1890 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1891 return expression.name 1892 1893 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1894 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1895 1896 constraint = self.sql(expression, "constraint") 1897 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1898 1899 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1900 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1901 action = self.sql(expression, "action") 1902 1903 expressions = self.expressions(expression, flat=True) 1904 if expressions: 1905 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1906 expressions = f" {set_keyword}{expressions}" 1907 1908 where = self.sql(expression, "where") 1909 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1910 1911 def returning_sql(self, expression: exp.Returning) -> str: 1912 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1913 1914 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1915 fields = self.sql(expression, "fields") 1916 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1917 escaped = self.sql(expression, "escaped") 1918 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1919 items = self.sql(expression, "collection_items") 1920 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1921 keys = self.sql(expression, "map_keys") 1922 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1923 lines = self.sql(expression, "lines") 1924 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1925 null = self.sql(expression, "null") 1926 null = f" NULL DEFINED AS {null}" if null else "" 1927 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1928 1929 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1930 return f"WITH ({self.expressions(expression, flat=True)})" 1931 1932 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1933 this = f"{self.sql(expression, 'this')} INDEX" 1934 target = self.sql(expression, "target") 1935 target = f" FOR {target}" if target else "" 1936 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1937 1938 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1939 this = self.sql(expression, "this") 1940 kind = self.sql(expression, "kind") 1941 expr = self.sql(expression, "expression") 1942 return f"{this} ({kind} => {expr})" 1943 1944 def table_parts(self, expression: exp.Table) -> str: 1945 return ".".join( 1946 self.sql(part) 1947 for part in ( 1948 expression.args.get("catalog"), 1949 expression.args.get("db"), 1950 expression.args.get("this"), 1951 ) 1952 if part is not None 1953 ) 1954 1955 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1956 table = self.table_parts(expression) 1957 only = "ONLY " if expression.args.get("only") else "" 1958 partition = self.sql(expression, "partition") 1959 partition = f" {partition}" if partition else "" 1960 version = self.sql(expression, "version") 1961 version = f" {version}" if version else "" 1962 alias = self.sql(expression, "alias") 1963 alias = f"{sep}{alias}" if alias else "" 1964 1965 sample = self.sql(expression, "sample") 1966 if self.dialect.ALIAS_POST_TABLESAMPLE: 1967 sample_pre_alias = sample 1968 sample_post_alias = "" 1969 else: 1970 sample_pre_alias = "" 1971 sample_post_alias = sample 1972 1973 hints = self.expressions(expression, key="hints", sep=" ") 1974 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1975 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1976 joins = self.indent( 1977 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1978 ) 1979 laterals = self.expressions(expression, key="laterals", sep="") 1980 1981 file_format = self.sql(expression, "format") 1982 if file_format: 1983 pattern = self.sql(expression, "pattern") 1984 pattern = f", PATTERN => {pattern}" if pattern else "" 1985 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1986 1987 ordinality = expression.args.get("ordinality") or "" 1988 if ordinality: 1989 ordinality = f" WITH ORDINALITY{alias}" 1990 alias = "" 1991 1992 when = self.sql(expression, "when") 1993 if when: 1994 table = f"{table} {when}" 1995 1996 changes = self.sql(expression, "changes") 1997 changes = f" {changes}" if changes else "" 1998 1999 rows_from = self.expressions(expression, key="rows_from") 2000 if rows_from: 2001 table = f"ROWS FROM {self.wrap(rows_from)}" 2002 2003 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2004 2005 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2006 table = self.func("TABLE", expression.this) 2007 alias = self.sql(expression, "alias") 2008 alias = f" AS {alias}" if alias else "" 2009 sample = self.sql(expression, "sample") 2010 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2011 joins = self.indent( 2012 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2013 ) 2014 return f"{table}{alias}{pivots}{sample}{joins}" 2015 2016 def tablesample_sql( 2017 self, 2018 expression: exp.TableSample, 2019 tablesample_keyword: t.Optional[str] = None, 2020 ) -> str: 2021 method = self.sql(expression, "method") 2022 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2023 numerator = self.sql(expression, "bucket_numerator") 2024 denominator = self.sql(expression, "bucket_denominator") 2025 field = self.sql(expression, "bucket_field") 2026 field = f" ON {field}" if field else "" 2027 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2028 seed = self.sql(expression, "seed") 2029 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2030 2031 size = self.sql(expression, "size") 2032 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2033 size = f"{size} ROWS" 2034 2035 percent = self.sql(expression, "percent") 2036 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2037 percent = f"{percent} PERCENT" 2038 2039 expr = f"{bucket}{percent}{size}" 2040 if self.TABLESAMPLE_REQUIRES_PARENS: 2041 expr = f"({expr})" 2042 2043 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2044 2045 def pivot_sql(self, expression: exp.Pivot) -> str: 2046 expressions = self.expressions(expression, flat=True) 2047 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2048 2049 if expression.this: 2050 this = self.sql(expression, "this") 2051 if not expressions: 2052 return f"UNPIVOT {this}" 2053 2054 on = f"{self.seg('ON')} {expressions}" 2055 into = self.sql(expression, "into") 2056 into = f"{self.seg('INTO')} {into}" if into else "" 2057 using = self.expressions(expression, key="using", flat=True) 2058 using = f"{self.seg('USING')} {using}" if using else "" 2059 group = self.sql(expression, "group") 2060 return f"{direction} {this}{on}{into}{using}{group}" 2061 2062 alias = self.sql(expression, "alias") 2063 alias = f" AS {alias}" if alias else "" 2064 2065 field = self.sql(expression, "field") 2066 2067 include_nulls = expression.args.get("include_nulls") 2068 if include_nulls is not None: 2069 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2070 else: 2071 nulls = "" 2072 2073 default_on_null = self.sql(expression, "default_on_null") 2074 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2075 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2076 2077 def version_sql(self, expression: exp.Version) -> str: 2078 this = f"FOR {expression.name}" 2079 kind = expression.text("kind") 2080 expr = self.sql(expression, "expression") 2081 return f"{this} {kind} {expr}" 2082 2083 def tuple_sql(self, expression: exp.Tuple) -> str: 2084 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2085 2086 def update_sql(self, expression: exp.Update) -> str: 2087 this = self.sql(expression, "this") 2088 set_sql = self.expressions(expression, flat=True) 2089 from_sql = self.sql(expression, "from") 2090 where_sql = self.sql(expression, "where") 2091 returning = self.sql(expression, "returning") 2092 order = self.sql(expression, "order") 2093 limit = self.sql(expression, "limit") 2094 if self.RETURNING_END: 2095 expression_sql = f"{from_sql}{where_sql}{returning}" 2096 else: 2097 expression_sql = f"{returning}{from_sql}{where_sql}" 2098 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2099 return self.prepend_ctes(expression, sql) 2100 2101 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2102 values_as_table = values_as_table and self.VALUES_AS_TABLE 2103 2104 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2105 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2106 args = self.expressions(expression) 2107 alias = self.sql(expression, "alias") 2108 values = f"VALUES{self.seg('')}{args}" 2109 values = ( 2110 f"({values})" 2111 if self.WRAP_DERIVED_VALUES 2112 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2113 else values 2114 ) 2115 return f"{values} AS {alias}" if alias else values 2116 2117 # Converts `VALUES...` expression into a series of select unions. 2118 alias_node = expression.args.get("alias") 2119 column_names = alias_node and alias_node.columns 2120 2121 selects: t.List[exp.Query] = [] 2122 2123 for i, tup in enumerate(expression.expressions): 2124 row = tup.expressions 2125 2126 if i == 0 and column_names: 2127 row = [ 2128 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2129 ] 2130 2131 selects.append(exp.Select(expressions=row)) 2132 2133 if self.pretty: 2134 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2135 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2136 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2137 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2138 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2139 2140 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2141 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2142 return f"({unions}){alias}" 2143 2144 def var_sql(self, expression: exp.Var) -> str: 2145 return self.sql(expression, "this") 2146 2147 @unsupported_args("expressions") 2148 def into_sql(self, expression: exp.Into) -> str: 2149 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2150 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2151 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2152 2153 def from_sql(self, expression: exp.From) -> str: 2154 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2155 2156 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2157 grouping_sets = self.expressions(expression, indent=False) 2158 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2159 2160 def rollup_sql(self, expression: exp.Rollup) -> str: 2161 expressions = self.expressions(expression, indent=False) 2162 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2163 2164 def cube_sql(self, expression: exp.Cube) -> str: 2165 expressions = self.expressions(expression, indent=False) 2166 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2167 2168 def group_sql(self, expression: exp.Group) -> str: 2169 group_by_all = expression.args.get("all") 2170 if group_by_all is True: 2171 modifier = " ALL" 2172 elif group_by_all is False: 2173 modifier = " DISTINCT" 2174 else: 2175 modifier = "" 2176 2177 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2178 2179 grouping_sets = self.expressions(expression, key="grouping_sets") 2180 cube = self.expressions(expression, key="cube") 2181 rollup = self.expressions(expression, key="rollup") 2182 2183 groupings = csv( 2184 self.seg(grouping_sets) if grouping_sets else "", 2185 self.seg(cube) if cube else "", 2186 self.seg(rollup) if rollup else "", 2187 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2188 sep=self.GROUPINGS_SEP, 2189 ) 2190 2191 if ( 2192 expression.expressions 2193 and groupings 2194 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2195 ): 2196 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2197 2198 return f"{group_by}{groupings}" 2199 2200 def having_sql(self, expression: exp.Having) -> str: 2201 this = self.indent(self.sql(expression, "this")) 2202 return f"{self.seg('HAVING')}{self.sep()}{this}" 2203 2204 def connect_sql(self, expression: exp.Connect) -> str: 2205 start = self.sql(expression, "start") 2206 start = self.seg(f"START WITH {start}") if start else "" 2207 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2208 connect = self.sql(expression, "connect") 2209 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2210 return start + connect 2211 2212 def prior_sql(self, expression: exp.Prior) -> str: 2213 return f"PRIOR {self.sql(expression, 'this')}" 2214 2215 def join_sql(self, expression: exp.Join) -> str: 2216 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2217 side = None 2218 else: 2219 side = expression.side 2220 2221 op_sql = " ".join( 2222 op 2223 for op in ( 2224 expression.method, 2225 "GLOBAL" if expression.args.get("global") else None, 2226 side, 2227 expression.kind, 2228 expression.hint if self.JOIN_HINTS else None, 2229 ) 2230 if op 2231 ) 2232 match_cond = self.sql(expression, "match_condition") 2233 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2234 on_sql = self.sql(expression, "on") 2235 using = expression.args.get("using") 2236 2237 if not on_sql and using: 2238 on_sql = csv(*(self.sql(column) for column in using)) 2239 2240 this = expression.this 2241 this_sql = self.sql(this) 2242 2243 exprs = self.expressions(expression) 2244 if exprs: 2245 this_sql = f"{this_sql},{self.seg(exprs)}" 2246 2247 if on_sql: 2248 on_sql = self.indent(on_sql, skip_first=True) 2249 space = self.seg(" " * self.pad) if self.pretty else " " 2250 if using: 2251 on_sql = f"{space}USING ({on_sql})" 2252 else: 2253 on_sql = f"{space}ON {on_sql}" 2254 elif not op_sql: 2255 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2256 return f" {this_sql}" 2257 2258 return f", {this_sql}" 2259 2260 if op_sql != "STRAIGHT_JOIN": 2261 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2262 2263 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2264 2265 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2266 args = self.expressions(expression, flat=True) 2267 args = f"({args})" if len(args.split(",")) > 1 else args 2268 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2269 2270 def lateral_op(self, expression: exp.Lateral) -> str: 2271 cross_apply = expression.args.get("cross_apply") 2272 2273 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2274 if cross_apply is True: 2275 op = "INNER JOIN " 2276 elif cross_apply is False: 2277 op = "LEFT JOIN " 2278 else: 2279 op = "" 2280 2281 return f"{op}LATERAL" 2282 2283 def lateral_sql(self, expression: exp.Lateral) -> str: 2284 this = self.sql(expression, "this") 2285 2286 if expression.args.get("view"): 2287 alias = expression.args["alias"] 2288 columns = self.expressions(alias, key="columns", flat=True) 2289 table = f" {alias.name}" if alias.name else "" 2290 columns = f" AS {columns}" if columns else "" 2291 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2292 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2293 2294 alias = self.sql(expression, "alias") 2295 alias = f" AS {alias}" if alias else "" 2296 return f"{self.lateral_op(expression)} {this}{alias}" 2297 2298 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2299 this = self.sql(expression, "this") 2300 2301 args = [ 2302 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2303 for e in (expression.args.get(k) for k in ("offset", "expression")) 2304 if e 2305 ] 2306 2307 args_sql = ", ".join(self.sql(e) for e in args) 2308 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2309 expressions = self.expressions(expression, flat=True) 2310 limit_options = self.sql(expression, "limit_options") 2311 expressions = f" BY {expressions}" if expressions else "" 2312 2313 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2314 2315 def offset_sql(self, expression: exp.Offset) -> str: 2316 this = self.sql(expression, "this") 2317 value = expression.expression 2318 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2319 expressions = self.expressions(expression, flat=True) 2320 expressions = f" BY {expressions}" if expressions else "" 2321 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2322 2323 def setitem_sql(self, expression: exp.SetItem) -> str: 2324 kind = self.sql(expression, "kind") 2325 kind = f"{kind} " if kind else "" 2326 this = self.sql(expression, "this") 2327 expressions = self.expressions(expression) 2328 collate = self.sql(expression, "collate") 2329 collate = f" COLLATE {collate}" if collate else "" 2330 global_ = "GLOBAL " if expression.args.get("global") else "" 2331 return f"{global_}{kind}{this}{expressions}{collate}" 2332 2333 def set_sql(self, expression: exp.Set) -> str: 2334 expressions = f" {self.expressions(expression, flat=True)}" 2335 tag = " TAG" if expression.args.get("tag") else "" 2336 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2337 2338 def pragma_sql(self, expression: exp.Pragma) -> str: 2339 return f"PRAGMA {self.sql(expression, 'this')}" 2340 2341 def lock_sql(self, expression: exp.Lock) -> str: 2342 if not self.LOCKING_READS_SUPPORTED: 2343 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2344 return "" 2345 2346 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2347 expressions = self.expressions(expression, flat=True) 2348 expressions = f" OF {expressions}" if expressions else "" 2349 wait = expression.args.get("wait") 2350 2351 if wait is not None: 2352 if isinstance(wait, exp.Literal): 2353 wait = f" WAIT {self.sql(wait)}" 2354 else: 2355 wait = " NOWAIT" if wait else " SKIP LOCKED" 2356 2357 return f"{lock_type}{expressions}{wait or ''}" 2358 2359 def literal_sql(self, expression: exp.Literal) -> str: 2360 text = expression.this or "" 2361 if expression.is_string: 2362 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2363 return text 2364 2365 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2366 if self.dialect.ESCAPED_SEQUENCES: 2367 to_escaped = self.dialect.ESCAPED_SEQUENCES 2368 text = "".join( 2369 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2370 ) 2371 2372 return self._replace_line_breaks(text).replace( 2373 self.dialect.QUOTE_END, self._escaped_quote_end 2374 ) 2375 2376 def loaddata_sql(self, expression: exp.LoadData) -> str: 2377 local = " LOCAL" if expression.args.get("local") else "" 2378 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2379 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2380 this = f" INTO TABLE {self.sql(expression, 'this')}" 2381 partition = self.sql(expression, "partition") 2382 partition = f" {partition}" if partition else "" 2383 input_format = self.sql(expression, "input_format") 2384 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2385 serde = self.sql(expression, "serde") 2386 serde = f" SERDE {serde}" if serde else "" 2387 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2388 2389 def null_sql(self, *_) -> str: 2390 return "NULL" 2391 2392 def boolean_sql(self, expression: exp.Boolean) -> str: 2393 return "TRUE" if expression.this else "FALSE" 2394 2395 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2396 this = self.sql(expression, "this") 2397 this = f"{this} " if this else this 2398 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2399 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2400 2401 def withfill_sql(self, expression: exp.WithFill) -> str: 2402 from_sql = self.sql(expression, "from") 2403 from_sql = f" FROM {from_sql}" if from_sql else "" 2404 to_sql = self.sql(expression, "to") 2405 to_sql = f" TO {to_sql}" if to_sql else "" 2406 step_sql = self.sql(expression, "step") 2407 step_sql = f" STEP {step_sql}" if step_sql else "" 2408 interpolated_values = [ 2409 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2410 if isinstance(e, exp.Alias) 2411 else self.sql(e, "this") 2412 for e in expression.args.get("interpolate") or [] 2413 ] 2414 interpolate = ( 2415 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2416 ) 2417 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2418 2419 def cluster_sql(self, expression: exp.Cluster) -> str: 2420 return self.op_expressions("CLUSTER BY", expression) 2421 2422 def distribute_sql(self, expression: exp.Distribute) -> str: 2423 return self.op_expressions("DISTRIBUTE BY", expression) 2424 2425 def sort_sql(self, expression: exp.Sort) -> str: 2426 return self.op_expressions("SORT BY", expression) 2427 2428 def ordered_sql(self, expression: exp.Ordered) -> str: 2429 desc = expression.args.get("desc") 2430 asc = not desc 2431 2432 nulls_first = expression.args.get("nulls_first") 2433 nulls_last = not nulls_first 2434 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2435 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2436 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2437 2438 this = self.sql(expression, "this") 2439 2440 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2441 nulls_sort_change = "" 2442 if nulls_first and ( 2443 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2444 ): 2445 nulls_sort_change = " NULLS FIRST" 2446 elif ( 2447 nulls_last 2448 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2449 and not nulls_are_last 2450 ): 2451 nulls_sort_change = " NULLS LAST" 2452 2453 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2454 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2455 window = expression.find_ancestor(exp.Window, exp.Select) 2456 if isinstance(window, exp.Window) and window.args.get("spec"): 2457 self.unsupported( 2458 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2459 ) 2460 nulls_sort_change = "" 2461 elif self.NULL_ORDERING_SUPPORTED is False and ( 2462 (asc and nulls_sort_change == " NULLS LAST") 2463 or (desc and nulls_sort_change == " NULLS FIRST") 2464 ): 2465 # BigQuery does not allow these ordering/nulls combinations when used under 2466 # an aggregation func or under a window containing one 2467 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2468 2469 if isinstance(ancestor, exp.Window): 2470 ancestor = ancestor.this 2471 if isinstance(ancestor, exp.AggFunc): 2472 self.unsupported( 2473 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2474 ) 2475 nulls_sort_change = "" 2476 elif self.NULL_ORDERING_SUPPORTED is None: 2477 if expression.this.is_int: 2478 self.unsupported( 2479 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2480 ) 2481 elif not isinstance(expression.this, exp.Rand): 2482 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2483 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2484 nulls_sort_change = "" 2485 2486 with_fill = self.sql(expression, "with_fill") 2487 with_fill = f" {with_fill}" if with_fill else "" 2488 2489 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2490 2491 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2492 window_frame = self.sql(expression, "window_frame") 2493 window_frame = f"{window_frame} " if window_frame else "" 2494 2495 this = self.sql(expression, "this") 2496 2497 return f"{window_frame}{this}" 2498 2499 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2500 partition = self.partition_by_sql(expression) 2501 order = self.sql(expression, "order") 2502 measures = self.expressions(expression, key="measures") 2503 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2504 rows = self.sql(expression, "rows") 2505 rows = self.seg(rows) if rows else "" 2506 after = self.sql(expression, "after") 2507 after = self.seg(after) if after else "" 2508 pattern = self.sql(expression, "pattern") 2509 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2510 definition_sqls = [ 2511 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2512 for definition in expression.args.get("define", []) 2513 ] 2514 definitions = self.expressions(sqls=definition_sqls) 2515 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2516 body = "".join( 2517 ( 2518 partition, 2519 order, 2520 measures, 2521 rows, 2522 after, 2523 pattern, 2524 define, 2525 ) 2526 ) 2527 alias = self.sql(expression, "alias") 2528 alias = f" {alias}" if alias else "" 2529 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2530 2531 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2532 limit = expression.args.get("limit") 2533 2534 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2535 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2536 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2537 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2538 2539 return csv( 2540 *sqls, 2541 *[self.sql(join) for join in expression.args.get("joins") or []], 2542 self.sql(expression, "match"), 2543 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2544 self.sql(expression, "prewhere"), 2545 self.sql(expression, "where"), 2546 self.sql(expression, "connect"), 2547 self.sql(expression, "group"), 2548 self.sql(expression, "having"), 2549 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2550 self.sql(expression, "order"), 2551 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2552 *self.after_limit_modifiers(expression), 2553 self.options_modifier(expression), 2554 sep="", 2555 ) 2556 2557 def options_modifier(self, expression: exp.Expression) -> str: 2558 options = self.expressions(expression, key="options") 2559 return f" {options}" if options else "" 2560 2561 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2562 return "" 2563 2564 def offset_limit_modifiers( 2565 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2566 ) -> t.List[str]: 2567 return [ 2568 self.sql(expression, "offset") if fetch else self.sql(limit), 2569 self.sql(limit) if fetch else self.sql(expression, "offset"), 2570 ] 2571 2572 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2573 locks = self.expressions(expression, key="locks", sep=" ") 2574 locks = f" {locks}" if locks else "" 2575 return [locks, self.sql(expression, "sample")] 2576 2577 def select_sql(self, expression: exp.Select) -> str: 2578 into = expression.args.get("into") 2579 if not self.SUPPORTS_SELECT_INTO and into: 2580 into.pop() 2581 2582 hint = self.sql(expression, "hint") 2583 distinct = self.sql(expression, "distinct") 2584 distinct = f" {distinct}" if distinct else "" 2585 kind = self.sql(expression, "kind") 2586 2587 limit = expression.args.get("limit") 2588 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2589 top = self.limit_sql(limit, top=True) 2590 limit.pop() 2591 else: 2592 top = "" 2593 2594 expressions = self.expressions(expression) 2595 2596 if kind: 2597 if kind in self.SELECT_KINDS: 2598 kind = f" AS {kind}" 2599 else: 2600 if kind == "STRUCT": 2601 expressions = self.expressions( 2602 sqls=[ 2603 self.sql( 2604 exp.Struct( 2605 expressions=[ 2606 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2607 if isinstance(e, exp.Alias) 2608 else e 2609 for e in expression.expressions 2610 ] 2611 ) 2612 ) 2613 ] 2614 ) 2615 kind = "" 2616 2617 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2618 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2619 2620 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2621 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2622 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2623 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2624 sql = self.query_modifiers( 2625 expression, 2626 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2627 self.sql(expression, "into", comment=False), 2628 self.sql(expression, "from", comment=False), 2629 ) 2630 2631 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2632 if expression.args.get("with"): 2633 sql = self.maybe_comment(sql, expression) 2634 expression.pop_comments() 2635 2636 sql = self.prepend_ctes(expression, sql) 2637 2638 if not self.SUPPORTS_SELECT_INTO and into: 2639 if into.args.get("temporary"): 2640 table_kind = " TEMPORARY" 2641 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2642 table_kind = " UNLOGGED" 2643 else: 2644 table_kind = "" 2645 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2646 2647 return sql 2648 2649 def schema_sql(self, expression: exp.Schema) -> str: 2650 this = self.sql(expression, "this") 2651 sql = self.schema_columns_sql(expression) 2652 return f"{this} {sql}" if this and sql else this or sql 2653 2654 def schema_columns_sql(self, expression: exp.Schema) -> str: 2655 if expression.expressions: 2656 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2657 return "" 2658 2659 def star_sql(self, expression: exp.Star) -> str: 2660 except_ = self.expressions(expression, key="except", flat=True) 2661 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2662 replace = self.expressions(expression, key="replace", flat=True) 2663 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2664 rename = self.expressions(expression, key="rename", flat=True) 2665 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2666 return f"*{except_}{replace}{rename}" 2667 2668 def parameter_sql(self, expression: exp.Parameter) -> str: 2669 this = self.sql(expression, "this") 2670 return f"{self.PARAMETER_TOKEN}{this}" 2671 2672 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2673 this = self.sql(expression, "this") 2674 kind = expression.text("kind") 2675 if kind: 2676 kind = f"{kind}." 2677 return f"@@{kind}{this}" 2678 2679 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2680 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2681 2682 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2683 alias = self.sql(expression, "alias") 2684 alias = f"{sep}{alias}" if alias else "" 2685 sample = self.sql(expression, "sample") 2686 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2687 alias = f"{sample}{alias}" 2688 2689 # Set to None so it's not generated again by self.query_modifiers() 2690 expression.set("sample", None) 2691 2692 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2693 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2694 return self.prepend_ctes(expression, sql) 2695 2696 def qualify_sql(self, expression: exp.Qualify) -> str: 2697 this = self.indent(self.sql(expression, "this")) 2698 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2699 2700 def unnest_sql(self, expression: exp.Unnest) -> str: 2701 args = self.expressions(expression, flat=True) 2702 2703 alias = expression.args.get("alias") 2704 offset = expression.args.get("offset") 2705 2706 if self.UNNEST_WITH_ORDINALITY: 2707 if alias and isinstance(offset, exp.Expression): 2708 alias.append("columns", offset) 2709 2710 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2711 columns = alias.columns 2712 alias = self.sql(columns[0]) if columns else "" 2713 else: 2714 alias = self.sql(alias) 2715 2716 alias = f" AS {alias}" if alias else alias 2717 if self.UNNEST_WITH_ORDINALITY: 2718 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2719 else: 2720 if isinstance(offset, exp.Expression): 2721 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2722 elif offset: 2723 suffix = f"{alias} WITH OFFSET" 2724 else: 2725 suffix = alias 2726 2727 return f"UNNEST({args}){suffix}" 2728 2729 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2730 return "" 2731 2732 def where_sql(self, expression: exp.Where) -> str: 2733 this = self.indent(self.sql(expression, "this")) 2734 return f"{self.seg('WHERE')}{self.sep()}{this}" 2735 2736 def window_sql(self, expression: exp.Window) -> str: 2737 this = self.sql(expression, "this") 2738 partition = self.partition_by_sql(expression) 2739 order = expression.args.get("order") 2740 order = self.order_sql(order, flat=True) if order else "" 2741 spec = self.sql(expression, "spec") 2742 alias = self.sql(expression, "alias") 2743 over = self.sql(expression, "over") or "OVER" 2744 2745 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2746 2747 first = expression.args.get("first") 2748 if first is None: 2749 first = "" 2750 else: 2751 first = "FIRST" if first else "LAST" 2752 2753 if not partition and not order and not spec and alias: 2754 return f"{this} {alias}" 2755 2756 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2757 return f"{this} ({args})" 2758 2759 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2760 partition = self.expressions(expression, key="partition_by", flat=True) 2761 return f"PARTITION BY {partition}" if partition else "" 2762 2763 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2764 kind = self.sql(expression, "kind") 2765 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2766 end = ( 2767 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2768 or "CURRENT ROW" 2769 ) 2770 return f"{kind} BETWEEN {start} AND {end}" 2771 2772 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2773 this = self.sql(expression, "this") 2774 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2775 return f"{this} WITHIN GROUP ({expression_sql})" 2776 2777 def between_sql(self, expression: exp.Between) -> str: 2778 this = self.sql(expression, "this") 2779 low = self.sql(expression, "low") 2780 high = self.sql(expression, "high") 2781 return f"{this} BETWEEN {low} AND {high}" 2782 2783 def bracket_offset_expressions( 2784 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2785 ) -> t.List[exp.Expression]: 2786 return apply_index_offset( 2787 expression.this, 2788 expression.expressions, 2789 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2790 ) 2791 2792 def bracket_sql(self, expression: exp.Bracket) -> str: 2793 expressions = self.bracket_offset_expressions(expression) 2794 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2795 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2796 2797 def all_sql(self, expression: exp.All) -> str: 2798 return f"ALL {self.wrap(expression)}" 2799 2800 def any_sql(self, expression: exp.Any) -> str: 2801 this = self.sql(expression, "this") 2802 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2803 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2804 this = self.wrap(this) 2805 return f"ANY{this}" 2806 return f"ANY {this}" 2807 2808 def exists_sql(self, expression: exp.Exists) -> str: 2809 return f"EXISTS{self.wrap(expression)}" 2810 2811 def case_sql(self, expression: exp.Case) -> str: 2812 this = self.sql(expression, "this") 2813 statements = [f"CASE {this}" if this else "CASE"] 2814 2815 for e in expression.args["ifs"]: 2816 statements.append(f"WHEN {self.sql(e, 'this')}") 2817 statements.append(f"THEN {self.sql(e, 'true')}") 2818 2819 default = self.sql(expression, "default") 2820 2821 if default: 2822 statements.append(f"ELSE {default}") 2823 2824 statements.append("END") 2825 2826 if self.pretty and self.too_wide(statements): 2827 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2828 2829 return " ".join(statements) 2830 2831 def constraint_sql(self, expression: exp.Constraint) -> str: 2832 this = self.sql(expression, "this") 2833 expressions = self.expressions(expression, flat=True) 2834 return f"CONSTRAINT {this} {expressions}" 2835 2836 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2837 order = expression.args.get("order") 2838 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2839 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2840 2841 def extract_sql(self, expression: exp.Extract) -> str: 2842 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2843 expression_sql = self.sql(expression, "expression") 2844 return f"EXTRACT({this} FROM {expression_sql})" 2845 2846 def trim_sql(self, expression: exp.Trim) -> str: 2847 trim_type = self.sql(expression, "position") 2848 2849 if trim_type == "LEADING": 2850 func_name = "LTRIM" 2851 elif trim_type == "TRAILING": 2852 func_name = "RTRIM" 2853 else: 2854 func_name = "TRIM" 2855 2856 return self.func(func_name, expression.this, expression.expression) 2857 2858 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2859 args = expression.expressions 2860 if isinstance(expression, exp.ConcatWs): 2861 args = args[1:] # Skip the delimiter 2862 2863 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2864 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2865 2866 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2867 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2868 2869 return args 2870 2871 def concat_sql(self, expression: exp.Concat) -> str: 2872 expressions = self.convert_concat_args(expression) 2873 2874 # Some dialects don't allow a single-argument CONCAT call 2875 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2876 return self.sql(expressions[0]) 2877 2878 return self.func("CONCAT", *expressions) 2879 2880 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2881 return self.func( 2882 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2883 ) 2884 2885 def check_sql(self, expression: exp.Check) -> str: 2886 this = self.sql(expression, key="this") 2887 return f"CHECK ({this})" 2888 2889 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2890 expressions = self.expressions(expression, flat=True) 2891 expressions = f" ({expressions})" if expressions else "" 2892 reference = self.sql(expression, "reference") 2893 reference = f" {reference}" if reference else "" 2894 delete = self.sql(expression, "delete") 2895 delete = f" ON DELETE {delete}" if delete else "" 2896 update = self.sql(expression, "update") 2897 update = f" ON UPDATE {update}" if update else "" 2898 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2899 2900 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2901 expressions = self.expressions(expression, flat=True) 2902 options = self.expressions(expression, key="options", flat=True, sep=" ") 2903 options = f" {options}" if options else "" 2904 return f"PRIMARY KEY ({expressions}){options}" 2905 2906 def if_sql(self, expression: exp.If) -> str: 2907 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2908 2909 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2910 modifier = expression.args.get("modifier") 2911 modifier = f" {modifier}" if modifier else "" 2912 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2913 2914 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2915 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2916 2917 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2918 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2919 2920 if expression.args.get("escape"): 2921 path = self.escape_str(path) 2922 2923 if self.QUOTE_JSON_PATH: 2924 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2925 2926 return path 2927 2928 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2929 if isinstance(expression, exp.JSONPathPart): 2930 transform = self.TRANSFORMS.get(expression.__class__) 2931 if not callable(transform): 2932 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2933 return "" 2934 2935 return transform(self, expression) 2936 2937 if isinstance(expression, int): 2938 return str(expression) 2939 2940 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2941 escaped = expression.replace("'", "\\'") 2942 escaped = f"\\'{expression}\\'" 2943 else: 2944 escaped = expression.replace('"', '\\"') 2945 escaped = f'"{escaped}"' 2946 2947 return escaped 2948 2949 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2950 return f"{self.sql(expression, 'this')} FORMAT JSON" 2951 2952 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2953 null_handling = expression.args.get("null_handling") 2954 null_handling = f" {null_handling}" if null_handling else "" 2955 2956 unique_keys = expression.args.get("unique_keys") 2957 if unique_keys is not None: 2958 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2959 else: 2960 unique_keys = "" 2961 2962 return_type = self.sql(expression, "return_type") 2963 return_type = f" RETURNING {return_type}" if return_type else "" 2964 encoding = self.sql(expression, "encoding") 2965 encoding = f" ENCODING {encoding}" if encoding else "" 2966 2967 return self.func( 2968 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2969 *expression.expressions, 2970 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2971 ) 2972 2973 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2974 return self.jsonobject_sql(expression) 2975 2976 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2977 null_handling = expression.args.get("null_handling") 2978 null_handling = f" {null_handling}" if null_handling else "" 2979 return_type = self.sql(expression, "return_type") 2980 return_type = f" RETURNING {return_type}" if return_type else "" 2981 strict = " STRICT" if expression.args.get("strict") else "" 2982 return self.func( 2983 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2984 ) 2985 2986 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2987 this = self.sql(expression, "this") 2988 order = self.sql(expression, "order") 2989 null_handling = expression.args.get("null_handling") 2990 null_handling = f" {null_handling}" if null_handling else "" 2991 return_type = self.sql(expression, "return_type") 2992 return_type = f" RETURNING {return_type}" if return_type else "" 2993 strict = " STRICT" if expression.args.get("strict") else "" 2994 return self.func( 2995 "JSON_ARRAYAGG", 2996 this, 2997 suffix=f"{order}{null_handling}{return_type}{strict})", 2998 ) 2999 3000 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3001 path = self.sql(expression, "path") 3002 path = f" PATH {path}" if path else "" 3003 nested_schema = self.sql(expression, "nested_schema") 3004 3005 if nested_schema: 3006 return f"NESTED{path} {nested_schema}" 3007 3008 this = self.sql(expression, "this") 3009 kind = self.sql(expression, "kind") 3010 kind = f" {kind}" if kind else "" 3011 return f"{this}{kind}{path}" 3012 3013 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3014 return self.func("COLUMNS", *expression.expressions) 3015 3016 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3017 this = self.sql(expression, "this") 3018 path = self.sql(expression, "path") 3019 path = f", {path}" if path else "" 3020 error_handling = expression.args.get("error_handling") 3021 error_handling = f" {error_handling}" if error_handling else "" 3022 empty_handling = expression.args.get("empty_handling") 3023 empty_handling = f" {empty_handling}" if empty_handling else "" 3024 schema = self.sql(expression, "schema") 3025 return self.func( 3026 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3027 ) 3028 3029 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3030 this = self.sql(expression, "this") 3031 kind = self.sql(expression, "kind") 3032 path = self.sql(expression, "path") 3033 path = f" {path}" if path else "" 3034 as_json = " AS JSON" if expression.args.get("as_json") else "" 3035 return f"{this} {kind}{path}{as_json}" 3036 3037 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3038 this = self.sql(expression, "this") 3039 path = self.sql(expression, "path") 3040 path = f", {path}" if path else "" 3041 expressions = self.expressions(expression) 3042 with_ = ( 3043 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3044 if expressions 3045 else "" 3046 ) 3047 return f"OPENJSON({this}{path}){with_}" 3048 3049 def in_sql(self, expression: exp.In) -> str: 3050 query = expression.args.get("query") 3051 unnest = expression.args.get("unnest") 3052 field = expression.args.get("field") 3053 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3054 3055 if query: 3056 in_sql = self.sql(query) 3057 elif unnest: 3058 in_sql = self.in_unnest_op(unnest) 3059 elif field: 3060 in_sql = self.sql(field) 3061 else: 3062 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3063 3064 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3065 3066 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3067 return f"(SELECT {self.sql(unnest)})" 3068 3069 def interval_sql(self, expression: exp.Interval) -> str: 3070 unit = self.sql(expression, "unit") 3071 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3072 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3073 unit = f" {unit}" if unit else "" 3074 3075 if self.SINGLE_STRING_INTERVAL: 3076 this = expression.this.name if expression.this else "" 3077 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3078 3079 this = self.sql(expression, "this") 3080 if this: 3081 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3082 this = f" {this}" if unwrapped else f" ({this})" 3083 3084 return f"INTERVAL{this}{unit}" 3085 3086 def return_sql(self, expression: exp.Return) -> str: 3087 return f"RETURN {self.sql(expression, 'this')}" 3088 3089 def reference_sql(self, expression: exp.Reference) -> str: 3090 this = self.sql(expression, "this") 3091 expressions = self.expressions(expression, flat=True) 3092 expressions = f"({expressions})" if expressions else "" 3093 options = self.expressions(expression, key="options", flat=True, sep=" ") 3094 options = f" {options}" if options else "" 3095 return f"REFERENCES {this}{expressions}{options}" 3096 3097 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3098 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3099 parent = expression.parent 3100 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3101 return self.func( 3102 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3103 ) 3104 3105 def paren_sql(self, expression: exp.Paren) -> str: 3106 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3107 return f"({sql}{self.seg(')', sep='')}" 3108 3109 def neg_sql(self, expression: exp.Neg) -> str: 3110 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3111 this_sql = self.sql(expression, "this") 3112 sep = " " if this_sql[0] == "-" else "" 3113 return f"-{sep}{this_sql}" 3114 3115 def not_sql(self, expression: exp.Not) -> str: 3116 return f"NOT {self.sql(expression, 'this')}" 3117 3118 def alias_sql(self, expression: exp.Alias) -> str: 3119 alias = self.sql(expression, "alias") 3120 alias = f" AS {alias}" if alias else "" 3121 return f"{self.sql(expression, 'this')}{alias}" 3122 3123 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3124 alias = expression.args["alias"] 3125 3126 parent = expression.parent 3127 pivot = parent and parent.parent 3128 3129 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3130 identifier_alias = isinstance(alias, exp.Identifier) 3131 literal_alias = isinstance(alias, exp.Literal) 3132 3133 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3134 alias.replace(exp.Literal.string(alias.output_name)) 3135 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3136 alias.replace(exp.to_identifier(alias.output_name)) 3137 3138 return self.alias_sql(expression) 3139 3140 def aliases_sql(self, expression: exp.Aliases) -> str: 3141 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3142 3143 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3144 this = self.sql(expression, "this") 3145 index = self.sql(expression, "expression") 3146 return f"{this} AT {index}" 3147 3148 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3149 this = self.sql(expression, "this") 3150 zone = self.sql(expression, "zone") 3151 return f"{this} AT TIME ZONE {zone}" 3152 3153 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3154 this = self.sql(expression, "this") 3155 zone = self.sql(expression, "zone") 3156 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3157 3158 def add_sql(self, expression: exp.Add) -> str: 3159 return self.binary(expression, "+") 3160 3161 def and_sql( 3162 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3163 ) -> str: 3164 return self.connector_sql(expression, "AND", stack) 3165 3166 def or_sql( 3167 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3168 ) -> str: 3169 return self.connector_sql(expression, "OR", stack) 3170 3171 def xor_sql( 3172 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3173 ) -> str: 3174 return self.connector_sql(expression, "XOR", stack) 3175 3176 def connector_sql( 3177 self, 3178 expression: exp.Connector, 3179 op: str, 3180 stack: t.Optional[t.List[str | exp.Expression]] = None, 3181 ) -> str: 3182 if stack is not None: 3183 if expression.expressions: 3184 stack.append(self.expressions(expression, sep=f" {op} ")) 3185 else: 3186 stack.append(expression.right) 3187 if expression.comments and self.comments: 3188 for comment in expression.comments: 3189 if comment: 3190 op += f" /*{self.pad_comment(comment)}*/" 3191 stack.extend((op, expression.left)) 3192 return op 3193 3194 stack = [expression] 3195 sqls: t.List[str] = [] 3196 ops = set() 3197 3198 while stack: 3199 node = stack.pop() 3200 if isinstance(node, exp.Connector): 3201 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3202 else: 3203 sql = self.sql(node) 3204 if sqls and sqls[-1] in ops: 3205 sqls[-1] += f" {sql}" 3206 else: 3207 sqls.append(sql) 3208 3209 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3210 return sep.join(sqls) 3211 3212 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3213 return self.binary(expression, "&") 3214 3215 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3216 return self.binary(expression, "<<") 3217 3218 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3219 return f"~{self.sql(expression, 'this')}" 3220 3221 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3222 return self.binary(expression, "|") 3223 3224 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3225 return self.binary(expression, ">>") 3226 3227 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3228 return self.binary(expression, "^") 3229 3230 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3231 format_sql = self.sql(expression, "format") 3232 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3233 to_sql = self.sql(expression, "to") 3234 to_sql = f" {to_sql}" if to_sql else "" 3235 action = self.sql(expression, "action") 3236 action = f" {action}" if action else "" 3237 default = self.sql(expression, "default") 3238 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3239 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3240 3241 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3242 zone = self.sql(expression, "this") 3243 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3244 3245 def collate_sql(self, expression: exp.Collate) -> str: 3246 if self.COLLATE_IS_FUNC: 3247 return self.function_fallback_sql(expression) 3248 return self.binary(expression, "COLLATE") 3249 3250 def command_sql(self, expression: exp.Command) -> str: 3251 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3252 3253 def comment_sql(self, expression: exp.Comment) -> str: 3254 this = self.sql(expression, "this") 3255 kind = expression.args["kind"] 3256 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3257 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3258 expression_sql = self.sql(expression, "expression") 3259 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3260 3261 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3262 this = self.sql(expression, "this") 3263 delete = " DELETE" if expression.args.get("delete") else "" 3264 recompress = self.sql(expression, "recompress") 3265 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3266 to_disk = self.sql(expression, "to_disk") 3267 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3268 to_volume = self.sql(expression, "to_volume") 3269 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3270 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3271 3272 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3273 where = self.sql(expression, "where") 3274 group = self.sql(expression, "group") 3275 aggregates = self.expressions(expression, key="aggregates") 3276 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3277 3278 if not (where or group or aggregates) and len(expression.expressions) == 1: 3279 return f"TTL {self.expressions(expression, flat=True)}" 3280 3281 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3282 3283 def transaction_sql(self, expression: exp.Transaction) -> str: 3284 return "BEGIN" 3285 3286 def commit_sql(self, expression: exp.Commit) -> str: 3287 chain = expression.args.get("chain") 3288 if chain is not None: 3289 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3290 3291 return f"COMMIT{chain or ''}" 3292 3293 def rollback_sql(self, expression: exp.Rollback) -> str: 3294 savepoint = expression.args.get("savepoint") 3295 savepoint = f" TO {savepoint}" if savepoint else "" 3296 return f"ROLLBACK{savepoint}" 3297 3298 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3299 this = self.sql(expression, "this") 3300 3301 dtype = self.sql(expression, "dtype") 3302 if dtype: 3303 collate = self.sql(expression, "collate") 3304 collate = f" COLLATE {collate}" if collate else "" 3305 using = self.sql(expression, "using") 3306 using = f" USING {using}" if using else "" 3307 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3308 3309 default = self.sql(expression, "default") 3310 if default: 3311 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3312 3313 comment = self.sql(expression, "comment") 3314 if comment: 3315 return f"ALTER COLUMN {this} COMMENT {comment}" 3316 3317 visible = expression.args.get("visible") 3318 if visible: 3319 return f"ALTER COLUMN {this} SET {visible}" 3320 3321 allow_null = expression.args.get("allow_null") 3322 drop = expression.args.get("drop") 3323 3324 if not drop and not allow_null: 3325 self.unsupported("Unsupported ALTER COLUMN syntax") 3326 3327 if allow_null is not None: 3328 keyword = "DROP" if drop else "SET" 3329 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3330 3331 return f"ALTER COLUMN {this} DROP DEFAULT" 3332 3333 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3334 this = self.sql(expression, "this") 3335 3336 visible = expression.args.get("visible") 3337 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3338 3339 return f"ALTER INDEX {this} {visible_sql}" 3340 3341 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3342 this = self.sql(expression, "this") 3343 if not isinstance(expression.this, exp.Var): 3344 this = f"KEY DISTKEY {this}" 3345 return f"ALTER DISTSTYLE {this}" 3346 3347 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3348 compound = " COMPOUND" if expression.args.get("compound") else "" 3349 this = self.sql(expression, "this") 3350 expressions = self.expressions(expression, flat=True) 3351 expressions = f"({expressions})" if expressions else "" 3352 return f"ALTER{compound} SORTKEY {this or expressions}" 3353 3354 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3355 if not self.RENAME_TABLE_WITH_DB: 3356 # Remove db from tables 3357 expression = expression.transform( 3358 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3359 ).assert_is(exp.AlterRename) 3360 this = self.sql(expression, "this") 3361 return f"RENAME TO {this}" 3362 3363 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3364 exists = " IF EXISTS" if expression.args.get("exists") else "" 3365 old_column = self.sql(expression, "this") 3366 new_column = self.sql(expression, "to") 3367 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3368 3369 def alterset_sql(self, expression: exp.AlterSet) -> str: 3370 exprs = self.expressions(expression, flat=True) 3371 return f"SET {exprs}" 3372 3373 def alter_sql(self, expression: exp.Alter) -> str: 3374 actions = expression.args["actions"] 3375 3376 if isinstance(actions[0], exp.ColumnDef): 3377 actions = self.add_column_sql(expression) 3378 elif isinstance(actions[0], exp.Schema): 3379 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3380 elif isinstance(actions[0], exp.Delete): 3381 actions = self.expressions(expression, key="actions", flat=True) 3382 elif isinstance(actions[0], exp.Query): 3383 actions = "AS " + self.expressions(expression, key="actions") 3384 else: 3385 actions = self.expressions(expression, key="actions", flat=True) 3386 3387 exists = " IF EXISTS" if expression.args.get("exists") else "" 3388 on_cluster = self.sql(expression, "cluster") 3389 on_cluster = f" {on_cluster}" if on_cluster else "" 3390 only = " ONLY" if expression.args.get("only") else "" 3391 options = self.expressions(expression, key="options") 3392 options = f", {options}" if options else "" 3393 kind = self.sql(expression, "kind") 3394 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3395 3396 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3397 3398 def add_column_sql(self, expression: exp.Alter) -> str: 3399 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3400 return self.expressions( 3401 expression, 3402 key="actions", 3403 prefix="ADD COLUMN ", 3404 skip_first=True, 3405 ) 3406 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3407 3408 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3409 expressions = self.expressions(expression) 3410 exists = " IF EXISTS " if expression.args.get("exists") else " " 3411 return f"DROP{exists}{expressions}" 3412 3413 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3414 return f"ADD {self.expressions(expression)}" 3415 3416 def distinct_sql(self, expression: exp.Distinct) -> str: 3417 this = self.expressions(expression, flat=True) 3418 3419 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3420 case = exp.case() 3421 for arg in expression.expressions: 3422 case = case.when(arg.is_(exp.null()), exp.null()) 3423 this = self.sql(case.else_(f"({this})")) 3424 3425 this = f" {this}" if this else "" 3426 3427 on = self.sql(expression, "on") 3428 on = f" ON {on}" if on else "" 3429 return f"DISTINCT{this}{on}" 3430 3431 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3432 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3433 3434 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3435 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3436 3437 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3438 this_sql = self.sql(expression, "this") 3439 expression_sql = self.sql(expression, "expression") 3440 kind = "MAX" if expression.args.get("max") else "MIN" 3441 return f"{this_sql} HAVING {kind} {expression_sql}" 3442 3443 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3444 return self.sql( 3445 exp.Cast( 3446 this=exp.Div(this=expression.this, expression=expression.expression), 3447 to=exp.DataType(this=exp.DataType.Type.INT), 3448 ) 3449 ) 3450 3451 def dpipe_sql(self, expression: exp.DPipe) -> str: 3452 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3453 return self.func( 3454 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3455 ) 3456 return self.binary(expression, "||") 3457 3458 def div_sql(self, expression: exp.Div) -> str: 3459 l, r = expression.left, expression.right 3460 3461 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3462 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3463 3464 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3465 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3466 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3467 3468 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3469 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3470 return self.sql( 3471 exp.cast( 3472 l / r, 3473 to=exp.DataType.Type.BIGINT, 3474 ) 3475 ) 3476 3477 return self.binary(expression, "/") 3478 3479 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3480 n = exp._wrap(expression.this, exp.Binary) 3481 d = exp._wrap(expression.expression, exp.Binary) 3482 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3483 3484 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3485 return self.binary(expression, "OVERLAPS") 3486 3487 def distance_sql(self, expression: exp.Distance) -> str: 3488 return self.binary(expression, "<->") 3489 3490 def dot_sql(self, expression: exp.Dot) -> str: 3491 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3492 3493 def eq_sql(self, expression: exp.EQ) -> str: 3494 return self.binary(expression, "=") 3495 3496 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3497 return self.binary(expression, ":=") 3498 3499 def escape_sql(self, expression: exp.Escape) -> str: 3500 return self.binary(expression, "ESCAPE") 3501 3502 def glob_sql(self, expression: exp.Glob) -> str: 3503 return self.binary(expression, "GLOB") 3504 3505 def gt_sql(self, expression: exp.GT) -> str: 3506 return self.binary(expression, ">") 3507 3508 def gte_sql(self, expression: exp.GTE) -> str: 3509 return self.binary(expression, ">=") 3510 3511 def ilike_sql(self, expression: exp.ILike) -> str: 3512 return self.binary(expression, "ILIKE") 3513 3514 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3515 return self.binary(expression, "ILIKE ANY") 3516 3517 def is_sql(self, expression: exp.Is) -> str: 3518 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3519 return self.sql( 3520 expression.this if expression.expression.this else exp.not_(expression.this) 3521 ) 3522 return self.binary(expression, "IS") 3523 3524 def like_sql(self, expression: exp.Like) -> str: 3525 return self.binary(expression, "LIKE") 3526 3527 def likeany_sql(self, expression: exp.LikeAny) -> str: 3528 return self.binary(expression, "LIKE ANY") 3529 3530 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3531 return self.binary(expression, "SIMILAR TO") 3532 3533 def lt_sql(self, expression: exp.LT) -> str: 3534 return self.binary(expression, "<") 3535 3536 def lte_sql(self, expression: exp.LTE) -> str: 3537 return self.binary(expression, "<=") 3538 3539 def mod_sql(self, expression: exp.Mod) -> str: 3540 return self.binary(expression, "%") 3541 3542 def mul_sql(self, expression: exp.Mul) -> str: 3543 return self.binary(expression, "*") 3544 3545 def neq_sql(self, expression: exp.NEQ) -> str: 3546 return self.binary(expression, "<>") 3547 3548 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3549 return self.binary(expression, "IS NOT DISTINCT FROM") 3550 3551 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3552 return self.binary(expression, "IS DISTINCT FROM") 3553 3554 def slice_sql(self, expression: exp.Slice) -> str: 3555 return self.binary(expression, ":") 3556 3557 def sub_sql(self, expression: exp.Sub) -> str: 3558 return self.binary(expression, "-") 3559 3560 def trycast_sql(self, expression: exp.TryCast) -> str: 3561 return self.cast_sql(expression, safe_prefix="TRY_") 3562 3563 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3564 return self.cast_sql(expression) 3565 3566 def try_sql(self, expression: exp.Try) -> str: 3567 if not self.TRY_SUPPORTED: 3568 self.unsupported("Unsupported TRY function") 3569 return self.sql(expression, "this") 3570 3571 return self.func("TRY", expression.this) 3572 3573 def log_sql(self, expression: exp.Log) -> str: 3574 this = expression.this 3575 expr = expression.expression 3576 3577 if self.dialect.LOG_BASE_FIRST is False: 3578 this, expr = expr, this 3579 elif self.dialect.LOG_BASE_FIRST is None and expr: 3580 if this.name in ("2", "10"): 3581 return self.func(f"LOG{this.name}", expr) 3582 3583 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3584 3585 return self.func("LOG", this, expr) 3586 3587 def use_sql(self, expression: exp.Use) -> str: 3588 kind = self.sql(expression, "kind") 3589 kind = f" {kind}" if kind else "" 3590 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3591 this = f" {this}" if this else "" 3592 return f"USE{kind}{this}" 3593 3594 def binary(self, expression: exp.Binary, op: str) -> str: 3595 sqls: t.List[str] = [] 3596 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3597 binary_type = type(expression) 3598 3599 while stack: 3600 node = stack.pop() 3601 3602 if type(node) is binary_type: 3603 op_func = node.args.get("operator") 3604 if op_func: 3605 op = f"OPERATOR({self.sql(op_func)})" 3606 3607 stack.append(node.right) 3608 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3609 stack.append(node.left) 3610 else: 3611 sqls.append(self.sql(node)) 3612 3613 return "".join(sqls) 3614 3615 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3616 to_clause = self.sql(expression, "to") 3617 if to_clause: 3618 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3619 3620 return self.function_fallback_sql(expression) 3621 3622 def function_fallback_sql(self, expression: exp.Func) -> str: 3623 args = [] 3624 3625 for key in expression.arg_types: 3626 arg_value = expression.args.get(key) 3627 3628 if isinstance(arg_value, list): 3629 for value in arg_value: 3630 args.append(value) 3631 elif arg_value is not None: 3632 args.append(arg_value) 3633 3634 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3635 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3636 else: 3637 name = expression.sql_name() 3638 3639 return self.func(name, *args) 3640 3641 def func( 3642 self, 3643 name: str, 3644 *args: t.Optional[exp.Expression | str], 3645 prefix: str = "(", 3646 suffix: str = ")", 3647 normalize: bool = True, 3648 ) -> str: 3649 name = self.normalize_func(name) if normalize else name 3650 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3651 3652 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3653 arg_sqls = tuple( 3654 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3655 ) 3656 if self.pretty and self.too_wide(arg_sqls): 3657 return self.indent( 3658 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3659 ) 3660 return sep.join(arg_sqls) 3661 3662 def too_wide(self, args: t.Iterable) -> bool: 3663 return sum(len(arg) for arg in args) > self.max_text_width 3664 3665 def format_time( 3666 self, 3667 expression: exp.Expression, 3668 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3669 inverse_time_trie: t.Optional[t.Dict] = None, 3670 ) -> t.Optional[str]: 3671 return format_time( 3672 self.sql(expression, "format"), 3673 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3674 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3675 ) 3676 3677 def expressions( 3678 self, 3679 expression: t.Optional[exp.Expression] = None, 3680 key: t.Optional[str] = None, 3681 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3682 flat: bool = False, 3683 indent: bool = True, 3684 skip_first: bool = False, 3685 skip_last: bool = False, 3686 sep: str = ", ", 3687 prefix: str = "", 3688 dynamic: bool = False, 3689 new_line: bool = False, 3690 ) -> str: 3691 expressions = expression.args.get(key or "expressions") if expression else sqls 3692 3693 if not expressions: 3694 return "" 3695 3696 if flat: 3697 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3698 3699 num_sqls = len(expressions) 3700 result_sqls = [] 3701 3702 for i, e in enumerate(expressions): 3703 sql = self.sql(e, comment=False) 3704 if not sql: 3705 continue 3706 3707 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3708 3709 if self.pretty: 3710 if self.leading_comma: 3711 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3712 else: 3713 result_sqls.append( 3714 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3715 ) 3716 else: 3717 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3718 3719 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3720 if new_line: 3721 result_sqls.insert(0, "") 3722 result_sqls.append("") 3723 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3724 else: 3725 result_sql = "".join(result_sqls) 3726 3727 return ( 3728 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3729 if indent 3730 else result_sql 3731 ) 3732 3733 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3734 flat = flat or isinstance(expression.parent, exp.Properties) 3735 expressions_sql = self.expressions(expression, flat=flat) 3736 if flat: 3737 return f"{op} {expressions_sql}" 3738 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3739 3740 def naked_property(self, expression: exp.Property) -> str: 3741 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3742 if not property_name: 3743 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3744 return f"{property_name} {self.sql(expression, 'this')}" 3745 3746 def tag_sql(self, expression: exp.Tag) -> str: 3747 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3748 3749 def token_sql(self, token_type: TokenType) -> str: 3750 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3751 3752 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3753 this = self.sql(expression, "this") 3754 expressions = self.no_identify(self.expressions, expression) 3755 expressions = ( 3756 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3757 ) 3758 return f"{this}{expressions}" if expressions.strip() != "" else this 3759 3760 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3761 this = self.sql(expression, "this") 3762 expressions = self.expressions(expression, flat=True) 3763 return f"{this}({expressions})" 3764 3765 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3766 return self.binary(expression, "=>") 3767 3768 def when_sql(self, expression: exp.When) -> str: 3769 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3770 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3771 condition = self.sql(expression, "condition") 3772 condition = f" AND {condition}" if condition else "" 3773 3774 then_expression = expression.args.get("then") 3775 if isinstance(then_expression, exp.Insert): 3776 this = self.sql(then_expression, "this") 3777 this = f"INSERT {this}" if this else "INSERT" 3778 then = self.sql(then_expression, "expression") 3779 then = f"{this} VALUES {then}" if then else this 3780 elif isinstance(then_expression, exp.Update): 3781 if isinstance(then_expression.args.get("expressions"), exp.Star): 3782 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3783 else: 3784 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3785 else: 3786 then = self.sql(then_expression) 3787 return f"WHEN {matched}{source}{condition} THEN {then}" 3788 3789 def whens_sql(self, expression: exp.Whens) -> str: 3790 return self.expressions(expression, sep=" ", indent=False) 3791 3792 def merge_sql(self, expression: exp.Merge) -> str: 3793 table = expression.this 3794 table_alias = "" 3795 3796 hints = table.args.get("hints") 3797 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3798 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3799 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3800 3801 this = self.sql(table) 3802 using = f"USING {self.sql(expression, 'using')}" 3803 on = f"ON {self.sql(expression, 'on')}" 3804 whens = self.sql(expression, "whens") 3805 3806 returning = self.sql(expression, "returning") 3807 if returning: 3808 whens = f"{whens}{returning}" 3809 3810 sep = self.sep() 3811 3812 return self.prepend_ctes( 3813 expression, 3814 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3815 ) 3816 3817 @unsupported_args("format") 3818 def tochar_sql(self, expression: exp.ToChar) -> str: 3819 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3820 3821 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3822 if not self.SUPPORTS_TO_NUMBER: 3823 self.unsupported("Unsupported TO_NUMBER function") 3824 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3825 3826 fmt = expression.args.get("format") 3827 if not fmt: 3828 self.unsupported("Conversion format is required for TO_NUMBER") 3829 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3830 3831 return self.func("TO_NUMBER", expression.this, fmt) 3832 3833 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3834 this = self.sql(expression, "this") 3835 kind = self.sql(expression, "kind") 3836 settings_sql = self.expressions(expression, key="settings", sep=" ") 3837 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3838 return f"{this}({kind}{args})" 3839 3840 def dictrange_sql(self, expression: exp.DictRange) -> str: 3841 this = self.sql(expression, "this") 3842 max = self.sql(expression, "max") 3843 min = self.sql(expression, "min") 3844 return f"{this}(MIN {min} MAX {max})" 3845 3846 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3847 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3848 3849 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3850 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3851 3852 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3853 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3854 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3855 3856 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3857 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3858 expressions = self.expressions(expression, flat=True) 3859 expressions = f" {self.wrap(expressions)}" if expressions else "" 3860 buckets = self.sql(expression, "buckets") 3861 kind = self.sql(expression, "kind") 3862 buckets = f" BUCKETS {buckets}" if buckets else "" 3863 order = self.sql(expression, "order") 3864 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3865 3866 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3867 return "" 3868 3869 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3870 expressions = self.expressions(expression, key="expressions", flat=True) 3871 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3872 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3873 buckets = self.sql(expression, "buckets") 3874 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3875 3876 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3877 this = self.sql(expression, "this") 3878 having = self.sql(expression, "having") 3879 3880 if having: 3881 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3882 3883 return self.func("ANY_VALUE", this) 3884 3885 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3886 transform = self.func("TRANSFORM", *expression.expressions) 3887 row_format_before = self.sql(expression, "row_format_before") 3888 row_format_before = f" {row_format_before}" if row_format_before else "" 3889 record_writer = self.sql(expression, "record_writer") 3890 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3891 using = f" USING {self.sql(expression, 'command_script')}" 3892 schema = self.sql(expression, "schema") 3893 schema = f" AS {schema}" if schema else "" 3894 row_format_after = self.sql(expression, "row_format_after") 3895 row_format_after = f" {row_format_after}" if row_format_after else "" 3896 record_reader = self.sql(expression, "record_reader") 3897 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3898 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3899 3900 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3901 key_block_size = self.sql(expression, "key_block_size") 3902 if key_block_size: 3903 return f"KEY_BLOCK_SIZE = {key_block_size}" 3904 3905 using = self.sql(expression, "using") 3906 if using: 3907 return f"USING {using}" 3908 3909 parser = self.sql(expression, "parser") 3910 if parser: 3911 return f"WITH PARSER {parser}" 3912 3913 comment = self.sql(expression, "comment") 3914 if comment: 3915 return f"COMMENT {comment}" 3916 3917 visible = expression.args.get("visible") 3918 if visible is not None: 3919 return "VISIBLE" if visible else "INVISIBLE" 3920 3921 engine_attr = self.sql(expression, "engine_attr") 3922 if engine_attr: 3923 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3924 3925 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3926 if secondary_engine_attr: 3927 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3928 3929 self.unsupported("Unsupported index constraint option.") 3930 return "" 3931 3932 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3933 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3934 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3935 3936 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3937 kind = self.sql(expression, "kind") 3938 kind = f"{kind} INDEX" if kind else "INDEX" 3939 this = self.sql(expression, "this") 3940 this = f" {this}" if this else "" 3941 index_type = self.sql(expression, "index_type") 3942 index_type = f" USING {index_type}" if index_type else "" 3943 expressions = self.expressions(expression, flat=True) 3944 expressions = f" ({expressions})" if expressions else "" 3945 options = self.expressions(expression, key="options", sep=" ") 3946 options = f" {options}" if options else "" 3947 return f"{kind}{this}{index_type}{expressions}{options}" 3948 3949 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3950 if self.NVL2_SUPPORTED: 3951 return self.function_fallback_sql(expression) 3952 3953 case = exp.Case().when( 3954 expression.this.is_(exp.null()).not_(copy=False), 3955 expression.args["true"], 3956 copy=False, 3957 ) 3958 else_cond = expression.args.get("false") 3959 if else_cond: 3960 case.else_(else_cond, copy=False) 3961 3962 return self.sql(case) 3963 3964 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3965 this = self.sql(expression, "this") 3966 expr = self.sql(expression, "expression") 3967 iterator = self.sql(expression, "iterator") 3968 condition = self.sql(expression, "condition") 3969 condition = f" IF {condition}" if condition else "" 3970 return f"{this} FOR {expr} IN {iterator}{condition}" 3971 3972 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3973 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3974 3975 def opclass_sql(self, expression: exp.Opclass) -> str: 3976 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3977 3978 def predict_sql(self, expression: exp.Predict) -> str: 3979 model = self.sql(expression, "this") 3980 model = f"MODEL {model}" 3981 table = self.sql(expression, "expression") 3982 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3983 parameters = self.sql(expression, "params_struct") 3984 return self.func("PREDICT", model, table, parameters or None) 3985 3986 def forin_sql(self, expression: exp.ForIn) -> str: 3987 this = self.sql(expression, "this") 3988 expression_sql = self.sql(expression, "expression") 3989 return f"FOR {this} DO {expression_sql}" 3990 3991 def refresh_sql(self, expression: exp.Refresh) -> str: 3992 this = self.sql(expression, "this") 3993 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3994 return f"REFRESH {table}{this}" 3995 3996 def toarray_sql(self, expression: exp.ToArray) -> str: 3997 arg = expression.this 3998 if not arg.type: 3999 from sqlglot.optimizer.annotate_types import annotate_types 4000 4001 arg = annotate_types(arg) 4002 4003 if arg.is_type(exp.DataType.Type.ARRAY): 4004 return self.sql(arg) 4005 4006 cond_for_null = arg.is_(exp.null()) 4007 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4008 4009 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4010 this = expression.this 4011 time_format = self.format_time(expression) 4012 4013 if time_format: 4014 return self.sql( 4015 exp.cast( 4016 exp.StrToTime(this=this, format=expression.args["format"]), 4017 exp.DataType.Type.TIME, 4018 ) 4019 ) 4020 4021 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4022 return self.sql(this) 4023 4024 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4025 4026 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4027 this = expression.this 4028 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4029 return self.sql(this) 4030 4031 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4032 4033 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4034 this = expression.this 4035 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4036 return self.sql(this) 4037 4038 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4039 4040 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4041 this = expression.this 4042 time_format = self.format_time(expression) 4043 4044 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4045 return self.sql( 4046 exp.cast( 4047 exp.StrToTime(this=this, format=expression.args["format"]), 4048 exp.DataType.Type.DATE, 4049 ) 4050 ) 4051 4052 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4053 return self.sql(this) 4054 4055 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4056 4057 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4058 return self.sql( 4059 exp.func( 4060 "DATEDIFF", 4061 expression.this, 4062 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4063 "day", 4064 ) 4065 ) 4066 4067 def lastday_sql(self, expression: exp.LastDay) -> str: 4068 if self.LAST_DAY_SUPPORTS_DATE_PART: 4069 return self.function_fallback_sql(expression) 4070 4071 unit = expression.text("unit") 4072 if unit and unit != "MONTH": 4073 self.unsupported("Date parts are not supported in LAST_DAY.") 4074 4075 return self.func("LAST_DAY", expression.this) 4076 4077 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4078 from sqlglot.dialects.dialect import unit_to_str 4079 4080 return self.func( 4081 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4082 ) 4083 4084 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4085 if self.CAN_IMPLEMENT_ARRAY_ANY: 4086 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4087 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4088 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4089 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4090 4091 from sqlglot.dialects import Dialect 4092 4093 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4094 if self.dialect.__class__ != Dialect: 4095 self.unsupported("ARRAY_ANY is unsupported") 4096 4097 return self.function_fallback_sql(expression) 4098 4099 def struct_sql(self, expression: exp.Struct) -> str: 4100 expression.set( 4101 "expressions", 4102 [ 4103 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4104 if isinstance(e, exp.PropertyEQ) 4105 else e 4106 for e in expression.expressions 4107 ], 4108 ) 4109 4110 return self.function_fallback_sql(expression) 4111 4112 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4113 low = self.sql(expression, "this") 4114 high = self.sql(expression, "expression") 4115 4116 return f"{low} TO {high}" 4117 4118 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4119 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4120 tables = f" {self.expressions(expression)}" 4121 4122 exists = " IF EXISTS" if expression.args.get("exists") else "" 4123 4124 on_cluster = self.sql(expression, "cluster") 4125 on_cluster = f" {on_cluster}" if on_cluster else "" 4126 4127 identity = self.sql(expression, "identity") 4128 identity = f" {identity} IDENTITY" if identity else "" 4129 4130 option = self.sql(expression, "option") 4131 option = f" {option}" if option else "" 4132 4133 partition = self.sql(expression, "partition") 4134 partition = f" {partition}" if partition else "" 4135 4136 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4137 4138 # This transpiles T-SQL's CONVERT function 4139 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4140 def convert_sql(self, expression: exp.Convert) -> str: 4141 to = expression.this 4142 value = expression.expression 4143 style = expression.args.get("style") 4144 safe = expression.args.get("safe") 4145 strict = expression.args.get("strict") 4146 4147 if not to or not value: 4148 return "" 4149 4150 # Retrieve length of datatype and override to default if not specified 4151 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4152 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4153 4154 transformed: t.Optional[exp.Expression] = None 4155 cast = exp.Cast if strict else exp.TryCast 4156 4157 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4158 if isinstance(style, exp.Literal) and style.is_int: 4159 from sqlglot.dialects.tsql import TSQL 4160 4161 style_value = style.name 4162 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4163 if not converted_style: 4164 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4165 4166 fmt = exp.Literal.string(converted_style) 4167 4168 if to.this == exp.DataType.Type.DATE: 4169 transformed = exp.StrToDate(this=value, format=fmt) 4170 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4171 transformed = exp.StrToTime(this=value, format=fmt) 4172 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4173 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4174 elif to.this == exp.DataType.Type.TEXT: 4175 transformed = exp.TimeToStr(this=value, format=fmt) 4176 4177 if not transformed: 4178 transformed = cast(this=value, to=to, safe=safe) 4179 4180 return self.sql(transformed) 4181 4182 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4183 this = expression.this 4184 if isinstance(this, exp.JSONPathWildcard): 4185 this = self.json_path_part(this) 4186 return f".{this}" if this else "" 4187 4188 if exp.SAFE_IDENTIFIER_RE.match(this): 4189 return f".{this}" 4190 4191 this = self.json_path_part(this) 4192 return ( 4193 f"[{this}]" 4194 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4195 else f".{this}" 4196 ) 4197 4198 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4199 this = self.json_path_part(expression.this) 4200 return f"[{this}]" if this else "" 4201 4202 def _simplify_unless_literal(self, expression: E) -> E: 4203 if not isinstance(expression, exp.Literal): 4204 from sqlglot.optimizer.simplify import simplify 4205 4206 expression = simplify(expression, dialect=self.dialect) 4207 4208 return expression 4209 4210 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4211 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4212 # The first modifier here will be the one closest to the AggFunc's arg 4213 mods = sorted( 4214 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4215 key=lambda x: 0 4216 if isinstance(x, exp.HavingMax) 4217 else (1 if isinstance(x, exp.Order) else 2), 4218 ) 4219 4220 if mods: 4221 mod = mods[0] 4222 this = expression.__class__(this=mod.this.copy()) 4223 this.meta["inline"] = True 4224 mod.this.replace(this) 4225 return self.sql(expression.this) 4226 4227 agg_func = expression.find(exp.AggFunc) 4228 4229 if agg_func: 4230 return self.sql(agg_func)[:-1] + f" {text})" 4231 4232 return f"{self.sql(expression, 'this')} {text}" 4233 4234 def _replace_line_breaks(self, string: str) -> str: 4235 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4236 if self.pretty: 4237 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4238 return string 4239 4240 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4241 option = self.sql(expression, "this") 4242 4243 if expression.expressions: 4244 upper = option.upper() 4245 4246 # Snowflake FILE_FORMAT options are separated by whitespace 4247 sep = " " if upper == "FILE_FORMAT" else ", " 4248 4249 # Databricks copy/format options do not set their list of values with EQ 4250 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4251 values = self.expressions(expression, flat=True, sep=sep) 4252 return f"{option}{op}({values})" 4253 4254 value = self.sql(expression, "expression") 4255 4256 if not value: 4257 return option 4258 4259 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4260 4261 return f"{option}{op}{value}" 4262 4263 def credentials_sql(self, expression: exp.Credentials) -> str: 4264 cred_expr = expression.args.get("credentials") 4265 if isinstance(cred_expr, exp.Literal): 4266 # Redshift case: CREDENTIALS <string> 4267 credentials = self.sql(expression, "credentials") 4268 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4269 else: 4270 # Snowflake case: CREDENTIALS = (...) 4271 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4272 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4273 4274 storage = self.sql(expression, "storage") 4275 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4276 4277 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4278 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4279 4280 iam_role = self.sql(expression, "iam_role") 4281 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4282 4283 region = self.sql(expression, "region") 4284 region = f" REGION {region}" if region else "" 4285 4286 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4287 4288 def copy_sql(self, expression: exp.Copy) -> str: 4289 this = self.sql(expression, "this") 4290 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4291 4292 credentials = self.sql(expression, "credentials") 4293 credentials = self.seg(credentials) if credentials else "" 4294 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4295 files = self.expressions(expression, key="files", flat=True) 4296 4297 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4298 params = self.expressions( 4299 expression, 4300 key="params", 4301 sep=sep, 4302 new_line=True, 4303 skip_last=True, 4304 skip_first=True, 4305 indent=self.COPY_PARAMS_ARE_WRAPPED, 4306 ) 4307 4308 if params: 4309 if self.COPY_PARAMS_ARE_WRAPPED: 4310 params = f" WITH ({params})" 4311 elif not self.pretty: 4312 params = f" {params}" 4313 4314 return f"COPY{this}{kind} {files}{credentials}{params}" 4315 4316 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4317 return "" 4318 4319 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4320 on_sql = "ON" if expression.args.get("on") else "OFF" 4321 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4322 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4323 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4324 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4325 4326 if filter_col or retention_period: 4327 on_sql = self.func("ON", filter_col, retention_period) 4328 4329 return f"DATA_DELETION={on_sql}" 4330 4331 def maskingpolicycolumnconstraint_sql( 4332 self, expression: exp.MaskingPolicyColumnConstraint 4333 ) -> str: 4334 this = self.sql(expression, "this") 4335 expressions = self.expressions(expression, flat=True) 4336 expressions = f" USING ({expressions})" if expressions else "" 4337 return f"MASKING POLICY {this}{expressions}" 4338 4339 def gapfill_sql(self, expression: exp.GapFill) -> str: 4340 this = self.sql(expression, "this") 4341 this = f"TABLE {this}" 4342 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4343 4344 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4345 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4346 4347 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4348 this = self.sql(expression, "this") 4349 expr = expression.expression 4350 4351 if isinstance(expr, exp.Func): 4352 # T-SQL's CLR functions are case sensitive 4353 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4354 else: 4355 expr = self.sql(expression, "expression") 4356 4357 return self.scope_resolution(expr, this) 4358 4359 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4360 if self.PARSE_JSON_NAME is None: 4361 return self.sql(expression.this) 4362 4363 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4364 4365 def rand_sql(self, expression: exp.Rand) -> str: 4366 lower = self.sql(expression, "lower") 4367 upper = self.sql(expression, "upper") 4368 4369 if lower and upper: 4370 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4371 return self.func("RAND", expression.this) 4372 4373 def changes_sql(self, expression: exp.Changes) -> str: 4374 information = self.sql(expression, "information") 4375 information = f"INFORMATION => {information}" 4376 at_before = self.sql(expression, "at_before") 4377 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4378 end = self.sql(expression, "end") 4379 end = f"{self.seg('')}{end}" if end else "" 4380 4381 return f"CHANGES ({information}){at_before}{end}" 4382 4383 def pad_sql(self, expression: exp.Pad) -> str: 4384 prefix = "L" if expression.args.get("is_left") else "R" 4385 4386 fill_pattern = self.sql(expression, "fill_pattern") or None 4387 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4388 fill_pattern = "' '" 4389 4390 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4391 4392 def summarize_sql(self, expression: exp.Summarize) -> str: 4393 table = " TABLE" if expression.args.get("table") else "" 4394 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4395 4396 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4397 generate_series = exp.GenerateSeries(**expression.args) 4398 4399 parent = expression.parent 4400 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4401 parent = parent.parent 4402 4403 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4404 return self.sql(exp.Unnest(expressions=[generate_series])) 4405 4406 if isinstance(parent, exp.Select): 4407 self.unsupported("GenerateSeries projection unnesting is not supported.") 4408 4409 return self.sql(generate_series) 4410 4411 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4412 exprs = expression.expressions 4413 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4414 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4415 else: 4416 rhs = self.expressions(expression) 4417 4418 return self.func(name, expression.this, rhs or None) 4419 4420 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4421 if self.SUPPORTS_CONVERT_TIMEZONE: 4422 return self.function_fallback_sql(expression) 4423 4424 source_tz = expression.args.get("source_tz") 4425 target_tz = expression.args.get("target_tz") 4426 timestamp = expression.args.get("timestamp") 4427 4428 if source_tz and timestamp: 4429 timestamp = exp.AtTimeZone( 4430 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4431 ) 4432 4433 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4434 4435 return self.sql(expr) 4436 4437 def json_sql(self, expression: exp.JSON) -> str: 4438 this = self.sql(expression, "this") 4439 this = f" {this}" if this else "" 4440 4441 _with = expression.args.get("with") 4442 4443 if _with is None: 4444 with_sql = "" 4445 elif not _with: 4446 with_sql = " WITHOUT" 4447 else: 4448 with_sql = " WITH" 4449 4450 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4451 4452 return f"JSON{this}{with_sql}{unique_sql}" 4453 4454 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4455 def _generate_on_options(arg: t.Any) -> str: 4456 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4457 4458 path = self.sql(expression, "path") 4459 returning = self.sql(expression, "returning") 4460 returning = f" RETURNING {returning}" if returning else "" 4461 4462 on_condition = self.sql(expression, "on_condition") 4463 on_condition = f" {on_condition}" if on_condition else "" 4464 4465 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4466 4467 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4468 else_ = "ELSE " if expression.args.get("else_") else "" 4469 condition = self.sql(expression, "expression") 4470 condition = f"WHEN {condition} THEN " if condition else else_ 4471 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4472 return f"{condition}{insert}" 4473 4474 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4475 kind = self.sql(expression, "kind") 4476 expressions = self.seg(self.expressions(expression, sep=" ")) 4477 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4478 return res 4479 4480 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4481 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4482 empty = expression.args.get("empty") 4483 empty = ( 4484 f"DEFAULT {empty} ON EMPTY" 4485 if isinstance(empty, exp.Expression) 4486 else self.sql(expression, "empty") 4487 ) 4488 4489 error = expression.args.get("error") 4490 error = ( 4491 f"DEFAULT {error} ON ERROR" 4492 if isinstance(error, exp.Expression) 4493 else self.sql(expression, "error") 4494 ) 4495 4496 if error and empty: 4497 error = ( 4498 f"{empty} {error}" 4499 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4500 else f"{error} {empty}" 4501 ) 4502 empty = "" 4503 4504 null = self.sql(expression, "null") 4505 4506 return f"{empty}{error}{null}" 4507 4508 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4509 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4510 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4511 4512 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4513 this = self.sql(expression, "this") 4514 path = self.sql(expression, "path") 4515 4516 passing = self.expressions(expression, "passing") 4517 passing = f" PASSING {passing}" if passing else "" 4518 4519 on_condition = self.sql(expression, "on_condition") 4520 on_condition = f" {on_condition}" if on_condition else "" 4521 4522 path = f"{path}{passing}{on_condition}" 4523 4524 return self.func("JSON_EXISTS", this, path) 4525 4526 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4527 array_agg = self.function_fallback_sql(expression) 4528 4529 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4530 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4531 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4532 parent = expression.parent 4533 if isinstance(parent, exp.Filter): 4534 parent_cond = parent.expression.this 4535 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4536 else: 4537 this = expression.this 4538 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4539 if this.find(exp.Column): 4540 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4541 this_sql = ( 4542 self.expressions(this) 4543 if isinstance(this, exp.Distinct) 4544 else self.sql(expression, "this") 4545 ) 4546 4547 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4548 4549 return array_agg 4550 4551 def apply_sql(self, expression: exp.Apply) -> str: 4552 this = self.sql(expression, "this") 4553 expr = self.sql(expression, "expression") 4554 4555 return f"{this} APPLY({expr})" 4556 4557 def grant_sql(self, expression: exp.Grant) -> str: 4558 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4559 4560 kind = self.sql(expression, "kind") 4561 kind = f" {kind}" if kind else "" 4562 4563 securable = self.sql(expression, "securable") 4564 securable = f" {securable}" if securable else "" 4565 4566 principals = self.expressions(expression, key="principals", flat=True) 4567 4568 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4569 4570 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4571 4572 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4573 this = self.sql(expression, "this") 4574 columns = self.expressions(expression, flat=True) 4575 columns = f"({columns})" if columns else "" 4576 4577 return f"{this}{columns}" 4578 4579 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4580 this = self.sql(expression, "this") 4581 4582 kind = self.sql(expression, "kind") 4583 kind = f"{kind} " if kind else "" 4584 4585 return f"{kind}{this}" 4586 4587 def columns_sql(self, expression: exp.Columns): 4588 func = self.function_fallback_sql(expression) 4589 if expression.args.get("unpack"): 4590 func = f"*{func}" 4591 4592 return func 4593 4594 def overlay_sql(self, expression: exp.Overlay): 4595 this = self.sql(expression, "this") 4596 expr = self.sql(expression, "expression") 4597 from_sql = self.sql(expression, "from") 4598 for_sql = self.sql(expression, "for") 4599 for_sql = f" FOR {for_sql}" if for_sql else "" 4600 4601 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4602 4603 @unsupported_args("format") 4604 def todouble_sql(self, expression: exp.ToDouble) -> str: 4605 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4606 4607 def string_sql(self, expression: exp.String) -> str: 4608 this = expression.this 4609 zone = expression.args.get("zone") 4610 4611 if zone: 4612 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4613 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4614 # set for source_tz to transpile the time conversion before the STRING cast 4615 this = exp.ConvertTimezone( 4616 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4617 ) 4618 4619 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4620 4621 def median_sql(self, expression: exp.Median): 4622 if not self.SUPPORTS_MEDIAN: 4623 return self.sql( 4624 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4625 ) 4626 4627 return self.function_fallback_sql(expression) 4628 4629 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4630 filler = self.sql(expression, "this") 4631 filler = f" {filler}" if filler else "" 4632 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4633 return f"TRUNCATE{filler} {with_count}" 4634 4635 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4636 if self.SUPPORTS_UNIX_SECONDS: 4637 return self.function_fallback_sql(expression) 4638 4639 start_ts = exp.cast( 4640 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4641 ) 4642 4643 return self.sql( 4644 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4645 ) 4646 4647 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4648 dim = expression.expression 4649 4650 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4651 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4652 if not (dim.is_int and dim.name == "1"): 4653 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4654 dim = None 4655 4656 # If dimension is required but not specified, default initialize it 4657 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4658 dim = exp.Literal.number(1) 4659 4660 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4661 4662 def attach_sql(self, expression: exp.Attach) -> str: 4663 this = self.sql(expression, "this") 4664 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4665 expressions = self.expressions(expression) 4666 expressions = f" ({expressions})" if expressions else "" 4667 4668 return f"ATTACH{exists_sql} {this}{expressions}" 4669 4670 def detach_sql(self, expression: exp.Detach) -> str: 4671 this = self.sql(expression, "this") 4672 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4673 4674 return f"DETACH{exists_sql} {this}" 4675 4676 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4677 this = self.sql(expression, "this") 4678 value = self.sql(expression, "expression") 4679 value = f" {value}" if value else "" 4680 return f"{this}{value}" 4681 4682 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4683 this_sql = self.sql(expression, "this") 4684 if isinstance(expression.this, exp.Table): 4685 this_sql = f"TABLE {this_sql}" 4686 4687 return self.func( 4688 "FEATURES_AT_TIME", 4689 this_sql, 4690 expression.args.get("time"), 4691 expression.args.get("num_rows"), 4692 expression.args.get("ignore_feature_nulls"), 4693 ) 4694 4695 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4696 return ( 4697 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4698 ) 4699 4700 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4701 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4702 encode = f"{encode} {self.sql(expression, 'this')}" 4703 4704 properties = expression.args.get("properties") 4705 if properties: 4706 encode = f"{encode} {self.properties(properties)}" 4707 4708 return encode 4709 4710 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4711 this = self.sql(expression, "this") 4712 include = f"INCLUDE {this}" 4713 4714 column_def = self.sql(expression, "column_def") 4715 if column_def: 4716 include = f"{include} {column_def}" 4717 4718 alias = self.sql(expression, "alias") 4719 if alias: 4720 include = f"{include} AS {alias}" 4721 4722 return include 4723 4724 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4725 name = f"NAME {self.sql(expression, 'this')}" 4726 return self.func("XMLELEMENT", name, *expression.expressions) 4727 4728 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4729 partitions = self.expressions(expression, "partition_expressions") 4730 create = self.expressions(expression, "create_expressions") 4731 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4732 4733 def partitionbyrangepropertydynamic_sql( 4734 self, expression: exp.PartitionByRangePropertyDynamic 4735 ) -> str: 4736 start = self.sql(expression, "start") 4737 end = self.sql(expression, "end") 4738 4739 every = expression.args["every"] 4740 if isinstance(every, exp.Interval) and every.this.is_string: 4741 every.this.replace(exp.Literal.number(every.name)) 4742 4743 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4744 4745 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4746 name = self.sql(expression, "this") 4747 values = self.expressions(expression, flat=True) 4748 4749 return f"NAME {name} VALUE {values}" 4750 4751 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4752 kind = self.sql(expression, "kind") 4753 sample = self.sql(expression, "sample") 4754 return f"SAMPLE {sample} {kind}" 4755 4756 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4757 kind = self.sql(expression, "kind") 4758 option = self.sql(expression, "option") 4759 option = f" {option}" if option else "" 4760 this = self.sql(expression, "this") 4761 this = f" {this}" if this else "" 4762 columns = self.expressions(expression) 4763 columns = f" {columns}" if columns else "" 4764 return f"{kind}{option} STATISTICS{this}{columns}" 4765 4766 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4767 this = self.sql(expression, "this") 4768 columns = self.expressions(expression) 4769 inner_expression = self.sql(expression, "expression") 4770 inner_expression = f" {inner_expression}" if inner_expression else "" 4771 update_options = self.sql(expression, "update_options") 4772 update_options = f" {update_options} UPDATE" if update_options else "" 4773 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4774 4775 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4776 kind = self.sql(expression, "kind") 4777 kind = f" {kind}" if kind else "" 4778 return f"DELETE{kind} STATISTICS" 4779 4780 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4781 inner_expression = self.sql(expression, "expression") 4782 return f"LIST CHAINED ROWS{inner_expression}" 4783 4784 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4785 kind = self.sql(expression, "kind") 4786 this = self.sql(expression, "this") 4787 this = f" {this}" if this else "" 4788 inner_expression = self.sql(expression, "expression") 4789 return f"VALIDATE {kind}{this}{inner_expression}" 4790 4791 def analyze_sql(self, expression: exp.Analyze) -> str: 4792 options = self.expressions(expression, key="options", sep=" ") 4793 options = f" {options}" if options else "" 4794 kind = self.sql(expression, "kind") 4795 kind = f" {kind}" if kind else "" 4796 this = self.sql(expression, "this") 4797 this = f" {this}" if this else "" 4798 mode = self.sql(expression, "mode") 4799 mode = f" {mode}" if mode else "" 4800 properties = self.sql(expression, "properties") 4801 properties = f" {properties}" if properties else "" 4802 partition = self.sql(expression, "partition") 4803 partition = f" {partition}" if partition else "" 4804 inner_expression = self.sql(expression, "expression") 4805 inner_expression = f" {inner_expression}" if inner_expression else "" 4806 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4807 4808 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4809 this = self.sql(expression, "this") 4810 namespaces = self.expressions(expression, key="namespaces") 4811 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4812 passing = self.expressions(expression, key="passing") 4813 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4814 columns = self.expressions(expression, key="columns") 4815 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4816 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4817 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4818 4819 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4820 this = self.sql(expression, "this") 4821 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4822 4823 def export_sql(self, expression: exp.Export) -> str: 4824 this = self.sql(expression, "this") 4825 connection = self.sql(expression, "connection") 4826 connection = f"WITH CONNECTION {connection} " if connection else "" 4827 options = self.sql(expression, "options") 4828 return f"EXPORT DATA {connection}{options} AS {this}" 4829 4830 def declare_sql(self, expression: exp.Declare) -> str: 4831 return f"DECLARE {self.expressions(expression, flat=True)}" 4832 4833 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4834 variable = self.sql(expression, "this") 4835 default = self.sql(expression, "default") 4836 default = f" = {default}" if default else "" 4837 4838 kind = self.sql(expression, "kind") 4839 if isinstance(expression.args.get("kind"), exp.Schema): 4840 kind = f"TABLE {kind}" 4841 4842 return f"{variable} AS {kind}{default}" 4843 4844 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4845 kind = self.sql(expression, "kind") 4846 this = self.sql(expression, "this") 4847 set = self.sql(expression, "expression") 4848 using = self.sql(expression, "using") 4849 using = f" USING {using}" if using else "" 4850 4851 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4852 4853 return f"{kind_sql} {this} SET {set}{using}" 4854 4855 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4856 params = self.expressions(expression, key="params", flat=True) 4857 return self.func(expression.name, *expression.expressions) + f"({params})" 4858 4859 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4860 return self.func(expression.name, *expression.expressions) 4861 4862 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4863 return self.anonymousaggfunc_sql(expression) 4864 4865 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4866 return self.parameterizedagg_sql(expression) 4867 4868 def show_sql(self, expression: exp.Show) -> str: 4869 self.unsupported("Unsupported SHOW statement") 4870 return "" 4871 4872 def put_sql(self, expression: exp.Put) -> str: 4873 props = expression.args.get("properties") 4874 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4875 this = self.sql(expression, "this") 4876 target = self.sql(expression, "target") 4877 return f"PUT {this} {target}{props_sql}"
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)
681 def __init__( 682 self, 683 pretty: t.Optional[bool] = None, 684 identify: str | bool = False, 685 normalize: bool = False, 686 pad: int = 2, 687 indent: int = 2, 688 normalize_functions: t.Optional[str | bool] = None, 689 unsupported_level: ErrorLevel = ErrorLevel.WARN, 690 max_unsupported: int = 3, 691 leading_comma: bool = False, 692 max_text_width: int = 80, 693 comments: bool = True, 694 dialect: DialectType = None, 695 ): 696 import sqlglot 697 from sqlglot.dialects import Dialect 698 699 self.pretty = pretty if pretty is not None else sqlglot.pretty 700 self.identify = identify 701 self.normalize = normalize 702 self.pad = pad 703 self._indent = indent 704 self.unsupported_level = unsupported_level 705 self.max_unsupported = max_unsupported 706 self.leading_comma = leading_comma 707 self.max_text_width = max_text_width 708 self.comments = comments 709 self.dialect = Dialect.get_or_raise(dialect) 710 711 # This is both a Dialect property and a Generator argument, so we prioritize the latter 712 self.normalize_functions = ( 713 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 714 ) 715 716 self.unsupported_messages: t.List[str] = [] 717 self._escaped_quote_end: str = ( 718 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 719 ) 720 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 721 722 self._next_name = name_sequence("_t") 723 724 self._identifier_start = self.dialect.IDENTIFIER_START 725 self._identifier_end = self.dialect.IDENTIFIER_END 726 727 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.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ForceProperty'>: <function Generator.<lambda>>}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.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.BLOB: 'BLOB'>: 'VARBINARY', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS =
{'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS =
{'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StorageHandlerProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.UsingTemplateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ForceProperty'>: <Location.POST_CREATE: 'POST_CREATE'>}
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES =
{<Type.VARCHAR: 'VARCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>}
729 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 730 """ 731 Generates the SQL string corresponding to the given syntax tree. 732 733 Args: 734 expression: The syntax tree. 735 copy: Whether to copy the expression. The generator performs mutations so 736 it is safer to copy. 737 738 Returns: 739 The SQL string corresponding to `expression`. 740 """ 741 if copy: 742 expression = expression.copy() 743 744 expression = self.preprocess(expression) 745 746 self.unsupported_messages = [] 747 sql = self.sql(expression).strip() 748 749 if self.pretty: 750 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 751 752 if self.unsupported_level == ErrorLevel.IGNORE: 753 return sql 754 755 if self.unsupported_level == ErrorLevel.WARN: 756 for msg in self.unsupported_messages: 757 logger.warning(msg) 758 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 759 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 760 761 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:
763 def preprocess(self, expression: exp.Expression) -> exp.Expression: 764 """Apply generic preprocessing transformations to a given expression.""" 765 expression = self._move_ctes_to_top_level(expression) 766 767 if self.ENSURE_BOOLS: 768 from sqlglot.transforms import ensure_bools 769 770 expression = ensure_bools(expression) 771 772 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:
801 def maybe_comment( 802 self, 803 sql: str, 804 expression: t.Optional[exp.Expression] = None, 805 comments: t.Optional[t.List[str]] = None, 806 separated: bool = False, 807 ) -> str: 808 comments = ( 809 ((expression and expression.comments) if comments is None else comments) # type: ignore 810 if self.comments 811 else None 812 ) 813 814 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 815 return sql 816 817 comments_sql = " ".join( 818 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 819 ) 820 821 if not comments_sql: 822 return sql 823 824 comments_sql = self._replace_line_breaks(comments_sql) 825 826 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 827 return ( 828 f"{self.sep()}{comments_sql}{sql}" 829 if not sql or sql[0].isspace() 830 else f"{comments_sql}{self.sep()}{sql}" 831 ) 832 833 return f"{sql} {comments_sql}"
835 def wrap(self, expression: exp.Expression | str) -> str: 836 this_sql = ( 837 self.sql(expression) 838 if isinstance(expression, exp.UNWRAPPED_QUERIES) 839 else self.sql(expression, "this") 840 ) 841 if not this_sql: 842 return "()" 843 844 this_sql = self.indent(this_sql, level=1, pad=0) 845 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:
861 def indent( 862 self, 863 sql: str, 864 level: int = 0, 865 pad: t.Optional[int] = None, 866 skip_first: bool = False, 867 skip_last: bool = False, 868 ) -> str: 869 if not self.pretty or not sql: 870 return sql 871 872 pad = self.pad if pad is None else pad 873 lines = sql.split("\n") 874 875 return "\n".join( 876 ( 877 line 878 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 879 else f"{' ' * (level * self._indent + pad)}{line}" 880 ) 881 for i, line in enumerate(lines) 882 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
884 def sql( 885 self, 886 expression: t.Optional[str | exp.Expression], 887 key: t.Optional[str] = None, 888 comment: bool = True, 889 ) -> str: 890 if not expression: 891 return "" 892 893 if isinstance(expression, str): 894 return expression 895 896 if key: 897 value = expression.args.get(key) 898 if value: 899 return self.sql(value) 900 return "" 901 902 transform = self.TRANSFORMS.get(expression.__class__) 903 904 if callable(transform): 905 sql = transform(self, expression) 906 elif isinstance(expression, exp.Expression): 907 exp_handler_name = f"{expression.key}_sql" 908 909 if hasattr(self, exp_handler_name): 910 sql = getattr(self, exp_handler_name)(expression) 911 elif isinstance(expression, exp.Func): 912 sql = self.function_fallback_sql(expression) 913 elif isinstance(expression, exp.Property): 914 sql = self.property_sql(expression) 915 else: 916 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 917 else: 918 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 919 920 return self.maybe_comment(sql, expression) if self.comments and comment else sql
927 def cache_sql(self, expression: exp.Cache) -> str: 928 lazy = " LAZY" if expression.args.get("lazy") else "" 929 table = self.sql(expression, "this") 930 options = expression.args.get("options") 931 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 932 sql = self.sql(expression, "expression") 933 sql = f" AS{self.sep()}{sql}" if sql else "" 934 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 935 return self.prepend_ctes(expression, sql)
937 def characterset_sql(self, expression: exp.CharacterSet) -> str: 938 if isinstance(expression.parent, exp.Cast): 939 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 940 default = "DEFAULT " if expression.args.get("default") else "" 941 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
955 def column_sql(self, expression: exp.Column) -> str: 956 join_mark = " (+)" if expression.args.get("join_mark") else "" 957 958 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 959 join_mark = "" 960 self.unsupported("Outer join syntax using the (+) operator is not supported.") 961 962 return f"{self.column_parts(expression)}{join_mark}"
970 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 971 column = self.sql(expression, "this") 972 kind = self.sql(expression, "kind") 973 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 974 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 975 kind = f"{sep}{kind}" if kind else "" 976 constraints = f" {constraints}" if constraints else "" 977 position = self.sql(expression, "position") 978 position = f" {position}" if position else "" 979 980 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 981 kind = "" 982 983 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
990 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 991 this = self.sql(expression, "this") 992 if expression.args.get("not_null"): 993 persisted = " PERSISTED NOT NULL" 994 elif expression.args.get("persisted"): 995 persisted = " PERSISTED" 996 else: 997 persisted = "" 998 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1011 def generatedasidentitycolumnconstraint_sql( 1012 self, expression: exp.GeneratedAsIdentityColumnConstraint 1013 ) -> str: 1014 this = "" 1015 if expression.this is not None: 1016 on_null = " ON NULL" if expression.args.get("on_null") else "" 1017 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1018 1019 start = expression.args.get("start") 1020 start = f"START WITH {start}" if start else "" 1021 increment = expression.args.get("increment") 1022 increment = f" INCREMENT BY {increment}" if increment else "" 1023 minvalue = expression.args.get("minvalue") 1024 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1025 maxvalue = expression.args.get("maxvalue") 1026 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1027 cycle = expression.args.get("cycle") 1028 cycle_sql = "" 1029 1030 if cycle is not None: 1031 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1032 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1033 1034 sequence_opts = "" 1035 if start or increment or cycle_sql: 1036 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1037 sequence_opts = f" ({sequence_opts.strip()})" 1038 1039 expr = self.sql(expression, "expression") 1040 expr = f"({expr})" if expr else "IDENTITY" 1041 1042 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1044 def generatedasrowcolumnconstraint_sql( 1045 self, expression: exp.GeneratedAsRowColumnConstraint 1046 ) -> str: 1047 start = "START" if expression.args.get("start") else "END" 1048 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1049 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:
1068 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1069 this = self.sql(expression, "this") 1070 this = f" {this}" if this else "" 1071 index_type = expression.args.get("index_type") 1072 index_type = f" USING {index_type}" if index_type else "" 1073 on_conflict = self.sql(expression, "on_conflict") 1074 on_conflict = f" {on_conflict}" if on_conflict else "" 1075 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1076 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1081 def create_sql(self, expression: exp.Create) -> str: 1082 kind = self.sql(expression, "kind") 1083 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1084 properties = expression.args.get("properties") 1085 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1086 1087 this = self.createable_sql(expression, properties_locs) 1088 1089 properties_sql = "" 1090 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1091 exp.Properties.Location.POST_WITH 1092 ): 1093 properties_sql = self.sql( 1094 exp.Properties( 1095 expressions=[ 1096 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1097 *properties_locs[exp.Properties.Location.POST_WITH], 1098 ] 1099 ) 1100 ) 1101 1102 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1103 properties_sql = self.sep() + properties_sql 1104 elif not self.pretty: 1105 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1106 properties_sql = f" {properties_sql}" 1107 1108 begin = " BEGIN" if expression.args.get("begin") else "" 1109 end = " END" if expression.args.get("end") else "" 1110 1111 expression_sql = self.sql(expression, "expression") 1112 if expression_sql: 1113 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1114 1115 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1116 postalias_props_sql = "" 1117 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1118 postalias_props_sql = self.properties( 1119 exp.Properties( 1120 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1121 ), 1122 wrapped=False, 1123 ) 1124 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1125 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1126 1127 postindex_props_sql = "" 1128 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1129 postindex_props_sql = self.properties( 1130 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1131 wrapped=False, 1132 prefix=" ", 1133 ) 1134 1135 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1136 indexes = f" {indexes}" if indexes else "" 1137 index_sql = indexes + postindex_props_sql 1138 1139 replace = " OR REPLACE" if expression.args.get("replace") else "" 1140 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1141 unique = " UNIQUE" if expression.args.get("unique") else "" 1142 1143 clustered = expression.args.get("clustered") 1144 if clustered is None: 1145 clustered_sql = "" 1146 elif clustered: 1147 clustered_sql = " CLUSTERED COLUMNSTORE" 1148 else: 1149 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1150 1151 postcreate_props_sql = "" 1152 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1153 postcreate_props_sql = self.properties( 1154 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1155 sep=" ", 1156 prefix=" ", 1157 wrapped=False, 1158 ) 1159 1160 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1161 1162 postexpression_props_sql = "" 1163 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1164 postexpression_props_sql = self.properties( 1165 exp.Properties( 1166 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1167 ), 1168 sep=" ", 1169 prefix=" ", 1170 wrapped=False, 1171 ) 1172 1173 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1174 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1175 no_schema_binding = ( 1176 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1177 ) 1178 1179 clone = self.sql(expression, "clone") 1180 clone = f" {clone}" if clone else "" 1181 1182 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1183 properties_expression = f"{expression_sql}{properties_sql}" 1184 else: 1185 properties_expression = f"{properties_sql}{expression_sql}" 1186 1187 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1188 return self.prepend_ctes(expression, expression_sql)
1190 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1191 start = self.sql(expression, "start") 1192 start = f"START WITH {start}" if start else "" 1193 increment = self.sql(expression, "increment") 1194 increment = f" INCREMENT BY {increment}" if increment else "" 1195 minvalue = self.sql(expression, "minvalue") 1196 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1197 maxvalue = self.sql(expression, "maxvalue") 1198 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1199 owned = self.sql(expression, "owned") 1200 owned = f" OWNED BY {owned}" if owned else "" 1201 1202 cache = expression.args.get("cache") 1203 if cache is None: 1204 cache_str = "" 1205 elif cache is True: 1206 cache_str = " CACHE" 1207 else: 1208 cache_str = f" CACHE {cache}" 1209 1210 options = self.expressions(expression, key="options", flat=True, sep=" ") 1211 options = f" {options}" if options else "" 1212 1213 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1215 def clone_sql(self, expression: exp.Clone) -> str: 1216 this = self.sql(expression, "this") 1217 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1218 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1219 return f"{shallow}{keyword} {this}"
1221 def describe_sql(self, expression: exp.Describe) -> str: 1222 style = expression.args.get("style") 1223 style = f" {style}" if style else "" 1224 partition = self.sql(expression, "partition") 1225 partition = f" {partition}" if partition else "" 1226 format = self.sql(expression, "format") 1227 format = f" {format}" if format else "" 1228 1229 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1241 def with_sql(self, expression: exp.With) -> str: 1242 sql = self.expressions(expression, flat=True) 1243 recursive = ( 1244 "RECURSIVE " 1245 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1246 else "" 1247 ) 1248 search = self.sql(expression, "search") 1249 search = f" {search}" if search else "" 1250 1251 return f"WITH {recursive}{sql}{search}"
1253 def cte_sql(self, expression: exp.CTE) -> str: 1254 alias = expression.args.get("alias") 1255 if alias: 1256 alias.add_comments(expression.pop_comments()) 1257 1258 alias_sql = self.sql(expression, "alias") 1259 1260 materialized = expression.args.get("materialized") 1261 if materialized is False: 1262 materialized = "NOT MATERIALIZED " 1263 elif materialized: 1264 materialized = "MATERIALIZED " 1265 1266 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1268 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1269 alias = self.sql(expression, "this") 1270 columns = self.expressions(expression, key="columns", flat=True) 1271 columns = f"({columns})" if columns else "" 1272 1273 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1274 columns = "" 1275 self.unsupported("Named columns are not supported in table alias.") 1276 1277 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1278 alias = self._next_name() 1279 1280 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1288 def hexstring_sql( 1289 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1290 ) -> str: 1291 this = self.sql(expression, "this") 1292 is_integer_type = expression.args.get("is_integer") 1293 1294 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1295 not self.dialect.HEX_START and not binary_function_repr 1296 ): 1297 # Integer representation will be returned if: 1298 # - The read dialect treats the hex value as integer literal but not the write 1299 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1300 return f"{int(this, 16)}" 1301 1302 if not is_integer_type: 1303 # Read dialect treats the hex value as BINARY/BLOB 1304 if binary_function_repr: 1305 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1306 return self.func(binary_function_repr, exp.Literal.string(this)) 1307 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1308 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1309 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1310 1311 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1319 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1320 this = self.sql(expression, "this") 1321 escape = expression.args.get("escape") 1322 1323 if self.dialect.UNICODE_START: 1324 escape_substitute = r"\\\1" 1325 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1326 else: 1327 escape_substitute = r"\\u\1" 1328 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1329 1330 if escape: 1331 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1332 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1333 else: 1334 escape_pattern = ESCAPED_UNICODE_RE 1335 escape_sql = "" 1336 1337 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1338 this = escape_pattern.sub(escape_substitute, this) 1339 1340 return f"{left_quote}{this}{right_quote}{escape_sql}"
1352 def datatype_sql(self, expression: exp.DataType) -> str: 1353 nested = "" 1354 values = "" 1355 interior = self.expressions(expression, flat=True) 1356 1357 type_value = expression.this 1358 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1359 type_sql = self.sql(expression, "kind") 1360 else: 1361 type_sql = ( 1362 self.TYPE_MAPPING.get(type_value, type_value.value) 1363 if isinstance(type_value, exp.DataType.Type) 1364 else type_value 1365 ) 1366 1367 if interior: 1368 if expression.args.get("nested"): 1369 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1370 if expression.args.get("values") is not None: 1371 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1372 values = self.expressions(expression, key="values", flat=True) 1373 values = f"{delimiters[0]}{values}{delimiters[1]}" 1374 elif type_value == exp.DataType.Type.INTERVAL: 1375 nested = f" {interior}" 1376 else: 1377 nested = f"({interior})" 1378 1379 type_sql = f"{type_sql}{nested}{values}" 1380 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1381 exp.DataType.Type.TIMETZ, 1382 exp.DataType.Type.TIMESTAMPTZ, 1383 ): 1384 type_sql = f"{type_sql} WITH TIME ZONE" 1385 1386 return type_sql
1388 def directory_sql(self, expression: exp.Directory) -> str: 1389 local = "LOCAL " if expression.args.get("local") else "" 1390 row_format = self.sql(expression, "row_format") 1391 row_format = f" {row_format}" if row_format else "" 1392 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1394 def delete_sql(self, expression: exp.Delete) -> str: 1395 this = self.sql(expression, "this") 1396 this = f" FROM {this}" if this else "" 1397 using = self.sql(expression, "using") 1398 using = f" USING {using}" if using else "" 1399 cluster = self.sql(expression, "cluster") 1400 cluster = f" {cluster}" if cluster else "" 1401 where = self.sql(expression, "where") 1402 returning = self.sql(expression, "returning") 1403 limit = self.sql(expression, "limit") 1404 tables = self.expressions(expression, key="tables") 1405 tables = f" {tables}" if tables else "" 1406 if self.RETURNING_END: 1407 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1408 else: 1409 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1410 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1412 def drop_sql(self, expression: exp.Drop) -> str: 1413 this = self.sql(expression, "this") 1414 expressions = self.expressions(expression, flat=True) 1415 expressions = f" ({expressions})" if expressions else "" 1416 kind = expression.args["kind"] 1417 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1418 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1419 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1420 on_cluster = self.sql(expression, "cluster") 1421 on_cluster = f" {on_cluster}" if on_cluster else "" 1422 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1423 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1424 cascade = " CASCADE" if expression.args.get("cascade") else "" 1425 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1426 purge = " PURGE" if expression.args.get("purge") else "" 1427 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1429 def set_operation(self, expression: exp.SetOperation) -> str: 1430 op_type = type(expression) 1431 op_name = op_type.key.upper() 1432 1433 distinct = expression.args.get("distinct") 1434 if ( 1435 distinct is False 1436 and op_type in (exp.Except, exp.Intersect) 1437 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1438 ): 1439 self.unsupported(f"{op_name} ALL is not supported") 1440 1441 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1442 1443 if distinct is None: 1444 distinct = default_distinct 1445 if distinct is None: 1446 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1447 1448 if distinct is default_distinct: 1449 kind = "" 1450 else: 1451 kind = " DISTINCT" if distinct else " ALL" 1452 1453 by_name = " BY NAME" if expression.args.get("by_name") else "" 1454 return f"{op_name}{kind}{by_name}"
1456 def set_operations(self, expression: exp.SetOperation) -> str: 1457 if not self.SET_OP_MODIFIERS: 1458 limit = expression.args.get("limit") 1459 order = expression.args.get("order") 1460 1461 if limit or order: 1462 select = self._move_ctes_to_top_level( 1463 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1464 ) 1465 1466 if limit: 1467 select = select.limit(limit.pop(), copy=False) 1468 if order: 1469 select = select.order_by(order.pop(), copy=False) 1470 return self.sql(select) 1471 1472 sqls: t.List[str] = [] 1473 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1474 1475 while stack: 1476 node = stack.pop() 1477 1478 if isinstance(node, exp.SetOperation): 1479 stack.append(node.expression) 1480 stack.append( 1481 self.maybe_comment( 1482 self.set_operation(node), comments=node.comments, separated=True 1483 ) 1484 ) 1485 stack.append(node.this) 1486 else: 1487 sqls.append(self.sql(node)) 1488 1489 this = self.sep().join(sqls) 1490 this = self.query_modifiers(expression, this) 1491 return self.prepend_ctes(expression, this)
1493 def fetch_sql(self, expression: exp.Fetch) -> str: 1494 direction = expression.args.get("direction") 1495 direction = f" {direction}" if direction else "" 1496 count = self.sql(expression, "count") 1497 count = f" {count}" if count else "" 1498 limit_options = self.sql(expression, "limit_options") 1499 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1500 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1502 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1503 percent = " PERCENT" if expression.args.get("percent") else "" 1504 rows = " ROWS" if expression.args.get("rows") else "" 1505 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1506 if not with_ties and rows: 1507 with_ties = " ONLY" 1508 return f"{percent}{rows}{with_ties}"
1510 def filter_sql(self, expression: exp.Filter) -> str: 1511 if self.AGGREGATE_FILTER_SUPPORTED: 1512 this = self.sql(expression, "this") 1513 where = self.sql(expression, "expression").strip() 1514 return f"{this} FILTER({where})" 1515 1516 agg = expression.this 1517 agg_arg = agg.this 1518 cond = expression.expression.this 1519 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1520 return self.sql(agg)
1529 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1530 using = self.sql(expression, "using") 1531 using = f" USING {using}" if using else "" 1532 columns = self.expressions(expression, key="columns", flat=True) 1533 columns = f"({columns})" if columns else "" 1534 partition_by = self.expressions(expression, key="partition_by", flat=True) 1535 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1536 where = self.sql(expression, "where") 1537 include = self.expressions(expression, key="include", flat=True) 1538 if include: 1539 include = f" INCLUDE ({include})" 1540 with_storage = self.expressions(expression, key="with_storage", flat=True) 1541 with_storage = f" WITH ({with_storage})" if with_storage else "" 1542 tablespace = self.sql(expression, "tablespace") 1543 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1544 on = self.sql(expression, "on") 1545 on = f" ON {on}" if on else "" 1546 1547 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1549 def index_sql(self, expression: exp.Index) -> str: 1550 unique = "UNIQUE " if expression.args.get("unique") else "" 1551 primary = "PRIMARY " if expression.args.get("primary") else "" 1552 amp = "AMP " if expression.args.get("amp") else "" 1553 name = self.sql(expression, "this") 1554 name = f"{name} " if name else "" 1555 table = self.sql(expression, "table") 1556 table = f"{self.INDEX_ON} {table}" if table else "" 1557 1558 index = "INDEX " if not table else "" 1559 1560 params = self.sql(expression, "params") 1561 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1563 def identifier_sql(self, expression: exp.Identifier) -> str: 1564 text = expression.name 1565 lower = text.lower() 1566 text = lower if self.normalize and not expression.quoted else text 1567 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1568 if ( 1569 expression.quoted 1570 or self.dialect.can_identify(text, self.identify) 1571 or lower in self.RESERVED_KEYWORDS 1572 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1573 ): 1574 text = f"{self._identifier_start}{text}{self._identifier_end}" 1575 return text
1590 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1591 input_format = self.sql(expression, "input_format") 1592 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1593 output_format = self.sql(expression, "output_format") 1594 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1595 return self.sep().join((input_format, output_format))
1605 def properties_sql(self, expression: exp.Properties) -> str: 1606 root_properties = [] 1607 with_properties = [] 1608 1609 for p in expression.expressions: 1610 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1611 if p_loc == exp.Properties.Location.POST_WITH: 1612 with_properties.append(p) 1613 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1614 root_properties.append(p) 1615 1616 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1617 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1618 1619 if root_props and with_props and not self.pretty: 1620 with_props = " " + with_props 1621 1622 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1629 def properties( 1630 self, 1631 properties: exp.Properties, 1632 prefix: str = "", 1633 sep: str = ", ", 1634 suffix: str = "", 1635 wrapped: bool = True, 1636 ) -> str: 1637 if properties.expressions: 1638 expressions = self.expressions(properties, sep=sep, indent=False) 1639 if expressions: 1640 expressions = self.wrap(expressions) if wrapped else expressions 1641 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1642 return ""
1647 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1648 properties_locs = defaultdict(list) 1649 for p in properties.expressions: 1650 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1651 if p_loc != exp.Properties.Location.UNSUPPORTED: 1652 properties_locs[p_loc].append(p) 1653 else: 1654 self.unsupported(f"Unsupported property {p.key}") 1655 1656 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1663 def property_sql(self, expression: exp.Property) -> str: 1664 property_cls = expression.__class__ 1665 if property_cls == exp.Property: 1666 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1667 1668 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1669 if not property_name: 1670 self.unsupported(f"Unsupported property {expression.key}") 1671 1672 return f"{property_name}={self.sql(expression, 'this')}"
1674 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1675 if self.SUPPORTS_CREATE_TABLE_LIKE: 1676 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1677 options = f" {options}" if options else "" 1678 1679 like = f"LIKE {self.sql(expression, 'this')}{options}" 1680 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1681 like = f"({like})" 1682 1683 return like 1684 1685 if expression.expressions: 1686 self.unsupported("Transpilation of LIKE property options is unsupported") 1687 1688 select = exp.select("*").from_(expression.this).limit(0) 1689 return f"AS {self.sql(select)}"
1696 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1697 no = "NO " if expression.args.get("no") else "" 1698 local = expression.args.get("local") 1699 local = f"{local} " if local else "" 1700 dual = "DUAL " if expression.args.get("dual") else "" 1701 before = "BEFORE " if expression.args.get("before") else "" 1702 after = "AFTER " if expression.args.get("after") else "" 1703 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1719 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1720 if expression.args.get("no"): 1721 return "NO MERGEBLOCKRATIO" 1722 if expression.args.get("default"): 1723 return "DEFAULT MERGEBLOCKRATIO" 1724 1725 percent = " PERCENT" if expression.args.get("percent") else "" 1726 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1728 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1729 default = expression.args.get("default") 1730 minimum = expression.args.get("minimum") 1731 maximum = expression.args.get("maximum") 1732 if default or minimum or maximum: 1733 if default: 1734 prop = "DEFAULT" 1735 elif minimum: 1736 prop = "MINIMUM" 1737 else: 1738 prop = "MAXIMUM" 1739 return f"{prop} DATABLOCKSIZE" 1740 units = expression.args.get("units") 1741 units = f" {units}" if units else "" 1742 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1744 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1745 autotemp = expression.args.get("autotemp") 1746 always = expression.args.get("always") 1747 default = expression.args.get("default") 1748 manual = expression.args.get("manual") 1749 never = expression.args.get("never") 1750 1751 if autotemp is not None: 1752 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1753 elif always: 1754 prop = "ALWAYS" 1755 elif default: 1756 prop = "DEFAULT" 1757 elif manual: 1758 prop = "MANUAL" 1759 elif never: 1760 prop = "NEVER" 1761 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1763 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1764 no = expression.args.get("no") 1765 no = " NO" if no else "" 1766 concurrent = expression.args.get("concurrent") 1767 concurrent = " CONCURRENT" if concurrent else "" 1768 target = self.sql(expression, "target") 1769 target = f" {target}" if target else "" 1770 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1772 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1773 if isinstance(expression.this, list): 1774 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1775 if expression.this: 1776 modulus = self.sql(expression, "this") 1777 remainder = self.sql(expression, "expression") 1778 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1779 1780 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1781 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1782 return f"FROM ({from_expressions}) TO ({to_expressions})"
1784 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1785 this = self.sql(expression, "this") 1786 1787 for_values_or_default = expression.expression 1788 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1789 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1790 else: 1791 for_values_or_default = " DEFAULT" 1792 1793 return f"PARTITION OF {this}{for_values_or_default}"
1795 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1796 kind = expression.args.get("kind") 1797 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1798 for_or_in = expression.args.get("for_or_in") 1799 for_or_in = f" {for_or_in}" if for_or_in else "" 1800 lock_type = expression.args.get("lock_type") 1801 override = " OVERRIDE" if expression.args.get("override") else "" 1802 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1804 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1805 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1806 statistics = expression.args.get("statistics") 1807 statistics_sql = "" 1808 if statistics is not None: 1809 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1810 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1812 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1813 this = self.sql(expression, "this") 1814 this = f"HISTORY_TABLE={this}" if this else "" 1815 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1816 data_consistency = ( 1817 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1818 ) 1819 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1820 retention_period = ( 1821 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1822 ) 1823 1824 if this: 1825 on_sql = self.func("ON", this, data_consistency, retention_period) 1826 else: 1827 on_sql = "ON" if expression.args.get("on") else "OFF" 1828 1829 sql = f"SYSTEM_VERSIONING={on_sql}" 1830 1831 return f"WITH({sql})" if expression.args.get("with") else sql
1833 def insert_sql(self, expression: exp.Insert) -> str: 1834 hint = self.sql(expression, "hint") 1835 overwrite = expression.args.get("overwrite") 1836 1837 if isinstance(expression.this, exp.Directory): 1838 this = " OVERWRITE" if overwrite else " INTO" 1839 else: 1840 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1841 1842 stored = self.sql(expression, "stored") 1843 stored = f" {stored}" if stored else "" 1844 alternative = expression.args.get("alternative") 1845 alternative = f" OR {alternative}" if alternative else "" 1846 ignore = " IGNORE" if expression.args.get("ignore") else "" 1847 is_function = expression.args.get("is_function") 1848 if is_function: 1849 this = f"{this} FUNCTION" 1850 this = f"{this} {self.sql(expression, 'this')}" 1851 1852 exists = " IF EXISTS" if expression.args.get("exists") else "" 1853 where = self.sql(expression, "where") 1854 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1855 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1856 on_conflict = self.sql(expression, "conflict") 1857 on_conflict = f" {on_conflict}" if on_conflict else "" 1858 by_name = " BY NAME" if expression.args.get("by_name") else "" 1859 returning = self.sql(expression, "returning") 1860 1861 if self.RETURNING_END: 1862 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1863 else: 1864 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1865 1866 partition_by = self.sql(expression, "partition") 1867 partition_by = f" {partition_by}" if partition_by else "" 1868 settings = self.sql(expression, "settings") 1869 settings = f" {settings}" if settings else "" 1870 1871 source = self.sql(expression, "source") 1872 source = f"TABLE {source}" if source else "" 1873 1874 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1875 return self.prepend_ctes(expression, sql)
1893 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1894 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1895 1896 constraint = self.sql(expression, "constraint") 1897 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1898 1899 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1900 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1901 action = self.sql(expression, "action") 1902 1903 expressions = self.expressions(expression, flat=True) 1904 if expressions: 1905 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1906 expressions = f" {set_keyword}{expressions}" 1907 1908 where = self.sql(expression, "where") 1909 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1914 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1915 fields = self.sql(expression, "fields") 1916 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1917 escaped = self.sql(expression, "escaped") 1918 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1919 items = self.sql(expression, "collection_items") 1920 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1921 keys = self.sql(expression, "map_keys") 1922 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1923 lines = self.sql(expression, "lines") 1924 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1925 null = self.sql(expression, "null") 1926 null = f" NULL DEFINED AS {null}" if null else "" 1927 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1955 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1956 table = self.table_parts(expression) 1957 only = "ONLY " if expression.args.get("only") else "" 1958 partition = self.sql(expression, "partition") 1959 partition = f" {partition}" if partition else "" 1960 version = self.sql(expression, "version") 1961 version = f" {version}" if version else "" 1962 alias = self.sql(expression, "alias") 1963 alias = f"{sep}{alias}" if alias else "" 1964 1965 sample = self.sql(expression, "sample") 1966 if self.dialect.ALIAS_POST_TABLESAMPLE: 1967 sample_pre_alias = sample 1968 sample_post_alias = "" 1969 else: 1970 sample_pre_alias = "" 1971 sample_post_alias = sample 1972 1973 hints = self.expressions(expression, key="hints", sep=" ") 1974 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1975 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1976 joins = self.indent( 1977 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1978 ) 1979 laterals = self.expressions(expression, key="laterals", sep="") 1980 1981 file_format = self.sql(expression, "format") 1982 if file_format: 1983 pattern = self.sql(expression, "pattern") 1984 pattern = f", PATTERN => {pattern}" if pattern else "" 1985 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1986 1987 ordinality = expression.args.get("ordinality") or "" 1988 if ordinality: 1989 ordinality = f" WITH ORDINALITY{alias}" 1990 alias = "" 1991 1992 when = self.sql(expression, "when") 1993 if when: 1994 table = f"{table} {when}" 1995 1996 changes = self.sql(expression, "changes") 1997 changes = f" {changes}" if changes else "" 1998 1999 rows_from = self.expressions(expression, key="rows_from") 2000 if rows_from: 2001 table = f"ROWS FROM {self.wrap(rows_from)}" 2002 2003 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2005 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2006 table = self.func("TABLE", expression.this) 2007 alias = self.sql(expression, "alias") 2008 alias = f" AS {alias}" if alias else "" 2009 sample = self.sql(expression, "sample") 2010 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2011 joins = self.indent( 2012 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2013 ) 2014 return f"{table}{alias}{pivots}{sample}{joins}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2016 def tablesample_sql( 2017 self, 2018 expression: exp.TableSample, 2019 tablesample_keyword: t.Optional[str] = None, 2020 ) -> str: 2021 method = self.sql(expression, "method") 2022 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2023 numerator = self.sql(expression, "bucket_numerator") 2024 denominator = self.sql(expression, "bucket_denominator") 2025 field = self.sql(expression, "bucket_field") 2026 field = f" ON {field}" if field else "" 2027 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2028 seed = self.sql(expression, "seed") 2029 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2030 2031 size = self.sql(expression, "size") 2032 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2033 size = f"{size} ROWS" 2034 2035 percent = self.sql(expression, "percent") 2036 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2037 percent = f"{percent} PERCENT" 2038 2039 expr = f"{bucket}{percent}{size}" 2040 if self.TABLESAMPLE_REQUIRES_PARENS: 2041 expr = f"({expr})" 2042 2043 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2045 def pivot_sql(self, expression: exp.Pivot) -> str: 2046 expressions = self.expressions(expression, flat=True) 2047 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2048 2049 if expression.this: 2050 this = self.sql(expression, "this") 2051 if not expressions: 2052 return f"UNPIVOT {this}" 2053 2054 on = f"{self.seg('ON')} {expressions}" 2055 into = self.sql(expression, "into") 2056 into = f"{self.seg('INTO')} {into}" if into else "" 2057 using = self.expressions(expression, key="using", flat=True) 2058 using = f"{self.seg('USING')} {using}" if using else "" 2059 group = self.sql(expression, "group") 2060 return f"{direction} {this}{on}{into}{using}{group}" 2061 2062 alias = self.sql(expression, "alias") 2063 alias = f" AS {alias}" if alias else "" 2064 2065 field = self.sql(expression, "field") 2066 2067 include_nulls = expression.args.get("include_nulls") 2068 if include_nulls is not None: 2069 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2070 else: 2071 nulls = "" 2072 2073 default_on_null = self.sql(expression, "default_on_null") 2074 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2075 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
2086 def update_sql(self, expression: exp.Update) -> str: 2087 this = self.sql(expression, "this") 2088 set_sql = self.expressions(expression, flat=True) 2089 from_sql = self.sql(expression, "from") 2090 where_sql = self.sql(expression, "where") 2091 returning = self.sql(expression, "returning") 2092 order = self.sql(expression, "order") 2093 limit = self.sql(expression, "limit") 2094 if self.RETURNING_END: 2095 expression_sql = f"{from_sql}{where_sql}{returning}" 2096 else: 2097 expression_sql = f"{returning}{from_sql}{where_sql}" 2098 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2099 return self.prepend_ctes(expression, sql)
2101 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2102 values_as_table = values_as_table and self.VALUES_AS_TABLE 2103 2104 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2105 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2106 args = self.expressions(expression) 2107 alias = self.sql(expression, "alias") 2108 values = f"VALUES{self.seg('')}{args}" 2109 values = ( 2110 f"({values})" 2111 if self.WRAP_DERIVED_VALUES 2112 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2113 else values 2114 ) 2115 return f"{values} AS {alias}" if alias else values 2116 2117 # Converts `VALUES...` expression into a series of select unions. 2118 alias_node = expression.args.get("alias") 2119 column_names = alias_node and alias_node.columns 2120 2121 selects: t.List[exp.Query] = [] 2122 2123 for i, tup in enumerate(expression.expressions): 2124 row = tup.expressions 2125 2126 if i == 0 and column_names: 2127 row = [ 2128 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2129 ] 2130 2131 selects.append(exp.Select(expressions=row)) 2132 2133 if self.pretty: 2134 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2135 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2136 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2137 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2138 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2139 2140 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2141 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2142 return f"({unions}){alias}"
2147 @unsupported_args("expressions") 2148 def into_sql(self, expression: exp.Into) -> str: 2149 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2150 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2151 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2168 def group_sql(self, expression: exp.Group) -> str: 2169 group_by_all = expression.args.get("all") 2170 if group_by_all is True: 2171 modifier = " ALL" 2172 elif group_by_all is False: 2173 modifier = " DISTINCT" 2174 else: 2175 modifier = "" 2176 2177 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2178 2179 grouping_sets = self.expressions(expression, key="grouping_sets") 2180 cube = self.expressions(expression, key="cube") 2181 rollup = self.expressions(expression, key="rollup") 2182 2183 groupings = csv( 2184 self.seg(grouping_sets) if grouping_sets else "", 2185 self.seg(cube) if cube else "", 2186 self.seg(rollup) if rollup else "", 2187 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2188 sep=self.GROUPINGS_SEP, 2189 ) 2190 2191 if ( 2192 expression.expressions 2193 and groupings 2194 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2195 ): 2196 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2197 2198 return f"{group_by}{groupings}"
2204 def connect_sql(self, expression: exp.Connect) -> str: 2205 start = self.sql(expression, "start") 2206 start = self.seg(f"START WITH {start}") if start else "" 2207 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2208 connect = self.sql(expression, "connect") 2209 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2210 return start + connect
2215 def join_sql(self, expression: exp.Join) -> str: 2216 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2217 side = None 2218 else: 2219 side = expression.side 2220 2221 op_sql = " ".join( 2222 op 2223 for op in ( 2224 expression.method, 2225 "GLOBAL" if expression.args.get("global") else None, 2226 side, 2227 expression.kind, 2228 expression.hint if self.JOIN_HINTS else None, 2229 ) 2230 if op 2231 ) 2232 match_cond = self.sql(expression, "match_condition") 2233 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2234 on_sql = self.sql(expression, "on") 2235 using = expression.args.get("using") 2236 2237 if not on_sql and using: 2238 on_sql = csv(*(self.sql(column) for column in using)) 2239 2240 this = expression.this 2241 this_sql = self.sql(this) 2242 2243 exprs = self.expressions(expression) 2244 if exprs: 2245 this_sql = f"{this_sql},{self.seg(exprs)}" 2246 2247 if on_sql: 2248 on_sql = self.indent(on_sql, skip_first=True) 2249 space = self.seg(" " * self.pad) if self.pretty else " " 2250 if using: 2251 on_sql = f"{space}USING ({on_sql})" 2252 else: 2253 on_sql = f"{space}ON {on_sql}" 2254 elif not op_sql: 2255 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2256 return f" {this_sql}" 2257 2258 return f", {this_sql}" 2259 2260 if op_sql != "STRAIGHT_JOIN": 2261 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2262 2263 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2270 def lateral_op(self, expression: exp.Lateral) -> str: 2271 cross_apply = expression.args.get("cross_apply") 2272 2273 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2274 if cross_apply is True: 2275 op = "INNER JOIN " 2276 elif cross_apply is False: 2277 op = "LEFT JOIN " 2278 else: 2279 op = "" 2280 2281 return f"{op}LATERAL"
2283 def lateral_sql(self, expression: exp.Lateral) -> str: 2284 this = self.sql(expression, "this") 2285 2286 if expression.args.get("view"): 2287 alias = expression.args["alias"] 2288 columns = self.expressions(alias, key="columns", flat=True) 2289 table = f" {alias.name}" if alias.name else "" 2290 columns = f" AS {columns}" if columns else "" 2291 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2292 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2293 2294 alias = self.sql(expression, "alias") 2295 alias = f" AS {alias}" if alias else "" 2296 return f"{self.lateral_op(expression)} {this}{alias}"
2298 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2299 this = self.sql(expression, "this") 2300 2301 args = [ 2302 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2303 for e in (expression.args.get(k) for k in ("offset", "expression")) 2304 if e 2305 ] 2306 2307 args_sql = ", ".join(self.sql(e) for e in args) 2308 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2309 expressions = self.expressions(expression, flat=True) 2310 limit_options = self.sql(expression, "limit_options") 2311 expressions = f" BY {expressions}" if expressions else "" 2312 2313 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2315 def offset_sql(self, expression: exp.Offset) -> str: 2316 this = self.sql(expression, "this") 2317 value = expression.expression 2318 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2319 expressions = self.expressions(expression, flat=True) 2320 expressions = f" BY {expressions}" if expressions else "" 2321 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2323 def setitem_sql(self, expression: exp.SetItem) -> str: 2324 kind = self.sql(expression, "kind") 2325 kind = f"{kind} " if kind else "" 2326 this = self.sql(expression, "this") 2327 expressions = self.expressions(expression) 2328 collate = self.sql(expression, "collate") 2329 collate = f" COLLATE {collate}" if collate else "" 2330 global_ = "GLOBAL " if expression.args.get("global") else "" 2331 return f"{global_}{kind}{this}{expressions}{collate}"
2341 def lock_sql(self, expression: exp.Lock) -> str: 2342 if not self.LOCKING_READS_SUPPORTED: 2343 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2344 return "" 2345 2346 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2347 expressions = self.expressions(expression, flat=True) 2348 expressions = f" OF {expressions}" if expressions else "" 2349 wait = expression.args.get("wait") 2350 2351 if wait is not None: 2352 if isinstance(wait, exp.Literal): 2353 wait = f" WAIT {self.sql(wait)}" 2354 else: 2355 wait = " NOWAIT" if wait else " SKIP LOCKED" 2356 2357 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2365 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2366 if self.dialect.ESCAPED_SEQUENCES: 2367 to_escaped = self.dialect.ESCAPED_SEQUENCES 2368 text = "".join( 2369 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2370 ) 2371 2372 return self._replace_line_breaks(text).replace( 2373 self.dialect.QUOTE_END, self._escaped_quote_end 2374 )
2376 def loaddata_sql(self, expression: exp.LoadData) -> str: 2377 local = " LOCAL" if expression.args.get("local") else "" 2378 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2379 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2380 this = f" INTO TABLE {self.sql(expression, 'this')}" 2381 partition = self.sql(expression, "partition") 2382 partition = f" {partition}" if partition else "" 2383 input_format = self.sql(expression, "input_format") 2384 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2385 serde = self.sql(expression, "serde") 2386 serde = f" SERDE {serde}" if serde else "" 2387 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2395 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2396 this = self.sql(expression, "this") 2397 this = f"{this} " if this else this 2398 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2399 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2401 def withfill_sql(self, expression: exp.WithFill) -> str: 2402 from_sql = self.sql(expression, "from") 2403 from_sql = f" FROM {from_sql}" if from_sql else "" 2404 to_sql = self.sql(expression, "to") 2405 to_sql = f" TO {to_sql}" if to_sql else "" 2406 step_sql = self.sql(expression, "step") 2407 step_sql = f" STEP {step_sql}" if step_sql else "" 2408 interpolated_values = [ 2409 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2410 if isinstance(e, exp.Alias) 2411 else self.sql(e, "this") 2412 for e in expression.args.get("interpolate") or [] 2413 ] 2414 interpolate = ( 2415 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2416 ) 2417 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2428 def ordered_sql(self, expression: exp.Ordered) -> str: 2429 desc = expression.args.get("desc") 2430 asc = not desc 2431 2432 nulls_first = expression.args.get("nulls_first") 2433 nulls_last = not nulls_first 2434 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2435 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2436 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2437 2438 this = self.sql(expression, "this") 2439 2440 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2441 nulls_sort_change = "" 2442 if nulls_first and ( 2443 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2444 ): 2445 nulls_sort_change = " NULLS FIRST" 2446 elif ( 2447 nulls_last 2448 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2449 and not nulls_are_last 2450 ): 2451 nulls_sort_change = " NULLS LAST" 2452 2453 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2454 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2455 window = expression.find_ancestor(exp.Window, exp.Select) 2456 if isinstance(window, exp.Window) and window.args.get("spec"): 2457 self.unsupported( 2458 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2459 ) 2460 nulls_sort_change = "" 2461 elif self.NULL_ORDERING_SUPPORTED is False and ( 2462 (asc and nulls_sort_change == " NULLS LAST") 2463 or (desc and nulls_sort_change == " NULLS FIRST") 2464 ): 2465 # BigQuery does not allow these ordering/nulls combinations when used under 2466 # an aggregation func or under a window containing one 2467 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2468 2469 if isinstance(ancestor, exp.Window): 2470 ancestor = ancestor.this 2471 if isinstance(ancestor, exp.AggFunc): 2472 self.unsupported( 2473 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2474 ) 2475 nulls_sort_change = "" 2476 elif self.NULL_ORDERING_SUPPORTED is None: 2477 if expression.this.is_int: 2478 self.unsupported( 2479 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2480 ) 2481 elif not isinstance(expression.this, exp.Rand): 2482 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2483 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2484 nulls_sort_change = "" 2485 2486 with_fill = self.sql(expression, "with_fill") 2487 with_fill = f" {with_fill}" if with_fill else "" 2488 2489 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2499 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2500 partition = self.partition_by_sql(expression) 2501 order = self.sql(expression, "order") 2502 measures = self.expressions(expression, key="measures") 2503 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2504 rows = self.sql(expression, "rows") 2505 rows = self.seg(rows) if rows else "" 2506 after = self.sql(expression, "after") 2507 after = self.seg(after) if after else "" 2508 pattern = self.sql(expression, "pattern") 2509 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2510 definition_sqls = [ 2511 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2512 for definition in expression.args.get("define", []) 2513 ] 2514 definitions = self.expressions(sqls=definition_sqls) 2515 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2516 body = "".join( 2517 ( 2518 partition, 2519 order, 2520 measures, 2521 rows, 2522 after, 2523 pattern, 2524 define, 2525 ) 2526 ) 2527 alias = self.sql(expression, "alias") 2528 alias = f" {alias}" if alias else "" 2529 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2531 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2532 limit = expression.args.get("limit") 2533 2534 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2535 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2536 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2537 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2538 2539 return csv( 2540 *sqls, 2541 *[self.sql(join) for join in expression.args.get("joins") or []], 2542 self.sql(expression, "match"), 2543 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2544 self.sql(expression, "prewhere"), 2545 self.sql(expression, "where"), 2546 self.sql(expression, "connect"), 2547 self.sql(expression, "group"), 2548 self.sql(expression, "having"), 2549 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2550 self.sql(expression, "order"), 2551 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2552 *self.after_limit_modifiers(expression), 2553 self.options_modifier(expression), 2554 sep="", 2555 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2564 def offset_limit_modifiers( 2565 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2566 ) -> t.List[str]: 2567 return [ 2568 self.sql(expression, "offset") if fetch else self.sql(limit), 2569 self.sql(limit) if fetch else self.sql(expression, "offset"), 2570 ]
2577 def select_sql(self, expression: exp.Select) -> str: 2578 into = expression.args.get("into") 2579 if not self.SUPPORTS_SELECT_INTO and into: 2580 into.pop() 2581 2582 hint = self.sql(expression, "hint") 2583 distinct = self.sql(expression, "distinct") 2584 distinct = f" {distinct}" if distinct else "" 2585 kind = self.sql(expression, "kind") 2586 2587 limit = expression.args.get("limit") 2588 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2589 top = self.limit_sql(limit, top=True) 2590 limit.pop() 2591 else: 2592 top = "" 2593 2594 expressions = self.expressions(expression) 2595 2596 if kind: 2597 if kind in self.SELECT_KINDS: 2598 kind = f" AS {kind}" 2599 else: 2600 if kind == "STRUCT": 2601 expressions = self.expressions( 2602 sqls=[ 2603 self.sql( 2604 exp.Struct( 2605 expressions=[ 2606 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2607 if isinstance(e, exp.Alias) 2608 else e 2609 for e in expression.expressions 2610 ] 2611 ) 2612 ) 2613 ] 2614 ) 2615 kind = "" 2616 2617 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2618 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2619 2620 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2621 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2622 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2623 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2624 sql = self.query_modifiers( 2625 expression, 2626 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2627 self.sql(expression, "into", comment=False), 2628 self.sql(expression, "from", comment=False), 2629 ) 2630 2631 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2632 if expression.args.get("with"): 2633 sql = self.maybe_comment(sql, expression) 2634 expression.pop_comments() 2635 2636 sql = self.prepend_ctes(expression, sql) 2637 2638 if not self.SUPPORTS_SELECT_INTO and into: 2639 if into.args.get("temporary"): 2640 table_kind = " TEMPORARY" 2641 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2642 table_kind = " UNLOGGED" 2643 else: 2644 table_kind = "" 2645 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2646 2647 return sql
2659 def star_sql(self, expression: exp.Star) -> str: 2660 except_ = self.expressions(expression, key="except", flat=True) 2661 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2662 replace = self.expressions(expression, key="replace", flat=True) 2663 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2664 rename = self.expressions(expression, key="rename", flat=True) 2665 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2666 return f"*{except_}{replace}{rename}"
2682 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2683 alias = self.sql(expression, "alias") 2684 alias = f"{sep}{alias}" if alias else "" 2685 sample = self.sql(expression, "sample") 2686 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2687 alias = f"{sample}{alias}" 2688 2689 # Set to None so it's not generated again by self.query_modifiers() 2690 expression.set("sample", None) 2691 2692 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2693 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2694 return self.prepend_ctes(expression, sql)
2700 def unnest_sql(self, expression: exp.Unnest) -> str: 2701 args = self.expressions(expression, flat=True) 2702 2703 alias = expression.args.get("alias") 2704 offset = expression.args.get("offset") 2705 2706 if self.UNNEST_WITH_ORDINALITY: 2707 if alias and isinstance(offset, exp.Expression): 2708 alias.append("columns", offset) 2709 2710 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2711 columns = alias.columns 2712 alias = self.sql(columns[0]) if columns else "" 2713 else: 2714 alias = self.sql(alias) 2715 2716 alias = f" AS {alias}" if alias else alias 2717 if self.UNNEST_WITH_ORDINALITY: 2718 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2719 else: 2720 if isinstance(offset, exp.Expression): 2721 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2722 elif offset: 2723 suffix = f"{alias} WITH OFFSET" 2724 else: 2725 suffix = alias 2726 2727 return f"UNNEST({args}){suffix}"
2736 def window_sql(self, expression: exp.Window) -> str: 2737 this = self.sql(expression, "this") 2738 partition = self.partition_by_sql(expression) 2739 order = expression.args.get("order") 2740 order = self.order_sql(order, flat=True) if order else "" 2741 spec = self.sql(expression, "spec") 2742 alias = self.sql(expression, "alias") 2743 over = self.sql(expression, "over") or "OVER" 2744 2745 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2746 2747 first = expression.args.get("first") 2748 if first is None: 2749 first = "" 2750 else: 2751 first = "FIRST" if first else "LAST" 2752 2753 if not partition and not order and not spec and alias: 2754 return f"{this} {alias}" 2755 2756 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2757 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2763 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2764 kind = self.sql(expression, "kind") 2765 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2766 end = ( 2767 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2768 or "CURRENT ROW" 2769 ) 2770 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]:
2783 def bracket_offset_expressions( 2784 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2785 ) -> t.List[exp.Expression]: 2786 return apply_index_offset( 2787 expression.this, 2788 expression.expressions, 2789 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2790 )
2800 def any_sql(self, expression: exp.Any) -> str: 2801 this = self.sql(expression, "this") 2802 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2803 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2804 this = self.wrap(this) 2805 return f"ANY{this}" 2806 return f"ANY {this}"
2811 def case_sql(self, expression: exp.Case) -> str: 2812 this = self.sql(expression, "this") 2813 statements = [f"CASE {this}" if this else "CASE"] 2814 2815 for e in expression.args["ifs"]: 2816 statements.append(f"WHEN {self.sql(e, 'this')}") 2817 statements.append(f"THEN {self.sql(e, 'true')}") 2818 2819 default = self.sql(expression, "default") 2820 2821 if default: 2822 statements.append(f"ELSE {default}") 2823 2824 statements.append("END") 2825 2826 if self.pretty and self.too_wide(statements): 2827 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2828 2829 return " ".join(statements)
2846 def trim_sql(self, expression: exp.Trim) -> str: 2847 trim_type = self.sql(expression, "position") 2848 2849 if trim_type == "LEADING": 2850 func_name = "LTRIM" 2851 elif trim_type == "TRAILING": 2852 func_name = "RTRIM" 2853 else: 2854 func_name = "TRIM" 2855 2856 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]:
2858 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2859 args = expression.expressions 2860 if isinstance(expression, exp.ConcatWs): 2861 args = args[1:] # Skip the delimiter 2862 2863 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2864 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2865 2866 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2867 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2868 2869 return args
2871 def concat_sql(self, expression: exp.Concat) -> str: 2872 expressions = self.convert_concat_args(expression) 2873 2874 # Some dialects don't allow a single-argument CONCAT call 2875 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2876 return self.sql(expressions[0]) 2877 2878 return self.func("CONCAT", *expressions)
2889 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2890 expressions = self.expressions(expression, flat=True) 2891 expressions = f" ({expressions})" if expressions else "" 2892 reference = self.sql(expression, "reference") 2893 reference = f" {reference}" if reference else "" 2894 delete = self.sql(expression, "delete") 2895 delete = f" ON DELETE {delete}" if delete else "" 2896 update = self.sql(expression, "update") 2897 update = f" ON UPDATE {update}" if update else "" 2898 return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
2900 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2901 expressions = self.expressions(expression, flat=True) 2902 options = self.expressions(expression, key="options", flat=True, sep=" ") 2903 options = f" {options}" if options else "" 2904 return f"PRIMARY KEY ({expressions}){options}"
2917 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2918 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2919 2920 if expression.args.get("escape"): 2921 path = self.escape_str(path) 2922 2923 if self.QUOTE_JSON_PATH: 2924 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2925 2926 return path
2928 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2929 if isinstance(expression, exp.JSONPathPart): 2930 transform = self.TRANSFORMS.get(expression.__class__) 2931 if not callable(transform): 2932 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2933 return "" 2934 2935 return transform(self, expression) 2936 2937 if isinstance(expression, int): 2938 return str(expression) 2939 2940 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2941 escaped = expression.replace("'", "\\'") 2942 escaped = f"\\'{expression}\\'" 2943 else: 2944 escaped = expression.replace('"', '\\"') 2945 escaped = f'"{escaped}"' 2946 2947 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2952 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2953 null_handling = expression.args.get("null_handling") 2954 null_handling = f" {null_handling}" if null_handling else "" 2955 2956 unique_keys = expression.args.get("unique_keys") 2957 if unique_keys is not None: 2958 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2959 else: 2960 unique_keys = "" 2961 2962 return_type = self.sql(expression, "return_type") 2963 return_type = f" RETURNING {return_type}" if return_type else "" 2964 encoding = self.sql(expression, "encoding") 2965 encoding = f" ENCODING {encoding}" if encoding else "" 2966 2967 return self.func( 2968 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2969 *expression.expressions, 2970 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2971 )
2976 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2977 null_handling = expression.args.get("null_handling") 2978 null_handling = f" {null_handling}" if null_handling else "" 2979 return_type = self.sql(expression, "return_type") 2980 return_type = f" RETURNING {return_type}" if return_type else "" 2981 strict = " STRICT" if expression.args.get("strict") else "" 2982 return self.func( 2983 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2984 )
2986 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2987 this = self.sql(expression, "this") 2988 order = self.sql(expression, "order") 2989 null_handling = expression.args.get("null_handling") 2990 null_handling = f" {null_handling}" if null_handling else "" 2991 return_type = self.sql(expression, "return_type") 2992 return_type = f" RETURNING {return_type}" if return_type else "" 2993 strict = " STRICT" if expression.args.get("strict") else "" 2994 return self.func( 2995 "JSON_ARRAYAGG", 2996 this, 2997 suffix=f"{order}{null_handling}{return_type}{strict})", 2998 )
3000 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 3001 path = self.sql(expression, "path") 3002 path = f" PATH {path}" if path else "" 3003 nested_schema = self.sql(expression, "nested_schema") 3004 3005 if nested_schema: 3006 return f"NESTED{path} {nested_schema}" 3007 3008 this = self.sql(expression, "this") 3009 kind = self.sql(expression, "kind") 3010 kind = f" {kind}" if kind else "" 3011 return f"{this}{kind}{path}"
3016 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3017 this = self.sql(expression, "this") 3018 path = self.sql(expression, "path") 3019 path = f", {path}" if path else "" 3020 error_handling = expression.args.get("error_handling") 3021 error_handling = f" {error_handling}" if error_handling else "" 3022 empty_handling = expression.args.get("empty_handling") 3023 empty_handling = f" {empty_handling}" if empty_handling else "" 3024 schema = self.sql(expression, "schema") 3025 return self.func( 3026 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3027 )
3029 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3030 this = self.sql(expression, "this") 3031 kind = self.sql(expression, "kind") 3032 path = self.sql(expression, "path") 3033 path = f" {path}" if path else "" 3034 as_json = " AS JSON" if expression.args.get("as_json") else "" 3035 return f"{this} {kind}{path}{as_json}"
3037 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3038 this = self.sql(expression, "this") 3039 path = self.sql(expression, "path") 3040 path = f", {path}" if path else "" 3041 expressions = self.expressions(expression) 3042 with_ = ( 3043 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3044 if expressions 3045 else "" 3046 ) 3047 return f"OPENJSON({this}{path}){with_}"
3049 def in_sql(self, expression: exp.In) -> str: 3050 query = expression.args.get("query") 3051 unnest = expression.args.get("unnest") 3052 field = expression.args.get("field") 3053 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3054 3055 if query: 3056 in_sql = self.sql(query) 3057 elif unnest: 3058 in_sql = self.in_unnest_op(unnest) 3059 elif field: 3060 in_sql = self.sql(field) 3061 else: 3062 in_sql = f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 3063 3064 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3069 def interval_sql(self, expression: exp.Interval) -> str: 3070 unit = self.sql(expression, "unit") 3071 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3072 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3073 unit = f" {unit}" if unit else "" 3074 3075 if self.SINGLE_STRING_INTERVAL: 3076 this = expression.this.name if expression.this else "" 3077 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3078 3079 this = self.sql(expression, "this") 3080 if this: 3081 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3082 this = f" {this}" if unwrapped else f" ({this})" 3083 3084 return f"INTERVAL{this}{unit}"
3089 def reference_sql(self, expression: exp.Reference) -> str: 3090 this = self.sql(expression, "this") 3091 expressions = self.expressions(expression, flat=True) 3092 expressions = f"({expressions})" if expressions else "" 3093 options = self.expressions(expression, key="options", flat=True, sep=" ") 3094 options = f" {options}" if options else "" 3095 return f"REFERENCES {this}{expressions}{options}"
3097 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3098 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3099 parent = expression.parent 3100 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3101 return self.func( 3102 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3103 )
3123 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3124 alias = expression.args["alias"] 3125 3126 parent = expression.parent 3127 pivot = parent and parent.parent 3128 3129 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3130 identifier_alias = isinstance(alias, exp.Identifier) 3131 literal_alias = isinstance(alias, exp.Literal) 3132 3133 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3134 alias.replace(exp.Literal.string(alias.output_name)) 3135 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3136 alias.replace(exp.to_identifier(alias.output_name)) 3137 3138 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:
3176 def connector_sql( 3177 self, 3178 expression: exp.Connector, 3179 op: str, 3180 stack: t.Optional[t.List[str | exp.Expression]] = None, 3181 ) -> str: 3182 if stack is not None: 3183 if expression.expressions: 3184 stack.append(self.expressions(expression, sep=f" {op} ")) 3185 else: 3186 stack.append(expression.right) 3187 if expression.comments and self.comments: 3188 for comment in expression.comments: 3189 if comment: 3190 op += f" /*{self.pad_comment(comment)}*/" 3191 stack.extend((op, expression.left)) 3192 return op 3193 3194 stack = [expression] 3195 sqls: t.List[str] = [] 3196 ops = set() 3197 3198 while stack: 3199 node = stack.pop() 3200 if isinstance(node, exp.Connector): 3201 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3202 else: 3203 sql = self.sql(node) 3204 if sqls and sqls[-1] in ops: 3205 sqls[-1] += f" {sql}" 3206 else: 3207 sqls.append(sql) 3208 3209 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3210 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3230 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3231 format_sql = self.sql(expression, "format") 3232 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3233 to_sql = self.sql(expression, "to") 3234 to_sql = f" {to_sql}" if to_sql else "" 3235 action = self.sql(expression, "action") 3236 action = f" {action}" if action else "" 3237 default = self.sql(expression, "default") 3238 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3239 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3253 def comment_sql(self, expression: exp.Comment) -> str: 3254 this = self.sql(expression, "this") 3255 kind = expression.args["kind"] 3256 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3257 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3258 expression_sql = self.sql(expression, "expression") 3259 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3261 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3262 this = self.sql(expression, "this") 3263 delete = " DELETE" if expression.args.get("delete") else "" 3264 recompress = self.sql(expression, "recompress") 3265 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3266 to_disk = self.sql(expression, "to_disk") 3267 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3268 to_volume = self.sql(expression, "to_volume") 3269 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3270 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3272 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3273 where = self.sql(expression, "where") 3274 group = self.sql(expression, "group") 3275 aggregates = self.expressions(expression, key="aggregates") 3276 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3277 3278 if not (where or group or aggregates) and len(expression.expressions) == 1: 3279 return f"TTL {self.expressions(expression, flat=True)}" 3280 3281 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3298 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3299 this = self.sql(expression, "this") 3300 3301 dtype = self.sql(expression, "dtype") 3302 if dtype: 3303 collate = self.sql(expression, "collate") 3304 collate = f" COLLATE {collate}" if collate else "" 3305 using = self.sql(expression, "using") 3306 using = f" USING {using}" if using else "" 3307 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3308 3309 default = self.sql(expression, "default") 3310 if default: 3311 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3312 3313 comment = self.sql(expression, "comment") 3314 if comment: 3315 return f"ALTER COLUMN {this} COMMENT {comment}" 3316 3317 visible = expression.args.get("visible") 3318 if visible: 3319 return f"ALTER COLUMN {this} SET {visible}" 3320 3321 allow_null = expression.args.get("allow_null") 3322 drop = expression.args.get("drop") 3323 3324 if not drop and not allow_null: 3325 self.unsupported("Unsupported ALTER COLUMN syntax") 3326 3327 if allow_null is not None: 3328 keyword = "DROP" if drop else "SET" 3329 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3330 3331 return f"ALTER COLUMN {this} DROP DEFAULT"
3347 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3348 compound = " COMPOUND" if expression.args.get("compound") else "" 3349 this = self.sql(expression, "this") 3350 expressions = self.expressions(expression, flat=True) 3351 expressions = f"({expressions})" if expressions else "" 3352 return f"ALTER{compound} SORTKEY {this or expressions}"
3354 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3355 if not self.RENAME_TABLE_WITH_DB: 3356 # Remove db from tables 3357 expression = expression.transform( 3358 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3359 ).assert_is(exp.AlterRename) 3360 this = self.sql(expression, "this") 3361 return f"RENAME TO {this}"
3373 def alter_sql(self, expression: exp.Alter) -> str: 3374 actions = expression.args["actions"] 3375 3376 if isinstance(actions[0], exp.ColumnDef): 3377 actions = self.add_column_sql(expression) 3378 elif isinstance(actions[0], exp.Schema): 3379 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3380 elif isinstance(actions[0], exp.Delete): 3381 actions = self.expressions(expression, key="actions", flat=True) 3382 elif isinstance(actions[0], exp.Query): 3383 actions = "AS " + self.expressions(expression, key="actions") 3384 else: 3385 actions = self.expressions(expression, key="actions", flat=True) 3386 3387 exists = " IF EXISTS" if expression.args.get("exists") else "" 3388 on_cluster = self.sql(expression, "cluster") 3389 on_cluster = f" {on_cluster}" if on_cluster else "" 3390 only = " ONLY" if expression.args.get("only") else "" 3391 options = self.expressions(expression, key="options") 3392 options = f", {options}" if options else "" 3393 kind = self.sql(expression, "kind") 3394 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3395 3396 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3398 def add_column_sql(self, expression: exp.Alter) -> str: 3399 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3400 return self.expressions( 3401 expression, 3402 key="actions", 3403 prefix="ADD COLUMN ", 3404 skip_first=True, 3405 ) 3406 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3416 def distinct_sql(self, expression: exp.Distinct) -> str: 3417 this = self.expressions(expression, flat=True) 3418 3419 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3420 case = exp.case() 3421 for arg in expression.expressions: 3422 case = case.when(arg.is_(exp.null()), exp.null()) 3423 this = self.sql(case.else_(f"({this})")) 3424 3425 this = f" {this}" if this else "" 3426 3427 on = self.sql(expression, "on") 3428 on = f" ON {on}" if on else "" 3429 return f"DISTINCT{this}{on}"
3458 def div_sql(self, expression: exp.Div) -> str: 3459 l, r = expression.left, expression.right 3460 3461 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3462 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3463 3464 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3465 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3466 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3467 3468 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3469 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3470 return self.sql( 3471 exp.cast( 3472 l / r, 3473 to=exp.DataType.Type.BIGINT, 3474 ) 3475 ) 3476 3477 return self.binary(expression, "/")
3573 def log_sql(self, expression: exp.Log) -> str: 3574 this = expression.this 3575 expr = expression.expression 3576 3577 if self.dialect.LOG_BASE_FIRST is False: 3578 this, expr = expr, this 3579 elif self.dialect.LOG_BASE_FIRST is None and expr: 3580 if this.name in ("2", "10"): 3581 return self.func(f"LOG{this.name}", expr) 3582 3583 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3584 3585 return self.func("LOG", this, expr)
3594 def binary(self, expression: exp.Binary, op: str) -> str: 3595 sqls: t.List[str] = [] 3596 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3597 binary_type = type(expression) 3598 3599 while stack: 3600 node = stack.pop() 3601 3602 if type(node) is binary_type: 3603 op_func = node.args.get("operator") 3604 if op_func: 3605 op = f"OPERATOR({self.sql(op_func)})" 3606 3607 stack.append(node.right) 3608 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3609 stack.append(node.left) 3610 else: 3611 sqls.append(self.sql(node)) 3612 3613 return "".join(sqls)
3622 def function_fallback_sql(self, expression: exp.Func) -> str: 3623 args = [] 3624 3625 for key in expression.arg_types: 3626 arg_value = expression.args.get(key) 3627 3628 if isinstance(arg_value, list): 3629 for value in arg_value: 3630 args.append(value) 3631 elif arg_value is not None: 3632 args.append(arg_value) 3633 3634 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3635 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3636 else: 3637 name = expression.sql_name() 3638 3639 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:
3641 def func( 3642 self, 3643 name: str, 3644 *args: t.Optional[exp.Expression | str], 3645 prefix: str = "(", 3646 suffix: str = ")", 3647 normalize: bool = True, 3648 ) -> str: 3649 name = self.normalize_func(name) if normalize else name 3650 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3652 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3653 arg_sqls = tuple( 3654 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3655 ) 3656 if self.pretty and self.too_wide(arg_sqls): 3657 return self.indent( 3658 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3659 ) 3660 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]:
3665 def format_time( 3666 self, 3667 expression: exp.Expression, 3668 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3669 inverse_time_trie: t.Optional[t.Dict] = None, 3670 ) -> t.Optional[str]: 3671 return format_time( 3672 self.sql(expression, "format"), 3673 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3674 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3675 )
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:
3677 def expressions( 3678 self, 3679 expression: t.Optional[exp.Expression] = None, 3680 key: t.Optional[str] = None, 3681 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3682 flat: bool = False, 3683 indent: bool = True, 3684 skip_first: bool = False, 3685 skip_last: bool = False, 3686 sep: str = ", ", 3687 prefix: str = "", 3688 dynamic: bool = False, 3689 new_line: bool = False, 3690 ) -> str: 3691 expressions = expression.args.get(key or "expressions") if expression else sqls 3692 3693 if not expressions: 3694 return "" 3695 3696 if flat: 3697 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3698 3699 num_sqls = len(expressions) 3700 result_sqls = [] 3701 3702 for i, e in enumerate(expressions): 3703 sql = self.sql(e, comment=False) 3704 if not sql: 3705 continue 3706 3707 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3708 3709 if self.pretty: 3710 if self.leading_comma: 3711 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3712 else: 3713 result_sqls.append( 3714 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3715 ) 3716 else: 3717 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3718 3719 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3720 if new_line: 3721 result_sqls.insert(0, "") 3722 result_sqls.append("") 3723 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3724 else: 3725 result_sql = "".join(result_sqls) 3726 3727 return ( 3728 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3729 if indent 3730 else result_sql 3731 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3733 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3734 flat = flat or isinstance(expression.parent, exp.Properties) 3735 expressions_sql = self.expressions(expression, flat=flat) 3736 if flat: 3737 return f"{op} {expressions_sql}" 3738 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3740 def naked_property(self, expression: exp.Property) -> str: 3741 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3742 if not property_name: 3743 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3744 return f"{property_name} {self.sql(expression, 'this')}"
3752 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3753 this = self.sql(expression, "this") 3754 expressions = self.no_identify(self.expressions, expression) 3755 expressions = ( 3756 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3757 ) 3758 return f"{this}{expressions}" if expressions.strip() != "" else this
3768 def when_sql(self, expression: exp.When) -> str: 3769 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3770 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3771 condition = self.sql(expression, "condition") 3772 condition = f" AND {condition}" if condition else "" 3773 3774 then_expression = expression.args.get("then") 3775 if isinstance(then_expression, exp.Insert): 3776 this = self.sql(then_expression, "this") 3777 this = f"INSERT {this}" if this else "INSERT" 3778 then = self.sql(then_expression, "expression") 3779 then = f"{this} VALUES {then}" if then else this 3780 elif isinstance(then_expression, exp.Update): 3781 if isinstance(then_expression.args.get("expressions"), exp.Star): 3782 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3783 else: 3784 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3785 else: 3786 then = self.sql(then_expression) 3787 return f"WHEN {matched}{source}{condition} THEN {then}"
3792 def merge_sql(self, expression: exp.Merge) -> str: 3793 table = expression.this 3794 table_alias = "" 3795 3796 hints = table.args.get("hints") 3797 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3798 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3799 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3800 3801 this = self.sql(table) 3802 using = f"USING {self.sql(expression, 'using')}" 3803 on = f"ON {self.sql(expression, 'on')}" 3804 whens = self.sql(expression, "whens") 3805 3806 returning = self.sql(expression, "returning") 3807 if returning: 3808 whens = f"{whens}{returning}" 3809 3810 sep = self.sep() 3811 3812 return self.prepend_ctes( 3813 expression, 3814 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3815 )
3821 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3822 if not self.SUPPORTS_TO_NUMBER: 3823 self.unsupported("Unsupported TO_NUMBER function") 3824 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3825 3826 fmt = expression.args.get("format") 3827 if not fmt: 3828 self.unsupported("Conversion format is required for TO_NUMBER") 3829 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3830 3831 return self.func("TO_NUMBER", expression.this, fmt)
3833 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3834 this = self.sql(expression, "this") 3835 kind = self.sql(expression, "kind") 3836 settings_sql = self.expressions(expression, key="settings", sep=" ") 3837 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3838 return f"{this}({kind}{args})"
3857 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3858 expressions = self.expressions(expression, flat=True) 3859 expressions = f" {self.wrap(expressions)}" if expressions else "" 3860 buckets = self.sql(expression, "buckets") 3861 kind = self.sql(expression, "kind") 3862 buckets = f" BUCKETS {buckets}" if buckets else "" 3863 order = self.sql(expression, "order") 3864 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3869 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3870 expressions = self.expressions(expression, key="expressions", flat=True) 3871 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3872 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3873 buckets = self.sql(expression, "buckets") 3874 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3876 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3877 this = self.sql(expression, "this") 3878 having = self.sql(expression, "having") 3879 3880 if having: 3881 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3882 3883 return self.func("ANY_VALUE", this)
3885 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3886 transform = self.func("TRANSFORM", *expression.expressions) 3887 row_format_before = self.sql(expression, "row_format_before") 3888 row_format_before = f" {row_format_before}" if row_format_before else "" 3889 record_writer = self.sql(expression, "record_writer") 3890 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3891 using = f" USING {self.sql(expression, 'command_script')}" 3892 schema = self.sql(expression, "schema") 3893 schema = f" AS {schema}" if schema else "" 3894 row_format_after = self.sql(expression, "row_format_after") 3895 row_format_after = f" {row_format_after}" if row_format_after else "" 3896 record_reader = self.sql(expression, "record_reader") 3897 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3898 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3900 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3901 key_block_size = self.sql(expression, "key_block_size") 3902 if key_block_size: 3903 return f"KEY_BLOCK_SIZE = {key_block_size}" 3904 3905 using = self.sql(expression, "using") 3906 if using: 3907 return f"USING {using}" 3908 3909 parser = self.sql(expression, "parser") 3910 if parser: 3911 return f"WITH PARSER {parser}" 3912 3913 comment = self.sql(expression, "comment") 3914 if comment: 3915 return f"COMMENT {comment}" 3916 3917 visible = expression.args.get("visible") 3918 if visible is not None: 3919 return "VISIBLE" if visible else "INVISIBLE" 3920 3921 engine_attr = self.sql(expression, "engine_attr") 3922 if engine_attr: 3923 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3924 3925 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3926 if secondary_engine_attr: 3927 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3928 3929 self.unsupported("Unsupported index constraint option.") 3930 return ""
3936 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3937 kind = self.sql(expression, "kind") 3938 kind = f"{kind} INDEX" if kind else "INDEX" 3939 this = self.sql(expression, "this") 3940 this = f" {this}" if this else "" 3941 index_type = self.sql(expression, "index_type") 3942 index_type = f" USING {index_type}" if index_type else "" 3943 expressions = self.expressions(expression, flat=True) 3944 expressions = f" ({expressions})" if expressions else "" 3945 options = self.expressions(expression, key="options", sep=" ") 3946 options = f" {options}" if options else "" 3947 return f"{kind}{this}{index_type}{expressions}{options}"
3949 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3950 if self.NVL2_SUPPORTED: 3951 return self.function_fallback_sql(expression) 3952 3953 case = exp.Case().when( 3954 expression.this.is_(exp.null()).not_(copy=False), 3955 expression.args["true"], 3956 copy=False, 3957 ) 3958 else_cond = expression.args.get("false") 3959 if else_cond: 3960 case.else_(else_cond, copy=False) 3961 3962 return self.sql(case)
3964 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3965 this = self.sql(expression, "this") 3966 expr = self.sql(expression, "expression") 3967 iterator = self.sql(expression, "iterator") 3968 condition = self.sql(expression, "condition") 3969 condition = f" IF {condition}" if condition else "" 3970 return f"{this} FOR {expr} IN {iterator}{condition}"
3978 def predict_sql(self, expression: exp.Predict) -> str: 3979 model = self.sql(expression, "this") 3980 model = f"MODEL {model}" 3981 table = self.sql(expression, "expression") 3982 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3983 parameters = self.sql(expression, "params_struct") 3984 return self.func("PREDICT", model, table, parameters or None)
3996 def toarray_sql(self, expression: exp.ToArray) -> str: 3997 arg = expression.this 3998 if not arg.type: 3999 from sqlglot.optimizer.annotate_types import annotate_types 4000 4001 arg = annotate_types(arg) 4002 4003 if arg.is_type(exp.DataType.Type.ARRAY): 4004 return self.sql(arg) 4005 4006 cond_for_null = arg.is_(exp.null()) 4007 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4009 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4010 this = expression.this 4011 time_format = self.format_time(expression) 4012 4013 if time_format: 4014 return self.sql( 4015 exp.cast( 4016 exp.StrToTime(this=this, format=expression.args["format"]), 4017 exp.DataType.Type.TIME, 4018 ) 4019 ) 4020 4021 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4022 return self.sql(this) 4023 4024 return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4026 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4027 this = expression.this 4028 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4029 return self.sql(this) 4030 4031 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4033 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4034 this = expression.this 4035 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4036 return self.sql(this) 4037 4038 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4040 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4041 this = expression.this 4042 time_format = self.format_time(expression) 4043 4044 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4045 return self.sql( 4046 exp.cast( 4047 exp.StrToTime(this=this, format=expression.args["format"]), 4048 exp.DataType.Type.DATE, 4049 ) 4050 ) 4051 4052 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4053 return self.sql(this) 4054 4055 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4067 def lastday_sql(self, expression: exp.LastDay) -> str: 4068 if self.LAST_DAY_SUPPORTS_DATE_PART: 4069 return self.function_fallback_sql(expression) 4070 4071 unit = expression.text("unit") 4072 if unit and unit != "MONTH": 4073 self.unsupported("Date parts are not supported in LAST_DAY.") 4074 4075 return self.func("LAST_DAY", expression.this)
4084 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4085 if self.CAN_IMPLEMENT_ARRAY_ANY: 4086 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4087 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4088 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4089 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4090 4091 from sqlglot.dialects import Dialect 4092 4093 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4094 if self.dialect.__class__ != Dialect: 4095 self.unsupported("ARRAY_ANY is unsupported") 4096 4097 return self.function_fallback_sql(expression)
4099 def struct_sql(self, expression: exp.Struct) -> str: 4100 expression.set( 4101 "expressions", 4102 [ 4103 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4104 if isinstance(e, exp.PropertyEQ) 4105 else e 4106 for e in expression.expressions 4107 ], 4108 ) 4109 4110 return self.function_fallback_sql(expression)
4118 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4119 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4120 tables = f" {self.expressions(expression)}" 4121 4122 exists = " IF EXISTS" if expression.args.get("exists") else "" 4123 4124 on_cluster = self.sql(expression, "cluster") 4125 on_cluster = f" {on_cluster}" if on_cluster else "" 4126 4127 identity = self.sql(expression, "identity") 4128 identity = f" {identity} IDENTITY" if identity else "" 4129 4130 option = self.sql(expression, "option") 4131 option = f" {option}" if option else "" 4132 4133 partition = self.sql(expression, "partition") 4134 partition = f" {partition}" if partition else "" 4135 4136 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4140 def convert_sql(self, expression: exp.Convert) -> str: 4141 to = expression.this 4142 value = expression.expression 4143 style = expression.args.get("style") 4144 safe = expression.args.get("safe") 4145 strict = expression.args.get("strict") 4146 4147 if not to or not value: 4148 return "" 4149 4150 # Retrieve length of datatype and override to default if not specified 4151 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4152 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4153 4154 transformed: t.Optional[exp.Expression] = None 4155 cast = exp.Cast if strict else exp.TryCast 4156 4157 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4158 if isinstance(style, exp.Literal) and style.is_int: 4159 from sqlglot.dialects.tsql import TSQL 4160 4161 style_value = style.name 4162 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4163 if not converted_style: 4164 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4165 4166 fmt = exp.Literal.string(converted_style) 4167 4168 if to.this == exp.DataType.Type.DATE: 4169 transformed = exp.StrToDate(this=value, format=fmt) 4170 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4171 transformed = exp.StrToTime(this=value, format=fmt) 4172 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4173 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4174 elif to.this == exp.DataType.Type.TEXT: 4175 transformed = exp.TimeToStr(this=value, format=fmt) 4176 4177 if not transformed: 4178 transformed = cast(this=value, to=to, safe=safe) 4179 4180 return self.sql(transformed)
4240 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4241 option = self.sql(expression, "this") 4242 4243 if expression.expressions: 4244 upper = option.upper() 4245 4246 # Snowflake FILE_FORMAT options are separated by whitespace 4247 sep = " " if upper == "FILE_FORMAT" else ", " 4248 4249 # Databricks copy/format options do not set their list of values with EQ 4250 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4251 values = self.expressions(expression, flat=True, sep=sep) 4252 return f"{option}{op}({values})" 4253 4254 value = self.sql(expression, "expression") 4255 4256 if not value: 4257 return option 4258 4259 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4260 4261 return f"{option}{op}{value}"
4263 def credentials_sql(self, expression: exp.Credentials) -> str: 4264 cred_expr = expression.args.get("credentials") 4265 if isinstance(cred_expr, exp.Literal): 4266 # Redshift case: CREDENTIALS <string> 4267 credentials = self.sql(expression, "credentials") 4268 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4269 else: 4270 # Snowflake case: CREDENTIALS = (...) 4271 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4272 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4273 4274 storage = self.sql(expression, "storage") 4275 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4276 4277 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4278 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4279 4280 iam_role = self.sql(expression, "iam_role") 4281 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4282 4283 region = self.sql(expression, "region") 4284 region = f" REGION {region}" if region else "" 4285 4286 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4288 def copy_sql(self, expression: exp.Copy) -> str: 4289 this = self.sql(expression, "this") 4290 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4291 4292 credentials = self.sql(expression, "credentials") 4293 credentials = self.seg(credentials) if credentials else "" 4294 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4295 files = self.expressions(expression, key="files", flat=True) 4296 4297 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4298 params = self.expressions( 4299 expression, 4300 key="params", 4301 sep=sep, 4302 new_line=True, 4303 skip_last=True, 4304 skip_first=True, 4305 indent=self.COPY_PARAMS_ARE_WRAPPED, 4306 ) 4307 4308 if params: 4309 if self.COPY_PARAMS_ARE_WRAPPED: 4310 params = f" WITH ({params})" 4311 elif not self.pretty: 4312 params = f" {params}" 4313 4314 return f"COPY{this}{kind} {files}{credentials}{params}"
4319 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4320 on_sql = "ON" if expression.args.get("on") else "OFF" 4321 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4322 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4323 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4324 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4325 4326 if filter_col or retention_period: 4327 on_sql = self.func("ON", filter_col, retention_period) 4328 4329 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4331 def maskingpolicycolumnconstraint_sql( 4332 self, expression: exp.MaskingPolicyColumnConstraint 4333 ) -> str: 4334 this = self.sql(expression, "this") 4335 expressions = self.expressions(expression, flat=True) 4336 expressions = f" USING ({expressions})" if expressions else "" 4337 return f"MASKING POLICY {this}{expressions}"
4347 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4348 this = self.sql(expression, "this") 4349 expr = expression.expression 4350 4351 if isinstance(expr, exp.Func): 4352 # T-SQL's CLR functions are case sensitive 4353 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4354 else: 4355 expr = self.sql(expression, "expression") 4356 4357 return self.scope_resolution(expr, this)
4365 def rand_sql(self, expression: exp.Rand) -> str: 4366 lower = self.sql(expression, "lower") 4367 upper = self.sql(expression, "upper") 4368 4369 if lower and upper: 4370 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4371 return self.func("RAND", expression.this)
4373 def changes_sql(self, expression: exp.Changes) -> str: 4374 information = self.sql(expression, "information") 4375 information = f"INFORMATION => {information}" 4376 at_before = self.sql(expression, "at_before") 4377 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4378 end = self.sql(expression, "end") 4379 end = f"{self.seg('')}{end}" if end else "" 4380 4381 return f"CHANGES ({information}){at_before}{end}"
4383 def pad_sql(self, expression: exp.Pad) -> str: 4384 prefix = "L" if expression.args.get("is_left") else "R" 4385 4386 fill_pattern = self.sql(expression, "fill_pattern") or None 4387 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4388 fill_pattern = "' '" 4389 4390 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4396 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4397 generate_series = exp.GenerateSeries(**expression.args) 4398 4399 parent = expression.parent 4400 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4401 parent = parent.parent 4402 4403 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4404 return self.sql(exp.Unnest(expressions=[generate_series])) 4405 4406 if isinstance(parent, exp.Select): 4407 self.unsupported("GenerateSeries projection unnesting is not supported.") 4408 4409 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4411 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4412 exprs = expression.expressions 4413 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4414 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4415 else: 4416 rhs = self.expressions(expression) 4417 4418 return self.func(name, expression.this, rhs or None)
4420 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4421 if self.SUPPORTS_CONVERT_TIMEZONE: 4422 return self.function_fallback_sql(expression) 4423 4424 source_tz = expression.args.get("source_tz") 4425 target_tz = expression.args.get("target_tz") 4426 timestamp = expression.args.get("timestamp") 4427 4428 if source_tz and timestamp: 4429 timestamp = exp.AtTimeZone( 4430 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4431 ) 4432 4433 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4434 4435 return self.sql(expr)
4437 def json_sql(self, expression: exp.JSON) -> str: 4438 this = self.sql(expression, "this") 4439 this = f" {this}" if this else "" 4440 4441 _with = expression.args.get("with") 4442 4443 if _with is None: 4444 with_sql = "" 4445 elif not _with: 4446 with_sql = " WITHOUT" 4447 else: 4448 with_sql = " WITH" 4449 4450 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4451 4452 return f"JSON{this}{with_sql}{unique_sql}"
4454 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4455 def _generate_on_options(arg: t.Any) -> str: 4456 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4457 4458 path = self.sql(expression, "path") 4459 returning = self.sql(expression, "returning") 4460 returning = f" RETURNING {returning}" if returning else "" 4461 4462 on_condition = self.sql(expression, "on_condition") 4463 on_condition = f" {on_condition}" if on_condition else "" 4464 4465 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4467 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4468 else_ = "ELSE " if expression.args.get("else_") else "" 4469 condition = self.sql(expression, "expression") 4470 condition = f"WHEN {condition} THEN " if condition else else_ 4471 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4472 return f"{condition}{insert}"
4480 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4481 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4482 empty = expression.args.get("empty") 4483 empty = ( 4484 f"DEFAULT {empty} ON EMPTY" 4485 if isinstance(empty, exp.Expression) 4486 else self.sql(expression, "empty") 4487 ) 4488 4489 error = expression.args.get("error") 4490 error = ( 4491 f"DEFAULT {error} ON ERROR" 4492 if isinstance(error, exp.Expression) 4493 else self.sql(expression, "error") 4494 ) 4495 4496 if error and empty: 4497 error = ( 4498 f"{empty} {error}" 4499 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4500 else f"{error} {empty}" 4501 ) 4502 empty = "" 4503 4504 null = self.sql(expression, "null") 4505 4506 return f"{empty}{error}{null}"
4512 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4513 this = self.sql(expression, "this") 4514 path = self.sql(expression, "path") 4515 4516 passing = self.expressions(expression, "passing") 4517 passing = f" PASSING {passing}" if passing else "" 4518 4519 on_condition = self.sql(expression, "on_condition") 4520 on_condition = f" {on_condition}" if on_condition else "" 4521 4522 path = f"{path}{passing}{on_condition}" 4523 4524 return self.func("JSON_EXISTS", this, path)
4526 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4527 array_agg = self.function_fallback_sql(expression) 4528 4529 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4530 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4531 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4532 parent = expression.parent 4533 if isinstance(parent, exp.Filter): 4534 parent_cond = parent.expression.this 4535 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4536 else: 4537 this = expression.this 4538 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4539 if this.find(exp.Column): 4540 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4541 this_sql = ( 4542 self.expressions(this) 4543 if isinstance(this, exp.Distinct) 4544 else self.sql(expression, "this") 4545 ) 4546 4547 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4548 4549 return array_agg
4557 def grant_sql(self, expression: exp.Grant) -> str: 4558 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4559 4560 kind = self.sql(expression, "kind") 4561 kind = f" {kind}" if kind else "" 4562 4563 securable = self.sql(expression, "securable") 4564 securable = f" {securable}" if securable else "" 4565 4566 principals = self.expressions(expression, key="principals", flat=True) 4567 4568 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4569 4570 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4594 def overlay_sql(self, expression: exp.Overlay): 4595 this = self.sql(expression, "this") 4596 expr = self.sql(expression, "expression") 4597 from_sql = self.sql(expression, "from") 4598 for_sql = self.sql(expression, "for") 4599 for_sql = f" FOR {for_sql}" if for_sql else "" 4600 4601 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4607 def string_sql(self, expression: exp.String) -> str: 4608 this = expression.this 4609 zone = expression.args.get("zone") 4610 4611 if zone: 4612 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4613 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4614 # set for source_tz to transpile the time conversion before the STRING cast 4615 this = exp.ConvertTimezone( 4616 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4617 ) 4618 4619 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4629 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4630 filler = self.sql(expression, "this") 4631 filler = f" {filler}" if filler else "" 4632 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4633 return f"TRUNCATE{filler} {with_count}"
4635 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4636 if self.SUPPORTS_UNIX_SECONDS: 4637 return self.function_fallback_sql(expression) 4638 4639 start_ts = exp.cast( 4640 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4641 ) 4642 4643 return self.sql( 4644 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4645 )
4647 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4648 dim = expression.expression 4649 4650 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4651 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4652 if not (dim.is_int and dim.name == "1"): 4653 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4654 dim = None 4655 4656 # If dimension is required but not specified, default initialize it 4657 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4658 dim = exp.Literal.number(1) 4659 4660 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4662 def attach_sql(self, expression: exp.Attach) -> str: 4663 this = self.sql(expression, "this") 4664 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4665 expressions = self.expressions(expression) 4666 expressions = f" ({expressions})" if expressions else "" 4667 4668 return f"ATTACH{exists_sql} {this}{expressions}"
4682 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4683 this_sql = self.sql(expression, "this") 4684 if isinstance(expression.this, exp.Table): 4685 this_sql = f"TABLE {this_sql}" 4686 4687 return self.func( 4688 "FEATURES_AT_TIME", 4689 this_sql, 4690 expression.args.get("time"), 4691 expression.args.get("num_rows"), 4692 expression.args.get("ignore_feature_nulls"), 4693 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4700 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4701 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4702 encode = f"{encode} {self.sql(expression, 'this')}" 4703 4704 properties = expression.args.get("properties") 4705 if properties: 4706 encode = f"{encode} {self.properties(properties)}" 4707 4708 return encode
4710 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4711 this = self.sql(expression, "this") 4712 include = f"INCLUDE {this}" 4713 4714 column_def = self.sql(expression, "column_def") 4715 if column_def: 4716 include = f"{include} {column_def}" 4717 4718 alias = self.sql(expression, "alias") 4719 if alias: 4720 include = f"{include} AS {alias}" 4721 4722 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4728 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4729 partitions = self.expressions(expression, "partition_expressions") 4730 create = self.expressions(expression, "create_expressions") 4731 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4733 def partitionbyrangepropertydynamic_sql( 4734 self, expression: exp.PartitionByRangePropertyDynamic 4735 ) -> str: 4736 start = self.sql(expression, "start") 4737 end = self.sql(expression, "end") 4738 4739 every = expression.args["every"] 4740 if isinstance(every, exp.Interval) and every.this.is_string: 4741 every.this.replace(exp.Literal.number(every.name)) 4742 4743 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4756 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4757 kind = self.sql(expression, "kind") 4758 option = self.sql(expression, "option") 4759 option = f" {option}" if option else "" 4760 this = self.sql(expression, "this") 4761 this = f" {this}" if this else "" 4762 columns = self.expressions(expression) 4763 columns = f" {columns}" if columns else "" 4764 return f"{kind}{option} STATISTICS{this}{columns}"
4766 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4767 this = self.sql(expression, "this") 4768 columns = self.expressions(expression) 4769 inner_expression = self.sql(expression, "expression") 4770 inner_expression = f" {inner_expression}" if inner_expression else "" 4771 update_options = self.sql(expression, "update_options") 4772 update_options = f" {update_options} UPDATE" if update_options else "" 4773 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4784 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4785 kind = self.sql(expression, "kind") 4786 this = self.sql(expression, "this") 4787 this = f" {this}" if this else "" 4788 inner_expression = self.sql(expression, "expression") 4789 return f"VALIDATE {kind}{this}{inner_expression}"
4791 def analyze_sql(self, expression: exp.Analyze) -> str: 4792 options = self.expressions(expression, key="options", sep=" ") 4793 options = f" {options}" if options else "" 4794 kind = self.sql(expression, "kind") 4795 kind = f" {kind}" if kind else "" 4796 this = self.sql(expression, "this") 4797 this = f" {this}" if this else "" 4798 mode = self.sql(expression, "mode") 4799 mode = f" {mode}" if mode else "" 4800 properties = self.sql(expression, "properties") 4801 properties = f" {properties}" if properties else "" 4802 partition = self.sql(expression, "partition") 4803 partition = f" {partition}" if partition else "" 4804 inner_expression = self.sql(expression, "expression") 4805 inner_expression = f" {inner_expression}" if inner_expression else "" 4806 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4808 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4809 this = self.sql(expression, "this") 4810 namespaces = self.expressions(expression, key="namespaces") 4811 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4812 passing = self.expressions(expression, key="passing") 4813 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4814 columns = self.expressions(expression, key="columns") 4815 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4816 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4817 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4823 def export_sql(self, expression: exp.Export) -> str: 4824 this = self.sql(expression, "this") 4825 connection = self.sql(expression, "connection") 4826 connection = f"WITH CONNECTION {connection} " if connection else "" 4827 options = self.sql(expression, "options") 4828 return f"EXPORT DATA {connection}{options} AS {this}"
4833 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4834 variable = self.sql(expression, "this") 4835 default = self.sql(expression, "default") 4836 default = f" = {default}" if default else "" 4837 4838 kind = self.sql(expression, "kind") 4839 if isinstance(expression.args.get("kind"), exp.Schema): 4840 kind = f"TABLE {kind}" 4841 4842 return f"{variable} AS {kind}{default}"
4844 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4845 kind = self.sql(expression, "kind") 4846 this = self.sql(expression, "this") 4847 set = self.sql(expression, "expression") 4848 using = self.sql(expression, "using") 4849 using = f" USING {using}" if using else "" 4850 4851 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4852 4853 return f"{kind_sql} {this} SET {set}{using}"
def
combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4872 def put_sql(self, expression: exp.Put) -> str: 4873 props = expression.args.get("properties") 4874 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4875 this = self.sql(expression, "this") 4876 target = self.sql(expression, "target") 4877 return f"PUT {this} {target}{props_sql}"