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.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 204 exp.Uuid: lambda *_: "UUID()", 205 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 206 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 207 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 208 exp.VolatileProperty: lambda *_: "VOLATILE", 209 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 210 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 211 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 212 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 213 exp.ForceProperty: lambda *_: "FORCE", 214 } 215 216 # Whether null ordering is supported in order by 217 # True: Full Support, None: No support, False: No support for certain cases 218 # such as window specifications, aggregate functions etc 219 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 220 221 # Whether ignore nulls is inside the agg or outside. 222 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 223 IGNORE_NULLS_IN_FUNC = False 224 225 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 226 LOCKING_READS_SUPPORTED = False 227 228 # Whether the EXCEPT and INTERSECT operations can return duplicates 229 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 230 231 # Wrap derived values in parens, usually standard but spark doesn't support it 232 WRAP_DERIVED_VALUES = True 233 234 # Whether create function uses an AS before the RETURN 235 CREATE_FUNCTION_RETURN_AS = True 236 237 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 238 MATCHED_BY_SOURCE = True 239 240 # Whether the INTERVAL expression works only with values like '1 day' 241 SINGLE_STRING_INTERVAL = False 242 243 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 244 INTERVAL_ALLOWS_PLURAL_FORM = True 245 246 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 247 LIMIT_FETCH = "ALL" 248 249 # Whether limit and fetch allows expresions or just limits 250 LIMIT_ONLY_LITERALS = False 251 252 # Whether a table is allowed to be renamed with a db 253 RENAME_TABLE_WITH_DB = True 254 255 # The separator for grouping sets and rollups 256 GROUPINGS_SEP = "," 257 258 # The string used for creating an index on a table 259 INDEX_ON = "ON" 260 261 # Whether join hints should be generated 262 JOIN_HINTS = True 263 264 # Whether table hints should be generated 265 TABLE_HINTS = True 266 267 # Whether query hints should be generated 268 QUERY_HINTS = True 269 270 # What kind of separator to use for query hints 271 QUERY_HINT_SEP = ", " 272 273 # Whether comparing against booleans (e.g. x IS TRUE) is supported 274 IS_BOOL_ALLOWED = True 275 276 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 277 DUPLICATE_KEY_UPDATE_WITH_SET = True 278 279 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 280 LIMIT_IS_TOP = False 281 282 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 283 RETURNING_END = True 284 285 # Whether to generate an unquoted value for EXTRACT's date part argument 286 EXTRACT_ALLOWS_QUOTES = True 287 288 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 289 TZ_TO_WITH_TIME_ZONE = False 290 291 # Whether the NVL2 function is supported 292 NVL2_SUPPORTED = True 293 294 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 295 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 296 297 # Whether VALUES statements can be used as derived tables. 298 # MySQL 5 and Redshift do not allow this, so when False, it will convert 299 # SELECT * VALUES into SELECT UNION 300 VALUES_AS_TABLE = True 301 302 # Whether the word COLUMN is included when adding a column with ALTER TABLE 303 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 304 305 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 306 UNNEST_WITH_ORDINALITY = True 307 308 # Whether FILTER (WHERE cond) can be used for conditional aggregation 309 AGGREGATE_FILTER_SUPPORTED = True 310 311 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 312 SEMI_ANTI_JOIN_WITH_SIDE = True 313 314 # Whether to include the type of a computed column in the CREATE DDL 315 COMPUTED_COLUMN_WITH_TYPE = True 316 317 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 318 SUPPORTS_TABLE_COPY = True 319 320 # Whether parentheses are required around the table sample's expression 321 TABLESAMPLE_REQUIRES_PARENS = True 322 323 # Whether a table sample clause's size needs to be followed by the ROWS keyword 324 TABLESAMPLE_SIZE_IS_ROWS = True 325 326 # The keyword(s) to use when generating a sample clause 327 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 328 329 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 330 TABLESAMPLE_WITH_METHOD = True 331 332 # The keyword to use when specifying the seed of a sample clause 333 TABLESAMPLE_SEED_KEYWORD = "SEED" 334 335 # Whether COLLATE is a function instead of a binary operator 336 COLLATE_IS_FUNC = False 337 338 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 339 DATA_TYPE_SPECIFIERS_ALLOWED = False 340 341 # Whether conditions require booleans WHERE x = 0 vs WHERE x 342 ENSURE_BOOLS = False 343 344 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 345 CTE_RECURSIVE_KEYWORD_REQUIRED = True 346 347 # Whether CONCAT requires >1 arguments 348 SUPPORTS_SINGLE_ARG_CONCAT = True 349 350 # Whether LAST_DAY function supports a date part argument 351 LAST_DAY_SUPPORTS_DATE_PART = True 352 353 # Whether named columns are allowed in table aliases 354 SUPPORTS_TABLE_ALIAS_COLUMNS = True 355 356 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 357 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 358 359 # What delimiter to use for separating JSON key/value pairs 360 JSON_KEY_VALUE_PAIR_SEP = ":" 361 362 # INSERT OVERWRITE TABLE x override 363 INSERT_OVERWRITE = " OVERWRITE TABLE" 364 365 # Whether the SELECT .. INTO syntax is used instead of CTAS 366 SUPPORTS_SELECT_INTO = False 367 368 # Whether UNLOGGED tables can be created 369 SUPPORTS_UNLOGGED_TABLES = False 370 371 # Whether the CREATE TABLE LIKE statement is supported 372 SUPPORTS_CREATE_TABLE_LIKE = True 373 374 # Whether the LikeProperty needs to be specified inside of the schema clause 375 LIKE_PROPERTY_INSIDE_SCHEMA = False 376 377 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 378 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 379 MULTI_ARG_DISTINCT = True 380 381 # Whether the JSON extraction operators expect a value of type JSON 382 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 383 384 # Whether bracketed keys like ["foo"] are supported in JSON paths 385 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 386 387 # Whether to escape keys using single quotes in JSON paths 388 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 389 390 # The JSONPathPart expressions supported by this dialect 391 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 392 393 # Whether any(f(x) for x in array) can be implemented by this dialect 394 CAN_IMPLEMENT_ARRAY_ANY = False 395 396 # Whether the function TO_NUMBER is supported 397 SUPPORTS_TO_NUMBER = True 398 399 # Whether or not set op modifiers apply to the outer set op or select. 400 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 401 # True means limit 1 happens after the set op, False means it it happens on y. 402 SET_OP_MODIFIERS = True 403 404 # Whether parameters from COPY statement are wrapped in parentheses 405 COPY_PARAMS_ARE_WRAPPED = True 406 407 # Whether values of params are set with "=" token or empty space 408 COPY_PARAMS_EQ_REQUIRED = False 409 410 # Whether COPY statement has INTO keyword 411 COPY_HAS_INTO_KEYWORD = True 412 413 # Whether the conditional TRY(expression) function is supported 414 TRY_SUPPORTED = True 415 416 # Whether the UESCAPE syntax in unicode strings is supported 417 SUPPORTS_UESCAPE = True 418 419 # The keyword to use when generating a star projection with excluded columns 420 STAR_EXCEPT = "EXCEPT" 421 422 # The HEX function name 423 HEX_FUNC = "HEX" 424 425 # The keywords to use when prefixing & separating WITH based properties 426 WITH_PROPERTIES_PREFIX = "WITH" 427 428 # Whether to quote the generated expression of exp.JsonPath 429 QUOTE_JSON_PATH = True 430 431 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 432 PAD_FILL_PATTERN_IS_REQUIRED = False 433 434 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 435 SUPPORTS_EXPLODING_PROJECTIONS = True 436 437 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 438 ARRAY_CONCAT_IS_VAR_LEN = True 439 440 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 441 SUPPORTS_CONVERT_TIMEZONE = False 442 443 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 444 SUPPORTS_MEDIAN = True 445 446 # Whether UNIX_SECONDS(timestamp) is supported 447 SUPPORTS_UNIX_SECONDS = False 448 449 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 450 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 451 452 # The function name of the exp.ArraySize expression 453 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 454 455 # The syntax to use when altering the type of a column 456 ALTER_SET_TYPE = "SET DATA TYPE" 457 458 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 459 # None -> Doesn't support it at all 460 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 461 # True (Postgres) -> Explicitly requires it 462 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 463 464 TYPE_MAPPING = { 465 exp.DataType.Type.DATETIME2: "TIMESTAMP", 466 exp.DataType.Type.NCHAR: "CHAR", 467 exp.DataType.Type.NVARCHAR: "VARCHAR", 468 exp.DataType.Type.MEDIUMTEXT: "TEXT", 469 exp.DataType.Type.LONGTEXT: "TEXT", 470 exp.DataType.Type.TINYTEXT: "TEXT", 471 exp.DataType.Type.BLOB: "VARBINARY", 472 exp.DataType.Type.MEDIUMBLOB: "BLOB", 473 exp.DataType.Type.LONGBLOB: "BLOB", 474 exp.DataType.Type.TINYBLOB: "BLOB", 475 exp.DataType.Type.INET: "INET", 476 exp.DataType.Type.ROWVERSION: "VARBINARY", 477 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 478 } 479 480 TIME_PART_SINGULARS = { 481 "MICROSECONDS": "MICROSECOND", 482 "SECONDS": "SECOND", 483 "MINUTES": "MINUTE", 484 "HOURS": "HOUR", 485 "DAYS": "DAY", 486 "WEEKS": "WEEK", 487 "MONTHS": "MONTH", 488 "QUARTERS": "QUARTER", 489 "YEARS": "YEAR", 490 } 491 492 AFTER_HAVING_MODIFIER_TRANSFORMS = { 493 "cluster": lambda self, e: self.sql(e, "cluster"), 494 "distribute": lambda self, e: self.sql(e, "distribute"), 495 "sort": lambda self, e: self.sql(e, "sort"), 496 "windows": lambda self, e: ( 497 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 498 if e.args.get("windows") 499 else "" 500 ), 501 "qualify": lambda self, e: self.sql(e, "qualify"), 502 } 503 504 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 505 506 STRUCT_DELIMITER = ("<", ">") 507 508 PARAMETER_TOKEN = "@" 509 NAMED_PLACEHOLDER_TOKEN = ":" 510 511 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 512 513 PROPERTIES_LOCATION = { 514 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 515 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 516 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 520 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 522 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 525 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 527 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 529 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 530 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 531 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 532 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 534 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 537 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 538 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 539 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 540 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 541 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 542 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 543 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 544 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 545 exp.HeapProperty: exp.Properties.Location.POST_WITH, 546 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 547 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 548 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 551 exp.JournalProperty: exp.Properties.Location.POST_NAME, 552 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 553 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 554 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 555 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 556 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 557 exp.LogProperty: exp.Properties.Location.POST_NAME, 558 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 559 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 560 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 561 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 562 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 563 exp.Order: exp.Properties.Location.POST_SCHEMA, 564 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 565 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 566 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 568 exp.Property: exp.Properties.Location.POST_WITH, 569 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 575 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 577 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 578 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 579 exp.Set: exp.Properties.Location.POST_SCHEMA, 580 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 581 exp.SetProperty: exp.Properties.Location.POST_CREATE, 582 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 583 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 584 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 585 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 586 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 588 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.StorageHandlerProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 591 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.Tags: exp.Properties.Location.POST_WITH, 593 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 594 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 595 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 596 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 597 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 598 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 599 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 600 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 601 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 602 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 603 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 604 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 605 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 606 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 607 } 608 609 # Keywords that can't be used as unquoted identifier names 610 RESERVED_KEYWORDS: t.Set[str] = set() 611 612 # Expressions whose comments are separated from them for better formatting 613 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 614 exp.Command, 615 exp.Create, 616 exp.Describe, 617 exp.Delete, 618 exp.Drop, 619 exp.From, 620 exp.Insert, 621 exp.Join, 622 exp.MultitableInserts, 623 exp.Select, 624 exp.SetOperation, 625 exp.Update, 626 exp.Where, 627 exp.With, 628 ) 629 630 # Expressions that should not have their comments generated in maybe_comment 631 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 632 exp.Binary, 633 exp.SetOperation, 634 ) 635 636 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 637 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 638 exp.Column, 639 exp.Literal, 640 exp.Neg, 641 exp.Paren, 642 ) 643 644 PARAMETERIZABLE_TEXT_TYPES = { 645 exp.DataType.Type.NVARCHAR, 646 exp.DataType.Type.VARCHAR, 647 exp.DataType.Type.CHAR, 648 exp.DataType.Type.NCHAR, 649 } 650 651 # Expressions that need to have all CTEs under them bubbled up to them 652 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 653 654 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 655 656 __slots__ = ( 657 "pretty", 658 "identify", 659 "normalize", 660 "pad", 661 "_indent", 662 "normalize_functions", 663 "unsupported_level", 664 "max_unsupported", 665 "leading_comma", 666 "max_text_width", 667 "comments", 668 "dialect", 669 "unsupported_messages", 670 "_escaped_quote_end", 671 "_escaped_identifier_end", 672 "_next_name", 673 "_identifier_start", 674 "_identifier_end", 675 "_quote_json_path_key_using_brackets", 676 ) 677 678 def __init__( 679 self, 680 pretty: t.Optional[bool] = None, 681 identify: str | bool = False, 682 normalize: bool = False, 683 pad: int = 2, 684 indent: int = 2, 685 normalize_functions: t.Optional[str | bool] = None, 686 unsupported_level: ErrorLevel = ErrorLevel.WARN, 687 max_unsupported: int = 3, 688 leading_comma: bool = False, 689 max_text_width: int = 80, 690 comments: bool = True, 691 dialect: DialectType = None, 692 ): 693 import sqlglot 694 from sqlglot.dialects import Dialect 695 696 self.pretty = pretty if pretty is not None else sqlglot.pretty 697 self.identify = identify 698 self.normalize = normalize 699 self.pad = pad 700 self._indent = indent 701 self.unsupported_level = unsupported_level 702 self.max_unsupported = max_unsupported 703 self.leading_comma = leading_comma 704 self.max_text_width = max_text_width 705 self.comments = comments 706 self.dialect = Dialect.get_or_raise(dialect) 707 708 # This is both a Dialect property and a Generator argument, so we prioritize the latter 709 self.normalize_functions = ( 710 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 711 ) 712 713 self.unsupported_messages: t.List[str] = [] 714 self._escaped_quote_end: str = ( 715 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 716 ) 717 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 718 719 self._next_name = name_sequence("_t") 720 721 self._identifier_start = self.dialect.IDENTIFIER_START 722 self._identifier_end = self.dialect.IDENTIFIER_END 723 724 self._quote_json_path_key_using_brackets = True 725 726 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 727 """ 728 Generates the SQL string corresponding to the given syntax tree. 729 730 Args: 731 expression: The syntax tree. 732 copy: Whether to copy the expression. The generator performs mutations so 733 it is safer to copy. 734 735 Returns: 736 The SQL string corresponding to `expression`. 737 """ 738 if copy: 739 expression = expression.copy() 740 741 expression = self.preprocess(expression) 742 743 self.unsupported_messages = [] 744 sql = self.sql(expression).strip() 745 746 if self.pretty: 747 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 748 749 if self.unsupported_level == ErrorLevel.IGNORE: 750 return sql 751 752 if self.unsupported_level == ErrorLevel.WARN: 753 for msg in self.unsupported_messages: 754 logger.warning(msg) 755 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 756 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 757 758 return sql 759 760 def preprocess(self, expression: exp.Expression) -> exp.Expression: 761 """Apply generic preprocessing transformations to a given expression.""" 762 expression = self._move_ctes_to_top_level(expression) 763 764 if self.ENSURE_BOOLS: 765 from sqlglot.transforms import ensure_bools 766 767 expression = ensure_bools(expression) 768 769 return expression 770 771 def _move_ctes_to_top_level(self, expression: E) -> E: 772 if ( 773 not expression.parent 774 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 775 and any(node.parent is not expression for node in expression.find_all(exp.With)) 776 ): 777 from sqlglot.transforms import move_ctes_to_top_level 778 779 expression = move_ctes_to_top_level(expression) 780 return expression 781 782 def unsupported(self, message: str) -> None: 783 if self.unsupported_level == ErrorLevel.IMMEDIATE: 784 raise UnsupportedError(message) 785 self.unsupported_messages.append(message) 786 787 def sep(self, sep: str = " ") -> str: 788 return f"{sep.strip()}\n" if self.pretty else sep 789 790 def seg(self, sql: str, sep: str = " ") -> str: 791 return f"{self.sep(sep)}{sql}" 792 793 def pad_comment(self, comment: str) -> str: 794 comment = " " + comment if comment[0].strip() else comment 795 comment = comment + " " if comment[-1].strip() else comment 796 return comment 797 798 def maybe_comment( 799 self, 800 sql: str, 801 expression: t.Optional[exp.Expression] = None, 802 comments: t.Optional[t.List[str]] = None, 803 separated: bool = False, 804 ) -> str: 805 comments = ( 806 ((expression and expression.comments) if comments is None else comments) # type: ignore 807 if self.comments 808 else None 809 ) 810 811 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 812 return sql 813 814 comments_sql = " ".join( 815 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 816 ) 817 818 if not comments_sql: 819 return sql 820 821 comments_sql = self._replace_line_breaks(comments_sql) 822 823 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 824 return ( 825 f"{self.sep()}{comments_sql}{sql}" 826 if not sql or sql[0].isspace() 827 else f"{comments_sql}{self.sep()}{sql}" 828 ) 829 830 return f"{sql} {comments_sql}" 831 832 def wrap(self, expression: exp.Expression | str) -> str: 833 this_sql = ( 834 self.sql(expression) 835 if isinstance(expression, exp.UNWRAPPED_QUERIES) 836 else self.sql(expression, "this") 837 ) 838 if not this_sql: 839 return "()" 840 841 this_sql = self.indent(this_sql, level=1, pad=0) 842 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 843 844 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 845 original = self.identify 846 self.identify = False 847 result = func(*args, **kwargs) 848 self.identify = original 849 return result 850 851 def normalize_func(self, name: str) -> str: 852 if self.normalize_functions == "upper" or self.normalize_functions is True: 853 return name.upper() 854 if self.normalize_functions == "lower": 855 return name.lower() 856 return name 857 858 def indent( 859 self, 860 sql: str, 861 level: int = 0, 862 pad: t.Optional[int] = None, 863 skip_first: bool = False, 864 skip_last: bool = False, 865 ) -> str: 866 if not self.pretty or not sql: 867 return sql 868 869 pad = self.pad if pad is None else pad 870 lines = sql.split("\n") 871 872 return "\n".join( 873 ( 874 line 875 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 876 else f"{' ' * (level * self._indent + pad)}{line}" 877 ) 878 for i, line in enumerate(lines) 879 ) 880 881 def sql( 882 self, 883 expression: t.Optional[str | exp.Expression], 884 key: t.Optional[str] = None, 885 comment: bool = True, 886 ) -> str: 887 if not expression: 888 return "" 889 890 if isinstance(expression, str): 891 return expression 892 893 if key: 894 value = expression.args.get(key) 895 if value: 896 return self.sql(value) 897 return "" 898 899 transform = self.TRANSFORMS.get(expression.__class__) 900 901 if callable(transform): 902 sql = transform(self, expression) 903 elif isinstance(expression, exp.Expression): 904 exp_handler_name = f"{expression.key}_sql" 905 906 if hasattr(self, exp_handler_name): 907 sql = getattr(self, exp_handler_name)(expression) 908 elif isinstance(expression, exp.Func): 909 sql = self.function_fallback_sql(expression) 910 elif isinstance(expression, exp.Property): 911 sql = self.property_sql(expression) 912 else: 913 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 914 else: 915 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 916 917 return self.maybe_comment(sql, expression) if self.comments and comment else sql 918 919 def uncache_sql(self, expression: exp.Uncache) -> str: 920 table = self.sql(expression, "this") 921 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 922 return f"UNCACHE TABLE{exists_sql} {table}" 923 924 def cache_sql(self, expression: exp.Cache) -> str: 925 lazy = " LAZY" if expression.args.get("lazy") else "" 926 table = self.sql(expression, "this") 927 options = expression.args.get("options") 928 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 929 sql = self.sql(expression, "expression") 930 sql = f" AS{self.sep()}{sql}" if sql else "" 931 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 932 return self.prepend_ctes(expression, sql) 933 934 def characterset_sql(self, expression: exp.CharacterSet) -> str: 935 if isinstance(expression.parent, exp.Cast): 936 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 937 default = "DEFAULT " if expression.args.get("default") else "" 938 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 939 940 def column_parts(self, expression: exp.Column) -> str: 941 return ".".join( 942 self.sql(part) 943 for part in ( 944 expression.args.get("catalog"), 945 expression.args.get("db"), 946 expression.args.get("table"), 947 expression.args.get("this"), 948 ) 949 if part 950 ) 951 952 def column_sql(self, expression: exp.Column) -> str: 953 join_mark = " (+)" if expression.args.get("join_mark") else "" 954 955 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 956 join_mark = "" 957 self.unsupported("Outer join syntax using the (+) operator is not supported.") 958 959 return f"{self.column_parts(expression)}{join_mark}" 960 961 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 962 this = self.sql(expression, "this") 963 this = f" {this}" if this else "" 964 position = self.sql(expression, "position") 965 return f"{position}{this}" 966 967 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 968 column = self.sql(expression, "this") 969 kind = self.sql(expression, "kind") 970 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 971 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 972 kind = f"{sep}{kind}" if kind else "" 973 constraints = f" {constraints}" if constraints else "" 974 position = self.sql(expression, "position") 975 position = f" {position}" if position else "" 976 977 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 978 kind = "" 979 980 return f"{exists}{column}{kind}{constraints}{position}" 981 982 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 983 this = self.sql(expression, "this") 984 kind_sql = self.sql(expression, "kind").strip() 985 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 986 987 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 988 this = self.sql(expression, "this") 989 if expression.args.get("not_null"): 990 persisted = " PERSISTED NOT NULL" 991 elif expression.args.get("persisted"): 992 persisted = " PERSISTED" 993 else: 994 persisted = "" 995 return f"AS {this}{persisted}" 996 997 def autoincrementcolumnconstraint_sql(self, _) -> str: 998 return self.token_sql(TokenType.AUTO_INCREMENT) 999 1000 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1001 if isinstance(expression.this, list): 1002 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1003 else: 1004 this = self.sql(expression, "this") 1005 1006 return f"COMPRESS {this}" 1007 1008 def generatedasidentitycolumnconstraint_sql( 1009 self, expression: exp.GeneratedAsIdentityColumnConstraint 1010 ) -> str: 1011 this = "" 1012 if expression.this is not None: 1013 on_null = " ON NULL" if expression.args.get("on_null") else "" 1014 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1015 1016 start = expression.args.get("start") 1017 start = f"START WITH {start}" if start else "" 1018 increment = expression.args.get("increment") 1019 increment = f" INCREMENT BY {increment}" if increment else "" 1020 minvalue = expression.args.get("minvalue") 1021 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1022 maxvalue = expression.args.get("maxvalue") 1023 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1024 cycle = expression.args.get("cycle") 1025 cycle_sql = "" 1026 1027 if cycle is not None: 1028 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1029 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1030 1031 sequence_opts = "" 1032 if start or increment or cycle_sql: 1033 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1034 sequence_opts = f" ({sequence_opts.strip()})" 1035 1036 expr = self.sql(expression, "expression") 1037 expr = f"({expr})" if expr else "IDENTITY" 1038 1039 return f"GENERATED{this} AS {expr}{sequence_opts}" 1040 1041 def generatedasrowcolumnconstraint_sql( 1042 self, expression: exp.GeneratedAsRowColumnConstraint 1043 ) -> str: 1044 start = "START" if expression.args.get("start") else "END" 1045 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1046 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1047 1048 def periodforsystemtimeconstraint_sql( 1049 self, expression: exp.PeriodForSystemTimeConstraint 1050 ) -> str: 1051 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1052 1053 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1054 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1055 1056 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1057 return f"AS {self.sql(expression, 'this')}" 1058 1059 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1060 desc = expression.args.get("desc") 1061 if desc is not None: 1062 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1063 return "PRIMARY KEY" 1064 1065 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1066 this = self.sql(expression, "this") 1067 this = f" {this}" if this else "" 1068 index_type = expression.args.get("index_type") 1069 index_type = f" USING {index_type}" if index_type else "" 1070 on_conflict = self.sql(expression, "on_conflict") 1071 on_conflict = f" {on_conflict}" if on_conflict else "" 1072 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1073 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1074 1075 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1076 return self.sql(expression, "this") 1077 1078 def create_sql(self, expression: exp.Create) -> str: 1079 kind = self.sql(expression, "kind") 1080 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1081 properties = expression.args.get("properties") 1082 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1083 1084 this = self.createable_sql(expression, properties_locs) 1085 1086 properties_sql = "" 1087 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1088 exp.Properties.Location.POST_WITH 1089 ): 1090 properties_sql = self.sql( 1091 exp.Properties( 1092 expressions=[ 1093 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1094 *properties_locs[exp.Properties.Location.POST_WITH], 1095 ] 1096 ) 1097 ) 1098 1099 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1100 properties_sql = self.sep() + properties_sql 1101 elif not self.pretty: 1102 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1103 properties_sql = f" {properties_sql}" 1104 1105 begin = " BEGIN" if expression.args.get("begin") else "" 1106 end = " END" if expression.args.get("end") else "" 1107 1108 expression_sql = self.sql(expression, "expression") 1109 if expression_sql: 1110 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1111 1112 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1113 postalias_props_sql = "" 1114 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1115 postalias_props_sql = self.properties( 1116 exp.Properties( 1117 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1118 ), 1119 wrapped=False, 1120 ) 1121 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1122 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1123 1124 postindex_props_sql = "" 1125 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1126 postindex_props_sql = self.properties( 1127 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1128 wrapped=False, 1129 prefix=" ", 1130 ) 1131 1132 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1133 indexes = f" {indexes}" if indexes else "" 1134 index_sql = indexes + postindex_props_sql 1135 1136 replace = " OR REPLACE" if expression.args.get("replace") else "" 1137 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1138 unique = " UNIQUE" if expression.args.get("unique") else "" 1139 1140 clustered = expression.args.get("clustered") 1141 if clustered is None: 1142 clustered_sql = "" 1143 elif clustered: 1144 clustered_sql = " CLUSTERED COLUMNSTORE" 1145 else: 1146 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1147 1148 postcreate_props_sql = "" 1149 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1150 postcreate_props_sql = self.properties( 1151 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1152 sep=" ", 1153 prefix=" ", 1154 wrapped=False, 1155 ) 1156 1157 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1158 1159 postexpression_props_sql = "" 1160 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1161 postexpression_props_sql = self.properties( 1162 exp.Properties( 1163 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1164 ), 1165 sep=" ", 1166 prefix=" ", 1167 wrapped=False, 1168 ) 1169 1170 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1171 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1172 no_schema_binding = ( 1173 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1174 ) 1175 1176 clone = self.sql(expression, "clone") 1177 clone = f" {clone}" if clone else "" 1178 1179 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1180 properties_expression = f"{expression_sql}{properties_sql}" 1181 else: 1182 properties_expression = f"{properties_sql}{expression_sql}" 1183 1184 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1185 return self.prepend_ctes(expression, expression_sql) 1186 1187 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1188 start = self.sql(expression, "start") 1189 start = f"START WITH {start}" if start else "" 1190 increment = self.sql(expression, "increment") 1191 increment = f" INCREMENT BY {increment}" if increment else "" 1192 minvalue = self.sql(expression, "minvalue") 1193 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1194 maxvalue = self.sql(expression, "maxvalue") 1195 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1196 owned = self.sql(expression, "owned") 1197 owned = f" OWNED BY {owned}" if owned else "" 1198 1199 cache = expression.args.get("cache") 1200 if cache is None: 1201 cache_str = "" 1202 elif cache is True: 1203 cache_str = " CACHE" 1204 else: 1205 cache_str = f" CACHE {cache}" 1206 1207 options = self.expressions(expression, key="options", flat=True, sep=" ") 1208 options = f" {options}" if options else "" 1209 1210 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1211 1212 def clone_sql(self, expression: exp.Clone) -> str: 1213 this = self.sql(expression, "this") 1214 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1215 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1216 return f"{shallow}{keyword} {this}" 1217 1218 def describe_sql(self, expression: exp.Describe) -> str: 1219 style = expression.args.get("style") 1220 style = f" {style}" if style else "" 1221 partition = self.sql(expression, "partition") 1222 partition = f" {partition}" if partition else "" 1223 format = self.sql(expression, "format") 1224 format = f" {format}" if format else "" 1225 1226 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1227 1228 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1229 tag = self.sql(expression, "tag") 1230 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1231 1232 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1233 with_ = self.sql(expression, "with") 1234 if with_: 1235 sql = f"{with_}{self.sep()}{sql}" 1236 return sql 1237 1238 def with_sql(self, expression: exp.With) -> str: 1239 sql = self.expressions(expression, flat=True) 1240 recursive = ( 1241 "RECURSIVE " 1242 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1243 else "" 1244 ) 1245 search = self.sql(expression, "search") 1246 search = f" {search}" if search else "" 1247 1248 return f"WITH {recursive}{sql}{search}" 1249 1250 def cte_sql(self, expression: exp.CTE) -> str: 1251 alias = expression.args.get("alias") 1252 if alias: 1253 alias.add_comments(expression.pop_comments()) 1254 1255 alias_sql = self.sql(expression, "alias") 1256 1257 materialized = expression.args.get("materialized") 1258 if materialized is False: 1259 materialized = "NOT MATERIALIZED " 1260 elif materialized: 1261 materialized = "MATERIALIZED " 1262 1263 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1264 1265 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1266 alias = self.sql(expression, "this") 1267 columns = self.expressions(expression, key="columns", flat=True) 1268 columns = f"({columns})" if columns else "" 1269 1270 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1271 columns = "" 1272 self.unsupported("Named columns are not supported in table alias.") 1273 1274 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1275 alias = self._next_name() 1276 1277 return f"{alias}{columns}" 1278 1279 def bitstring_sql(self, expression: exp.BitString) -> str: 1280 this = self.sql(expression, "this") 1281 if self.dialect.BIT_START: 1282 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1283 return f"{int(this, 2)}" 1284 1285 def hexstring_sql( 1286 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1287 ) -> str: 1288 this = self.sql(expression, "this") 1289 is_integer_type = expression.args.get("is_integer") 1290 1291 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1292 not self.dialect.HEX_START and not binary_function_repr 1293 ): 1294 # Integer representation will be returned if: 1295 # - The read dialect treats the hex value as integer literal but not the write 1296 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1297 return f"{int(this, 16)}" 1298 1299 if not is_integer_type: 1300 # Read dialect treats the hex value as BINARY/BLOB 1301 if binary_function_repr: 1302 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1303 return self.func(binary_function_repr, exp.Literal.string(this)) 1304 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1305 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1306 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1307 1308 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1309 1310 def bytestring_sql(self, expression: exp.ByteString) -> str: 1311 this = self.sql(expression, "this") 1312 if self.dialect.BYTE_START: 1313 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1314 return this 1315 1316 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1317 this = self.sql(expression, "this") 1318 escape = expression.args.get("escape") 1319 1320 if self.dialect.UNICODE_START: 1321 escape_substitute = r"\\\1" 1322 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1323 else: 1324 escape_substitute = r"\\u\1" 1325 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1326 1327 if escape: 1328 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1329 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1330 else: 1331 escape_pattern = ESCAPED_UNICODE_RE 1332 escape_sql = "" 1333 1334 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1335 this = escape_pattern.sub(escape_substitute, this) 1336 1337 return f"{left_quote}{this}{right_quote}{escape_sql}" 1338 1339 def rawstring_sql(self, expression: exp.RawString) -> str: 1340 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1341 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1342 1343 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1344 this = self.sql(expression, "this") 1345 specifier = self.sql(expression, "expression") 1346 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1347 return f"{this}{specifier}" 1348 1349 def datatype_sql(self, expression: exp.DataType) -> str: 1350 nested = "" 1351 values = "" 1352 interior = self.expressions(expression, flat=True) 1353 1354 type_value = expression.this 1355 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1356 type_sql = self.sql(expression, "kind") 1357 else: 1358 type_sql = ( 1359 self.TYPE_MAPPING.get(type_value, type_value.value) 1360 if isinstance(type_value, exp.DataType.Type) 1361 else type_value 1362 ) 1363 1364 if interior: 1365 if expression.args.get("nested"): 1366 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1367 if expression.args.get("values") is not None: 1368 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1369 values = self.expressions(expression, key="values", flat=True) 1370 values = f"{delimiters[0]}{values}{delimiters[1]}" 1371 elif type_value == exp.DataType.Type.INTERVAL: 1372 nested = f" {interior}" 1373 else: 1374 nested = f"({interior})" 1375 1376 type_sql = f"{type_sql}{nested}{values}" 1377 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1378 exp.DataType.Type.TIMETZ, 1379 exp.DataType.Type.TIMESTAMPTZ, 1380 ): 1381 type_sql = f"{type_sql} WITH TIME ZONE" 1382 1383 return type_sql 1384 1385 def directory_sql(self, expression: exp.Directory) -> str: 1386 local = "LOCAL " if expression.args.get("local") else "" 1387 row_format = self.sql(expression, "row_format") 1388 row_format = f" {row_format}" if row_format else "" 1389 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1390 1391 def delete_sql(self, expression: exp.Delete) -> str: 1392 this = self.sql(expression, "this") 1393 this = f" FROM {this}" if this else "" 1394 using = self.sql(expression, "using") 1395 using = f" USING {using}" if using else "" 1396 cluster = self.sql(expression, "cluster") 1397 cluster = f" {cluster}" if cluster else "" 1398 where = self.sql(expression, "where") 1399 returning = self.sql(expression, "returning") 1400 limit = self.sql(expression, "limit") 1401 tables = self.expressions(expression, key="tables") 1402 tables = f" {tables}" if tables else "" 1403 if self.RETURNING_END: 1404 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1405 else: 1406 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1407 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1408 1409 def drop_sql(self, expression: exp.Drop) -> str: 1410 this = self.sql(expression, "this") 1411 expressions = self.expressions(expression, flat=True) 1412 expressions = f" ({expressions})" if expressions else "" 1413 kind = expression.args["kind"] 1414 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1415 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1416 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1417 on_cluster = self.sql(expression, "cluster") 1418 on_cluster = f" {on_cluster}" if on_cluster else "" 1419 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1420 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1421 cascade = " CASCADE" if expression.args.get("cascade") else "" 1422 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1423 purge = " PURGE" if expression.args.get("purge") else "" 1424 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1425 1426 def set_operation(self, expression: exp.SetOperation) -> str: 1427 op_type = type(expression) 1428 op_name = op_type.key.upper() 1429 1430 distinct = expression.args.get("distinct") 1431 if ( 1432 distinct is False 1433 and op_type in (exp.Except, exp.Intersect) 1434 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1435 ): 1436 self.unsupported(f"{op_name} ALL is not supported") 1437 1438 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1439 1440 if distinct is None: 1441 distinct = default_distinct 1442 if distinct is None: 1443 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1444 1445 if distinct is default_distinct: 1446 kind = "" 1447 else: 1448 kind = " DISTINCT" if distinct else " ALL" 1449 1450 by_name = " BY NAME" if expression.args.get("by_name") else "" 1451 return f"{op_name}{kind}{by_name}" 1452 1453 def set_operations(self, expression: exp.SetOperation) -> str: 1454 if not self.SET_OP_MODIFIERS: 1455 limit = expression.args.get("limit") 1456 order = expression.args.get("order") 1457 1458 if limit or order: 1459 select = self._move_ctes_to_top_level( 1460 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1461 ) 1462 1463 if limit: 1464 select = select.limit(limit.pop(), copy=False) 1465 if order: 1466 select = select.order_by(order.pop(), copy=False) 1467 return self.sql(select) 1468 1469 sqls: t.List[str] = [] 1470 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1471 1472 while stack: 1473 node = stack.pop() 1474 1475 if isinstance(node, exp.SetOperation): 1476 stack.append(node.expression) 1477 stack.append( 1478 self.maybe_comment( 1479 self.set_operation(node), comments=node.comments, separated=True 1480 ) 1481 ) 1482 stack.append(node.this) 1483 else: 1484 sqls.append(self.sql(node)) 1485 1486 this = self.sep().join(sqls) 1487 this = self.query_modifiers(expression, this) 1488 return self.prepend_ctes(expression, this) 1489 1490 def fetch_sql(self, expression: exp.Fetch) -> str: 1491 direction = expression.args.get("direction") 1492 direction = f" {direction}" if direction else "" 1493 count = self.sql(expression, "count") 1494 count = f" {count}" if count else "" 1495 limit_options = self.sql(expression, "limit_options") 1496 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1497 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1498 1499 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1500 percent = " PERCENT" if expression.args.get("percent") else "" 1501 rows = " ROWS" if expression.args.get("rows") else "" 1502 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1503 if not with_ties and rows: 1504 with_ties = " ONLY" 1505 return f"{percent}{rows}{with_ties}" 1506 1507 def filter_sql(self, expression: exp.Filter) -> str: 1508 if self.AGGREGATE_FILTER_SUPPORTED: 1509 this = self.sql(expression, "this") 1510 where = self.sql(expression, "expression").strip() 1511 return f"{this} FILTER({where})" 1512 1513 agg = expression.this 1514 agg_arg = agg.this 1515 cond = expression.expression.this 1516 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1517 return self.sql(agg) 1518 1519 def hint_sql(self, expression: exp.Hint) -> str: 1520 if not self.QUERY_HINTS: 1521 self.unsupported("Hints are not supported") 1522 return "" 1523 1524 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1525 1526 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1527 using = self.sql(expression, "using") 1528 using = f" USING {using}" if using else "" 1529 columns = self.expressions(expression, key="columns", flat=True) 1530 columns = f"({columns})" if columns else "" 1531 partition_by = self.expressions(expression, key="partition_by", flat=True) 1532 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1533 where = self.sql(expression, "where") 1534 include = self.expressions(expression, key="include", flat=True) 1535 if include: 1536 include = f" INCLUDE ({include})" 1537 with_storage = self.expressions(expression, key="with_storage", flat=True) 1538 with_storage = f" WITH ({with_storage})" if with_storage else "" 1539 tablespace = self.sql(expression, "tablespace") 1540 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1541 on = self.sql(expression, "on") 1542 on = f" ON {on}" if on else "" 1543 1544 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1545 1546 def index_sql(self, expression: exp.Index) -> str: 1547 unique = "UNIQUE " if expression.args.get("unique") else "" 1548 primary = "PRIMARY " if expression.args.get("primary") else "" 1549 amp = "AMP " if expression.args.get("amp") else "" 1550 name = self.sql(expression, "this") 1551 name = f"{name} " if name else "" 1552 table = self.sql(expression, "table") 1553 table = f"{self.INDEX_ON} {table}" if table else "" 1554 1555 index = "INDEX " if not table else "" 1556 1557 params = self.sql(expression, "params") 1558 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1559 1560 def identifier_sql(self, expression: exp.Identifier) -> str: 1561 text = expression.name 1562 lower = text.lower() 1563 text = lower if self.normalize and not expression.quoted else text 1564 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1565 if ( 1566 expression.quoted 1567 or self.dialect.can_identify(text, self.identify) 1568 or lower in self.RESERVED_KEYWORDS 1569 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1570 ): 1571 text = f"{self._identifier_start}{text}{self._identifier_end}" 1572 return text 1573 1574 def hex_sql(self, expression: exp.Hex) -> str: 1575 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1576 if self.dialect.HEX_LOWERCASE: 1577 text = self.func("LOWER", text) 1578 1579 return text 1580 1581 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1582 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1583 if not self.dialect.HEX_LOWERCASE: 1584 text = self.func("LOWER", text) 1585 return text 1586 1587 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1588 input_format = self.sql(expression, "input_format") 1589 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1590 output_format = self.sql(expression, "output_format") 1591 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1592 return self.sep().join((input_format, output_format)) 1593 1594 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1595 string = self.sql(exp.Literal.string(expression.name)) 1596 return f"{prefix}{string}" 1597 1598 def partition_sql(self, expression: exp.Partition) -> str: 1599 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1600 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1601 1602 def properties_sql(self, expression: exp.Properties) -> str: 1603 root_properties = [] 1604 with_properties = [] 1605 1606 for p in expression.expressions: 1607 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1608 if p_loc == exp.Properties.Location.POST_WITH: 1609 with_properties.append(p) 1610 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1611 root_properties.append(p) 1612 1613 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1614 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1615 1616 if root_props and with_props and not self.pretty: 1617 with_props = " " + with_props 1618 1619 return root_props + with_props 1620 1621 def root_properties(self, properties: exp.Properties) -> str: 1622 if properties.expressions: 1623 return self.expressions(properties, indent=False, sep=" ") 1624 return "" 1625 1626 def properties( 1627 self, 1628 properties: exp.Properties, 1629 prefix: str = "", 1630 sep: str = ", ", 1631 suffix: str = "", 1632 wrapped: bool = True, 1633 ) -> str: 1634 if properties.expressions: 1635 expressions = self.expressions(properties, sep=sep, indent=False) 1636 if expressions: 1637 expressions = self.wrap(expressions) if wrapped else expressions 1638 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1639 return "" 1640 1641 def with_properties(self, properties: exp.Properties) -> str: 1642 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1643 1644 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1645 properties_locs = defaultdict(list) 1646 for p in properties.expressions: 1647 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1648 if p_loc != exp.Properties.Location.UNSUPPORTED: 1649 properties_locs[p_loc].append(p) 1650 else: 1651 self.unsupported(f"Unsupported property {p.key}") 1652 1653 return properties_locs 1654 1655 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1656 if isinstance(expression.this, exp.Dot): 1657 return self.sql(expression, "this") 1658 return f"'{expression.name}'" if string_key else expression.name 1659 1660 def property_sql(self, expression: exp.Property) -> str: 1661 property_cls = expression.__class__ 1662 if property_cls == exp.Property: 1663 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1664 1665 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1666 if not property_name: 1667 self.unsupported(f"Unsupported property {expression.key}") 1668 1669 return f"{property_name}={self.sql(expression, 'this')}" 1670 1671 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1672 if self.SUPPORTS_CREATE_TABLE_LIKE: 1673 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1674 options = f" {options}" if options else "" 1675 1676 like = f"LIKE {self.sql(expression, 'this')}{options}" 1677 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1678 like = f"({like})" 1679 1680 return like 1681 1682 if expression.expressions: 1683 self.unsupported("Transpilation of LIKE property options is unsupported") 1684 1685 select = exp.select("*").from_(expression.this).limit(0) 1686 return f"AS {self.sql(select)}" 1687 1688 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1689 no = "NO " if expression.args.get("no") else "" 1690 protection = " PROTECTION" if expression.args.get("protection") else "" 1691 return f"{no}FALLBACK{protection}" 1692 1693 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1694 no = "NO " if expression.args.get("no") else "" 1695 local = expression.args.get("local") 1696 local = f"{local} " if local else "" 1697 dual = "DUAL " if expression.args.get("dual") else "" 1698 before = "BEFORE " if expression.args.get("before") else "" 1699 after = "AFTER " if expression.args.get("after") else "" 1700 return f"{no}{local}{dual}{before}{after}JOURNAL" 1701 1702 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1703 freespace = self.sql(expression, "this") 1704 percent = " PERCENT" if expression.args.get("percent") else "" 1705 return f"FREESPACE={freespace}{percent}" 1706 1707 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1708 if expression.args.get("default"): 1709 property = "DEFAULT" 1710 elif expression.args.get("on"): 1711 property = "ON" 1712 else: 1713 property = "OFF" 1714 return f"CHECKSUM={property}" 1715 1716 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1717 if expression.args.get("no"): 1718 return "NO MERGEBLOCKRATIO" 1719 if expression.args.get("default"): 1720 return "DEFAULT MERGEBLOCKRATIO" 1721 1722 percent = " PERCENT" if expression.args.get("percent") else "" 1723 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1724 1725 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1726 default = expression.args.get("default") 1727 minimum = expression.args.get("minimum") 1728 maximum = expression.args.get("maximum") 1729 if default or minimum or maximum: 1730 if default: 1731 prop = "DEFAULT" 1732 elif minimum: 1733 prop = "MINIMUM" 1734 else: 1735 prop = "MAXIMUM" 1736 return f"{prop} DATABLOCKSIZE" 1737 units = expression.args.get("units") 1738 units = f" {units}" if units else "" 1739 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1740 1741 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1742 autotemp = expression.args.get("autotemp") 1743 always = expression.args.get("always") 1744 default = expression.args.get("default") 1745 manual = expression.args.get("manual") 1746 never = expression.args.get("never") 1747 1748 if autotemp is not None: 1749 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1750 elif always: 1751 prop = "ALWAYS" 1752 elif default: 1753 prop = "DEFAULT" 1754 elif manual: 1755 prop = "MANUAL" 1756 elif never: 1757 prop = "NEVER" 1758 return f"BLOCKCOMPRESSION={prop}" 1759 1760 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1761 no = expression.args.get("no") 1762 no = " NO" if no else "" 1763 concurrent = expression.args.get("concurrent") 1764 concurrent = " CONCURRENT" if concurrent else "" 1765 target = self.sql(expression, "target") 1766 target = f" {target}" if target else "" 1767 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1768 1769 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1770 if isinstance(expression.this, list): 1771 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1772 if expression.this: 1773 modulus = self.sql(expression, "this") 1774 remainder = self.sql(expression, "expression") 1775 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1776 1777 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1778 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1779 return f"FROM ({from_expressions}) TO ({to_expressions})" 1780 1781 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1782 this = self.sql(expression, "this") 1783 1784 for_values_or_default = expression.expression 1785 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1786 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1787 else: 1788 for_values_or_default = " DEFAULT" 1789 1790 return f"PARTITION OF {this}{for_values_or_default}" 1791 1792 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1793 kind = expression.args.get("kind") 1794 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1795 for_or_in = expression.args.get("for_or_in") 1796 for_or_in = f" {for_or_in}" if for_or_in else "" 1797 lock_type = expression.args.get("lock_type") 1798 override = " OVERRIDE" if expression.args.get("override") else "" 1799 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1800 1801 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1802 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1803 statistics = expression.args.get("statistics") 1804 statistics_sql = "" 1805 if statistics is not None: 1806 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1807 return f"{data_sql}{statistics_sql}" 1808 1809 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1810 this = self.sql(expression, "this") 1811 this = f"HISTORY_TABLE={this}" if this else "" 1812 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1813 data_consistency = ( 1814 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1815 ) 1816 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1817 retention_period = ( 1818 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1819 ) 1820 1821 if this: 1822 on_sql = self.func("ON", this, data_consistency, retention_period) 1823 else: 1824 on_sql = "ON" if expression.args.get("on") else "OFF" 1825 1826 sql = f"SYSTEM_VERSIONING={on_sql}" 1827 1828 return f"WITH({sql})" if expression.args.get("with") else sql 1829 1830 def insert_sql(self, expression: exp.Insert) -> str: 1831 hint = self.sql(expression, "hint") 1832 overwrite = expression.args.get("overwrite") 1833 1834 if isinstance(expression.this, exp.Directory): 1835 this = " OVERWRITE" if overwrite else " INTO" 1836 else: 1837 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1838 1839 stored = self.sql(expression, "stored") 1840 stored = f" {stored}" if stored else "" 1841 alternative = expression.args.get("alternative") 1842 alternative = f" OR {alternative}" if alternative else "" 1843 ignore = " IGNORE" if expression.args.get("ignore") else "" 1844 is_function = expression.args.get("is_function") 1845 if is_function: 1846 this = f"{this} FUNCTION" 1847 this = f"{this} {self.sql(expression, 'this')}" 1848 1849 exists = " IF EXISTS" if expression.args.get("exists") else "" 1850 where = self.sql(expression, "where") 1851 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1852 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1853 on_conflict = self.sql(expression, "conflict") 1854 on_conflict = f" {on_conflict}" if on_conflict else "" 1855 by_name = " BY NAME" if expression.args.get("by_name") else "" 1856 returning = self.sql(expression, "returning") 1857 1858 if self.RETURNING_END: 1859 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1860 else: 1861 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1862 1863 partition_by = self.sql(expression, "partition") 1864 partition_by = f" {partition_by}" if partition_by else "" 1865 settings = self.sql(expression, "settings") 1866 settings = f" {settings}" if settings else "" 1867 1868 source = self.sql(expression, "source") 1869 source = f"TABLE {source}" if source else "" 1870 1871 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1872 return self.prepend_ctes(expression, sql) 1873 1874 def introducer_sql(self, expression: exp.Introducer) -> str: 1875 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1876 1877 def kill_sql(self, expression: exp.Kill) -> str: 1878 kind = self.sql(expression, "kind") 1879 kind = f" {kind}" if kind else "" 1880 this = self.sql(expression, "this") 1881 this = f" {this}" if this else "" 1882 return f"KILL{kind}{this}" 1883 1884 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1885 return expression.name 1886 1887 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1888 return expression.name 1889 1890 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1891 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1892 1893 constraint = self.sql(expression, "constraint") 1894 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1895 1896 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1897 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1898 action = self.sql(expression, "action") 1899 1900 expressions = self.expressions(expression, flat=True) 1901 if expressions: 1902 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1903 expressions = f" {set_keyword}{expressions}" 1904 1905 where = self.sql(expression, "where") 1906 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1907 1908 def returning_sql(self, expression: exp.Returning) -> str: 1909 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1910 1911 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1912 fields = self.sql(expression, "fields") 1913 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1914 escaped = self.sql(expression, "escaped") 1915 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1916 items = self.sql(expression, "collection_items") 1917 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1918 keys = self.sql(expression, "map_keys") 1919 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1920 lines = self.sql(expression, "lines") 1921 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1922 null = self.sql(expression, "null") 1923 null = f" NULL DEFINED AS {null}" if null else "" 1924 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1925 1926 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1927 return f"WITH ({self.expressions(expression, flat=True)})" 1928 1929 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1930 this = f"{self.sql(expression, 'this')} INDEX" 1931 target = self.sql(expression, "target") 1932 target = f" FOR {target}" if target else "" 1933 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1934 1935 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1936 this = self.sql(expression, "this") 1937 kind = self.sql(expression, "kind") 1938 expr = self.sql(expression, "expression") 1939 return f"{this} ({kind} => {expr})" 1940 1941 def table_parts(self, expression: exp.Table) -> str: 1942 return ".".join( 1943 self.sql(part) 1944 for part in ( 1945 expression.args.get("catalog"), 1946 expression.args.get("db"), 1947 expression.args.get("this"), 1948 ) 1949 if part is not None 1950 ) 1951 1952 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1953 table = self.table_parts(expression) 1954 only = "ONLY " if expression.args.get("only") else "" 1955 partition = self.sql(expression, "partition") 1956 partition = f" {partition}" if partition else "" 1957 version = self.sql(expression, "version") 1958 version = f" {version}" if version else "" 1959 alias = self.sql(expression, "alias") 1960 alias = f"{sep}{alias}" if alias else "" 1961 1962 sample = self.sql(expression, "sample") 1963 if self.dialect.ALIAS_POST_TABLESAMPLE: 1964 sample_pre_alias = sample 1965 sample_post_alias = "" 1966 else: 1967 sample_pre_alias = "" 1968 sample_post_alias = sample 1969 1970 hints = self.expressions(expression, key="hints", sep=" ") 1971 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1972 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1973 joins = self.indent( 1974 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1975 ) 1976 laterals = self.expressions(expression, key="laterals", sep="") 1977 1978 file_format = self.sql(expression, "format") 1979 if file_format: 1980 pattern = self.sql(expression, "pattern") 1981 pattern = f", PATTERN => {pattern}" if pattern else "" 1982 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1983 1984 ordinality = expression.args.get("ordinality") or "" 1985 if ordinality: 1986 ordinality = f" WITH ORDINALITY{alias}" 1987 alias = "" 1988 1989 when = self.sql(expression, "when") 1990 if when: 1991 table = f"{table} {when}" 1992 1993 changes = self.sql(expression, "changes") 1994 changes = f" {changes}" if changes else "" 1995 1996 rows_from = self.expressions(expression, key="rows_from") 1997 if rows_from: 1998 table = f"ROWS FROM {self.wrap(rows_from)}" 1999 2000 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2001 2002 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2003 table = self.func("TABLE", expression.this) 2004 alias = self.sql(expression, "alias") 2005 alias = f" AS {alias}" if alias else "" 2006 sample = self.sql(expression, "sample") 2007 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2008 joins = self.indent( 2009 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2010 ) 2011 return f"{table}{alias}{pivots}{sample}{joins}" 2012 2013 def tablesample_sql( 2014 self, 2015 expression: exp.TableSample, 2016 tablesample_keyword: t.Optional[str] = None, 2017 ) -> str: 2018 method = self.sql(expression, "method") 2019 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2020 numerator = self.sql(expression, "bucket_numerator") 2021 denominator = self.sql(expression, "bucket_denominator") 2022 field = self.sql(expression, "bucket_field") 2023 field = f" ON {field}" if field else "" 2024 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2025 seed = self.sql(expression, "seed") 2026 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2027 2028 size = self.sql(expression, "size") 2029 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2030 size = f"{size} ROWS" 2031 2032 percent = self.sql(expression, "percent") 2033 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2034 percent = f"{percent} PERCENT" 2035 2036 expr = f"{bucket}{percent}{size}" 2037 if self.TABLESAMPLE_REQUIRES_PARENS: 2038 expr = f"({expr})" 2039 2040 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2041 2042 def pivot_sql(self, expression: exp.Pivot) -> str: 2043 expressions = self.expressions(expression, flat=True) 2044 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2045 2046 if expression.this: 2047 this = self.sql(expression, "this") 2048 if not expressions: 2049 return f"UNPIVOT {this}" 2050 2051 on = f"{self.seg('ON')} {expressions}" 2052 into = self.sql(expression, "into") 2053 into = f"{self.seg('INTO')} {into}" if into else "" 2054 using = self.expressions(expression, key="using", flat=True) 2055 using = f"{self.seg('USING')} {using}" if using else "" 2056 group = self.sql(expression, "group") 2057 return f"{direction} {this}{on}{into}{using}{group}" 2058 2059 alias = self.sql(expression, "alias") 2060 alias = f" AS {alias}" if alias else "" 2061 2062 field = self.sql(expression, "field") 2063 2064 include_nulls = expression.args.get("include_nulls") 2065 if include_nulls is not None: 2066 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2067 else: 2068 nulls = "" 2069 2070 default_on_null = self.sql(expression, "default_on_null") 2071 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2072 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2073 2074 def version_sql(self, expression: exp.Version) -> str: 2075 this = f"FOR {expression.name}" 2076 kind = expression.text("kind") 2077 expr = self.sql(expression, "expression") 2078 return f"{this} {kind} {expr}" 2079 2080 def tuple_sql(self, expression: exp.Tuple) -> str: 2081 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2082 2083 def update_sql(self, expression: exp.Update) -> str: 2084 this = self.sql(expression, "this") 2085 set_sql = self.expressions(expression, flat=True) 2086 from_sql = self.sql(expression, "from") 2087 where_sql = self.sql(expression, "where") 2088 returning = self.sql(expression, "returning") 2089 order = self.sql(expression, "order") 2090 limit = self.sql(expression, "limit") 2091 if self.RETURNING_END: 2092 expression_sql = f"{from_sql}{where_sql}{returning}" 2093 else: 2094 expression_sql = f"{returning}{from_sql}{where_sql}" 2095 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2096 return self.prepend_ctes(expression, sql) 2097 2098 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2099 values_as_table = values_as_table and self.VALUES_AS_TABLE 2100 2101 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2102 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2103 args = self.expressions(expression) 2104 alias = self.sql(expression, "alias") 2105 values = f"VALUES{self.seg('')}{args}" 2106 values = ( 2107 f"({values})" 2108 if self.WRAP_DERIVED_VALUES 2109 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2110 else values 2111 ) 2112 return f"{values} AS {alias}" if alias else values 2113 2114 # Converts `VALUES...` expression into a series of select unions. 2115 alias_node = expression.args.get("alias") 2116 column_names = alias_node and alias_node.columns 2117 2118 selects: t.List[exp.Query] = [] 2119 2120 for i, tup in enumerate(expression.expressions): 2121 row = tup.expressions 2122 2123 if i == 0 and column_names: 2124 row = [ 2125 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2126 ] 2127 2128 selects.append(exp.Select(expressions=row)) 2129 2130 if self.pretty: 2131 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2132 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2133 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2134 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2135 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2136 2137 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2138 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2139 return f"({unions}){alias}" 2140 2141 def var_sql(self, expression: exp.Var) -> str: 2142 return self.sql(expression, "this") 2143 2144 @unsupported_args("expressions") 2145 def into_sql(self, expression: exp.Into) -> str: 2146 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2147 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2148 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2149 2150 def from_sql(self, expression: exp.From) -> str: 2151 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2152 2153 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2154 grouping_sets = self.expressions(expression, indent=False) 2155 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2156 2157 def rollup_sql(self, expression: exp.Rollup) -> str: 2158 expressions = self.expressions(expression, indent=False) 2159 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2160 2161 def cube_sql(self, expression: exp.Cube) -> str: 2162 expressions = self.expressions(expression, indent=False) 2163 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2164 2165 def group_sql(self, expression: exp.Group) -> str: 2166 group_by_all = expression.args.get("all") 2167 if group_by_all is True: 2168 modifier = " ALL" 2169 elif group_by_all is False: 2170 modifier = " DISTINCT" 2171 else: 2172 modifier = "" 2173 2174 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2175 2176 grouping_sets = self.expressions(expression, key="grouping_sets") 2177 cube = self.expressions(expression, key="cube") 2178 rollup = self.expressions(expression, key="rollup") 2179 2180 groupings = csv( 2181 self.seg(grouping_sets) if grouping_sets else "", 2182 self.seg(cube) if cube else "", 2183 self.seg(rollup) if rollup else "", 2184 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2185 sep=self.GROUPINGS_SEP, 2186 ) 2187 2188 if ( 2189 expression.expressions 2190 and groupings 2191 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2192 ): 2193 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2194 2195 return f"{group_by}{groupings}" 2196 2197 def having_sql(self, expression: exp.Having) -> str: 2198 this = self.indent(self.sql(expression, "this")) 2199 return f"{self.seg('HAVING')}{self.sep()}{this}" 2200 2201 def connect_sql(self, expression: exp.Connect) -> str: 2202 start = self.sql(expression, "start") 2203 start = self.seg(f"START WITH {start}") if start else "" 2204 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2205 connect = self.sql(expression, "connect") 2206 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2207 return start + connect 2208 2209 def prior_sql(self, expression: exp.Prior) -> str: 2210 return f"PRIOR {self.sql(expression, 'this')}" 2211 2212 def join_sql(self, expression: exp.Join) -> str: 2213 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2214 side = None 2215 else: 2216 side = expression.side 2217 2218 op_sql = " ".join( 2219 op 2220 for op in ( 2221 expression.method, 2222 "GLOBAL" if expression.args.get("global") else None, 2223 side, 2224 expression.kind, 2225 expression.hint if self.JOIN_HINTS else None, 2226 ) 2227 if op 2228 ) 2229 match_cond = self.sql(expression, "match_condition") 2230 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2231 on_sql = self.sql(expression, "on") 2232 using = expression.args.get("using") 2233 2234 if not on_sql and using: 2235 on_sql = csv(*(self.sql(column) for column in using)) 2236 2237 this = expression.this 2238 this_sql = self.sql(this) 2239 2240 exprs = self.expressions(expression) 2241 if exprs: 2242 this_sql = f"{this_sql},{self.seg(exprs)}" 2243 2244 if on_sql: 2245 on_sql = self.indent(on_sql, skip_first=True) 2246 space = self.seg(" " * self.pad) if self.pretty else " " 2247 if using: 2248 on_sql = f"{space}USING ({on_sql})" 2249 else: 2250 on_sql = f"{space}ON {on_sql}" 2251 elif not op_sql: 2252 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2253 return f" {this_sql}" 2254 2255 return f", {this_sql}" 2256 2257 if op_sql != "STRAIGHT_JOIN": 2258 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2259 2260 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2261 2262 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2263 args = self.expressions(expression, flat=True) 2264 args = f"({args})" if len(args.split(",")) > 1 else args 2265 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2266 2267 def lateral_op(self, expression: exp.Lateral) -> str: 2268 cross_apply = expression.args.get("cross_apply") 2269 2270 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2271 if cross_apply is True: 2272 op = "INNER JOIN " 2273 elif cross_apply is False: 2274 op = "LEFT JOIN " 2275 else: 2276 op = "" 2277 2278 return f"{op}LATERAL" 2279 2280 def lateral_sql(self, expression: exp.Lateral) -> str: 2281 this = self.sql(expression, "this") 2282 2283 if expression.args.get("view"): 2284 alias = expression.args["alias"] 2285 columns = self.expressions(alias, key="columns", flat=True) 2286 table = f" {alias.name}" if alias.name else "" 2287 columns = f" AS {columns}" if columns else "" 2288 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2289 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2290 2291 alias = self.sql(expression, "alias") 2292 alias = f" AS {alias}" if alias else "" 2293 return f"{self.lateral_op(expression)} {this}{alias}" 2294 2295 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2296 this = self.sql(expression, "this") 2297 2298 args = [ 2299 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2300 for e in (expression.args.get(k) for k in ("offset", "expression")) 2301 if e 2302 ] 2303 2304 args_sql = ", ".join(self.sql(e) for e in args) 2305 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2306 expressions = self.expressions(expression, flat=True) 2307 limit_options = self.sql(expression, "limit_options") 2308 expressions = f" BY {expressions}" if expressions else "" 2309 2310 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2311 2312 def offset_sql(self, expression: exp.Offset) -> str: 2313 this = self.sql(expression, "this") 2314 value = expression.expression 2315 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2316 expressions = self.expressions(expression, flat=True) 2317 expressions = f" BY {expressions}" if expressions else "" 2318 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2319 2320 def setitem_sql(self, expression: exp.SetItem) -> str: 2321 kind = self.sql(expression, "kind") 2322 kind = f"{kind} " if kind else "" 2323 this = self.sql(expression, "this") 2324 expressions = self.expressions(expression) 2325 collate = self.sql(expression, "collate") 2326 collate = f" COLLATE {collate}" if collate else "" 2327 global_ = "GLOBAL " if expression.args.get("global") else "" 2328 return f"{global_}{kind}{this}{expressions}{collate}" 2329 2330 def set_sql(self, expression: exp.Set) -> str: 2331 expressions = f" {self.expressions(expression, flat=True)}" 2332 tag = " TAG" if expression.args.get("tag") else "" 2333 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2334 2335 def pragma_sql(self, expression: exp.Pragma) -> str: 2336 return f"PRAGMA {self.sql(expression, 'this')}" 2337 2338 def lock_sql(self, expression: exp.Lock) -> str: 2339 if not self.LOCKING_READS_SUPPORTED: 2340 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2341 return "" 2342 2343 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2344 expressions = self.expressions(expression, flat=True) 2345 expressions = f" OF {expressions}" if expressions else "" 2346 wait = expression.args.get("wait") 2347 2348 if wait is not None: 2349 if isinstance(wait, exp.Literal): 2350 wait = f" WAIT {self.sql(wait)}" 2351 else: 2352 wait = " NOWAIT" if wait else " SKIP LOCKED" 2353 2354 return f"{lock_type}{expressions}{wait or ''}" 2355 2356 def literal_sql(self, expression: exp.Literal) -> str: 2357 text = expression.this or "" 2358 if expression.is_string: 2359 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2360 return text 2361 2362 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2363 if self.dialect.ESCAPED_SEQUENCES: 2364 to_escaped = self.dialect.ESCAPED_SEQUENCES 2365 text = "".join( 2366 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2367 ) 2368 2369 return self._replace_line_breaks(text).replace( 2370 self.dialect.QUOTE_END, self._escaped_quote_end 2371 ) 2372 2373 def loaddata_sql(self, expression: exp.LoadData) -> str: 2374 local = " LOCAL" if expression.args.get("local") else "" 2375 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2376 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2377 this = f" INTO TABLE {self.sql(expression, 'this')}" 2378 partition = self.sql(expression, "partition") 2379 partition = f" {partition}" if partition else "" 2380 input_format = self.sql(expression, "input_format") 2381 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2382 serde = self.sql(expression, "serde") 2383 serde = f" SERDE {serde}" if serde else "" 2384 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2385 2386 def null_sql(self, *_) -> str: 2387 return "NULL" 2388 2389 def boolean_sql(self, expression: exp.Boolean) -> str: 2390 return "TRUE" if expression.this else "FALSE" 2391 2392 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2393 this = self.sql(expression, "this") 2394 this = f"{this} " if this else this 2395 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2396 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2397 2398 def withfill_sql(self, expression: exp.WithFill) -> str: 2399 from_sql = self.sql(expression, "from") 2400 from_sql = f" FROM {from_sql}" if from_sql else "" 2401 to_sql = self.sql(expression, "to") 2402 to_sql = f" TO {to_sql}" if to_sql else "" 2403 step_sql = self.sql(expression, "step") 2404 step_sql = f" STEP {step_sql}" if step_sql else "" 2405 interpolated_values = [ 2406 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2407 if isinstance(e, exp.Alias) 2408 else self.sql(e, "this") 2409 for e in expression.args.get("interpolate") or [] 2410 ] 2411 interpolate = ( 2412 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2413 ) 2414 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2415 2416 def cluster_sql(self, expression: exp.Cluster) -> str: 2417 return self.op_expressions("CLUSTER BY", expression) 2418 2419 def distribute_sql(self, expression: exp.Distribute) -> str: 2420 return self.op_expressions("DISTRIBUTE BY", expression) 2421 2422 def sort_sql(self, expression: exp.Sort) -> str: 2423 return self.op_expressions("SORT BY", expression) 2424 2425 def ordered_sql(self, expression: exp.Ordered) -> str: 2426 desc = expression.args.get("desc") 2427 asc = not desc 2428 2429 nulls_first = expression.args.get("nulls_first") 2430 nulls_last = not nulls_first 2431 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2432 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2433 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2434 2435 this = self.sql(expression, "this") 2436 2437 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2438 nulls_sort_change = "" 2439 if nulls_first and ( 2440 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2441 ): 2442 nulls_sort_change = " NULLS FIRST" 2443 elif ( 2444 nulls_last 2445 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2446 and not nulls_are_last 2447 ): 2448 nulls_sort_change = " NULLS LAST" 2449 2450 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2451 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2452 window = expression.find_ancestor(exp.Window, exp.Select) 2453 if isinstance(window, exp.Window) and window.args.get("spec"): 2454 self.unsupported( 2455 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2456 ) 2457 nulls_sort_change = "" 2458 elif self.NULL_ORDERING_SUPPORTED is False and ( 2459 (asc and nulls_sort_change == " NULLS LAST") 2460 or (desc and nulls_sort_change == " NULLS FIRST") 2461 ): 2462 # BigQuery does not allow these ordering/nulls combinations when used under 2463 # an aggregation func or under a window containing one 2464 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2465 2466 if isinstance(ancestor, exp.Window): 2467 ancestor = ancestor.this 2468 if isinstance(ancestor, exp.AggFunc): 2469 self.unsupported( 2470 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2471 ) 2472 nulls_sort_change = "" 2473 elif self.NULL_ORDERING_SUPPORTED is None: 2474 if expression.this.is_int: 2475 self.unsupported( 2476 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2477 ) 2478 elif not isinstance(expression.this, exp.Rand): 2479 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2480 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2481 nulls_sort_change = "" 2482 2483 with_fill = self.sql(expression, "with_fill") 2484 with_fill = f" {with_fill}" if with_fill else "" 2485 2486 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2487 2488 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2489 window_frame = self.sql(expression, "window_frame") 2490 window_frame = f"{window_frame} " if window_frame else "" 2491 2492 this = self.sql(expression, "this") 2493 2494 return f"{window_frame}{this}" 2495 2496 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2497 partition = self.partition_by_sql(expression) 2498 order = self.sql(expression, "order") 2499 measures = self.expressions(expression, key="measures") 2500 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2501 rows = self.sql(expression, "rows") 2502 rows = self.seg(rows) if rows else "" 2503 after = self.sql(expression, "after") 2504 after = self.seg(after) if after else "" 2505 pattern = self.sql(expression, "pattern") 2506 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2507 definition_sqls = [ 2508 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2509 for definition in expression.args.get("define", []) 2510 ] 2511 definitions = self.expressions(sqls=definition_sqls) 2512 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2513 body = "".join( 2514 ( 2515 partition, 2516 order, 2517 measures, 2518 rows, 2519 after, 2520 pattern, 2521 define, 2522 ) 2523 ) 2524 alias = self.sql(expression, "alias") 2525 alias = f" {alias}" if alias else "" 2526 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2527 2528 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2529 limit = expression.args.get("limit") 2530 2531 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2532 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2533 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2534 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2535 2536 return csv( 2537 *sqls, 2538 *[self.sql(join) for join in expression.args.get("joins") or []], 2539 self.sql(expression, "match"), 2540 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2541 self.sql(expression, "prewhere"), 2542 self.sql(expression, "where"), 2543 self.sql(expression, "connect"), 2544 self.sql(expression, "group"), 2545 self.sql(expression, "having"), 2546 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2547 self.sql(expression, "order"), 2548 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2549 *self.after_limit_modifiers(expression), 2550 self.options_modifier(expression), 2551 sep="", 2552 ) 2553 2554 def options_modifier(self, expression: exp.Expression) -> str: 2555 options = self.expressions(expression, key="options") 2556 return f" {options}" if options else "" 2557 2558 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2559 return "" 2560 2561 def offset_limit_modifiers( 2562 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2563 ) -> t.List[str]: 2564 return [ 2565 self.sql(expression, "offset") if fetch else self.sql(limit), 2566 self.sql(limit) if fetch else self.sql(expression, "offset"), 2567 ] 2568 2569 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2570 locks = self.expressions(expression, key="locks", sep=" ") 2571 locks = f" {locks}" if locks else "" 2572 return [locks, self.sql(expression, "sample")] 2573 2574 def select_sql(self, expression: exp.Select) -> str: 2575 into = expression.args.get("into") 2576 if not self.SUPPORTS_SELECT_INTO and into: 2577 into.pop() 2578 2579 hint = self.sql(expression, "hint") 2580 distinct = self.sql(expression, "distinct") 2581 distinct = f" {distinct}" if distinct else "" 2582 kind = self.sql(expression, "kind") 2583 2584 limit = expression.args.get("limit") 2585 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2586 top = self.limit_sql(limit, top=True) 2587 limit.pop() 2588 else: 2589 top = "" 2590 2591 expressions = self.expressions(expression) 2592 2593 if kind: 2594 if kind in self.SELECT_KINDS: 2595 kind = f" AS {kind}" 2596 else: 2597 if kind == "STRUCT": 2598 expressions = self.expressions( 2599 sqls=[ 2600 self.sql( 2601 exp.Struct( 2602 expressions=[ 2603 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2604 if isinstance(e, exp.Alias) 2605 else e 2606 for e in expression.expressions 2607 ] 2608 ) 2609 ) 2610 ] 2611 ) 2612 kind = "" 2613 2614 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2615 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2616 2617 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2618 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2619 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2620 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2621 sql = self.query_modifiers( 2622 expression, 2623 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2624 self.sql(expression, "into", comment=False), 2625 self.sql(expression, "from", comment=False), 2626 ) 2627 2628 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2629 if expression.args.get("with"): 2630 sql = self.maybe_comment(sql, expression) 2631 expression.pop_comments() 2632 2633 sql = self.prepend_ctes(expression, sql) 2634 2635 if not self.SUPPORTS_SELECT_INTO and into: 2636 if into.args.get("temporary"): 2637 table_kind = " TEMPORARY" 2638 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2639 table_kind = " UNLOGGED" 2640 else: 2641 table_kind = "" 2642 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2643 2644 return sql 2645 2646 def schema_sql(self, expression: exp.Schema) -> str: 2647 this = self.sql(expression, "this") 2648 sql = self.schema_columns_sql(expression) 2649 return f"{this} {sql}" if this and sql else this or sql 2650 2651 def schema_columns_sql(self, expression: exp.Schema) -> str: 2652 if expression.expressions: 2653 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2654 return "" 2655 2656 def star_sql(self, expression: exp.Star) -> str: 2657 except_ = self.expressions(expression, key="except", flat=True) 2658 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2659 replace = self.expressions(expression, key="replace", flat=True) 2660 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2661 rename = self.expressions(expression, key="rename", flat=True) 2662 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2663 return f"*{except_}{replace}{rename}" 2664 2665 def parameter_sql(self, expression: exp.Parameter) -> str: 2666 this = self.sql(expression, "this") 2667 return f"{self.PARAMETER_TOKEN}{this}" 2668 2669 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2670 this = self.sql(expression, "this") 2671 kind = expression.text("kind") 2672 if kind: 2673 kind = f"{kind}." 2674 return f"@@{kind}{this}" 2675 2676 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2677 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2678 2679 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2680 alias = self.sql(expression, "alias") 2681 alias = f"{sep}{alias}" if alias else "" 2682 sample = self.sql(expression, "sample") 2683 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2684 alias = f"{sample}{alias}" 2685 2686 # Set to None so it's not generated again by self.query_modifiers() 2687 expression.set("sample", None) 2688 2689 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2690 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2691 return self.prepend_ctes(expression, sql) 2692 2693 def qualify_sql(self, expression: exp.Qualify) -> str: 2694 this = self.indent(self.sql(expression, "this")) 2695 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2696 2697 def unnest_sql(self, expression: exp.Unnest) -> str: 2698 args = self.expressions(expression, flat=True) 2699 2700 alias = expression.args.get("alias") 2701 offset = expression.args.get("offset") 2702 2703 if self.UNNEST_WITH_ORDINALITY: 2704 if alias and isinstance(offset, exp.Expression): 2705 alias.append("columns", offset) 2706 2707 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2708 columns = alias.columns 2709 alias = self.sql(columns[0]) if columns else "" 2710 else: 2711 alias = self.sql(alias) 2712 2713 alias = f" AS {alias}" if alias else alias 2714 if self.UNNEST_WITH_ORDINALITY: 2715 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2716 else: 2717 if isinstance(offset, exp.Expression): 2718 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2719 elif offset: 2720 suffix = f"{alias} WITH OFFSET" 2721 else: 2722 suffix = alias 2723 2724 return f"UNNEST({args}){suffix}" 2725 2726 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2727 return "" 2728 2729 def where_sql(self, expression: exp.Where) -> str: 2730 this = self.indent(self.sql(expression, "this")) 2731 return f"{self.seg('WHERE')}{self.sep()}{this}" 2732 2733 def window_sql(self, expression: exp.Window) -> str: 2734 this = self.sql(expression, "this") 2735 partition = self.partition_by_sql(expression) 2736 order = expression.args.get("order") 2737 order = self.order_sql(order, flat=True) if order else "" 2738 spec = self.sql(expression, "spec") 2739 alias = self.sql(expression, "alias") 2740 over = self.sql(expression, "over") or "OVER" 2741 2742 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2743 2744 first = expression.args.get("first") 2745 if first is None: 2746 first = "" 2747 else: 2748 first = "FIRST" if first else "LAST" 2749 2750 if not partition and not order and not spec and alias: 2751 return f"{this} {alias}" 2752 2753 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2754 return f"{this} ({args})" 2755 2756 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2757 partition = self.expressions(expression, key="partition_by", flat=True) 2758 return f"PARTITION BY {partition}" if partition else "" 2759 2760 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2761 kind = self.sql(expression, "kind") 2762 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2763 end = ( 2764 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2765 or "CURRENT ROW" 2766 ) 2767 return f"{kind} BETWEEN {start} AND {end}" 2768 2769 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2770 this = self.sql(expression, "this") 2771 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2772 return f"{this} WITHIN GROUP ({expression_sql})" 2773 2774 def between_sql(self, expression: exp.Between) -> str: 2775 this = self.sql(expression, "this") 2776 low = self.sql(expression, "low") 2777 high = self.sql(expression, "high") 2778 return f"{this} BETWEEN {low} AND {high}" 2779 2780 def bracket_offset_expressions( 2781 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2782 ) -> t.List[exp.Expression]: 2783 return apply_index_offset( 2784 expression.this, 2785 expression.expressions, 2786 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2787 ) 2788 2789 def bracket_sql(self, expression: exp.Bracket) -> str: 2790 expressions = self.bracket_offset_expressions(expression) 2791 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2792 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2793 2794 def all_sql(self, expression: exp.All) -> str: 2795 return f"ALL {self.wrap(expression)}" 2796 2797 def any_sql(self, expression: exp.Any) -> str: 2798 this = self.sql(expression, "this") 2799 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2800 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2801 this = self.wrap(this) 2802 return f"ANY{this}" 2803 return f"ANY {this}" 2804 2805 def exists_sql(self, expression: exp.Exists) -> str: 2806 return f"EXISTS{self.wrap(expression)}" 2807 2808 def case_sql(self, expression: exp.Case) -> str: 2809 this = self.sql(expression, "this") 2810 statements = [f"CASE {this}" if this else "CASE"] 2811 2812 for e in expression.args["ifs"]: 2813 statements.append(f"WHEN {self.sql(e, 'this')}") 2814 statements.append(f"THEN {self.sql(e, 'true')}") 2815 2816 default = self.sql(expression, "default") 2817 2818 if default: 2819 statements.append(f"ELSE {default}") 2820 2821 statements.append("END") 2822 2823 if self.pretty and self.too_wide(statements): 2824 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2825 2826 return " ".join(statements) 2827 2828 def constraint_sql(self, expression: exp.Constraint) -> str: 2829 this = self.sql(expression, "this") 2830 expressions = self.expressions(expression, flat=True) 2831 return f"CONSTRAINT {this} {expressions}" 2832 2833 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2834 order = expression.args.get("order") 2835 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2836 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2837 2838 def extract_sql(self, expression: exp.Extract) -> str: 2839 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2840 expression_sql = self.sql(expression, "expression") 2841 return f"EXTRACT({this} FROM {expression_sql})" 2842 2843 def trim_sql(self, expression: exp.Trim) -> str: 2844 trim_type = self.sql(expression, "position") 2845 2846 if trim_type == "LEADING": 2847 func_name = "LTRIM" 2848 elif trim_type == "TRAILING": 2849 func_name = "RTRIM" 2850 else: 2851 func_name = "TRIM" 2852 2853 return self.func(func_name, expression.this, expression.expression) 2854 2855 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2856 args = expression.expressions 2857 if isinstance(expression, exp.ConcatWs): 2858 args = args[1:] # Skip the delimiter 2859 2860 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2861 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2862 2863 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2864 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2865 2866 return args 2867 2868 def concat_sql(self, expression: exp.Concat) -> str: 2869 expressions = self.convert_concat_args(expression) 2870 2871 # Some dialects don't allow a single-argument CONCAT call 2872 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2873 return self.sql(expressions[0]) 2874 2875 return self.func("CONCAT", *expressions) 2876 2877 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2878 return self.func( 2879 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2880 ) 2881 2882 def check_sql(self, expression: exp.Check) -> str: 2883 this = self.sql(expression, key="this") 2884 return f"CHECK ({this})" 2885 2886 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2887 expressions = self.expressions(expression, flat=True) 2888 expressions = f" ({expressions})" if expressions else "" 2889 reference = self.sql(expression, "reference") 2890 reference = f" {reference}" if reference else "" 2891 delete = self.sql(expression, "delete") 2892 delete = f" ON DELETE {delete}" if delete else "" 2893 update = self.sql(expression, "update") 2894 update = f" ON UPDATE {update}" if update else "" 2895 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2896 2897 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2898 expressions = self.expressions(expression, flat=True) 2899 options = self.expressions(expression, key="options", flat=True, sep=" ") 2900 options = f" {options}" if options else "" 2901 return f"PRIMARY KEY ({expressions}){options}" 2902 2903 def if_sql(self, expression: exp.If) -> str: 2904 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2905 2906 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2907 modifier = expression.args.get("modifier") 2908 modifier = f" {modifier}" if modifier else "" 2909 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2910 2911 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2912 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2913 2914 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2915 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2916 2917 if expression.args.get("escape"): 2918 path = self.escape_str(path) 2919 2920 if self.QUOTE_JSON_PATH: 2921 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2922 2923 return path 2924 2925 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2926 if isinstance(expression, exp.JSONPathPart): 2927 transform = self.TRANSFORMS.get(expression.__class__) 2928 if not callable(transform): 2929 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2930 return "" 2931 2932 return transform(self, expression) 2933 2934 if isinstance(expression, int): 2935 return str(expression) 2936 2937 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2938 escaped = expression.replace("'", "\\'") 2939 escaped = f"\\'{expression}\\'" 2940 else: 2941 escaped = expression.replace('"', '\\"') 2942 escaped = f'"{escaped}"' 2943 2944 return escaped 2945 2946 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2947 return f"{self.sql(expression, 'this')} FORMAT JSON" 2948 2949 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2950 null_handling = expression.args.get("null_handling") 2951 null_handling = f" {null_handling}" if null_handling else "" 2952 2953 unique_keys = expression.args.get("unique_keys") 2954 if unique_keys is not None: 2955 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2956 else: 2957 unique_keys = "" 2958 2959 return_type = self.sql(expression, "return_type") 2960 return_type = f" RETURNING {return_type}" if return_type else "" 2961 encoding = self.sql(expression, "encoding") 2962 encoding = f" ENCODING {encoding}" if encoding else "" 2963 2964 return self.func( 2965 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2966 *expression.expressions, 2967 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2968 ) 2969 2970 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2971 return self.jsonobject_sql(expression) 2972 2973 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2974 null_handling = expression.args.get("null_handling") 2975 null_handling = f" {null_handling}" if null_handling else "" 2976 return_type = self.sql(expression, "return_type") 2977 return_type = f" RETURNING {return_type}" if return_type else "" 2978 strict = " STRICT" if expression.args.get("strict") else "" 2979 return self.func( 2980 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2981 ) 2982 2983 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2984 this = self.sql(expression, "this") 2985 order = self.sql(expression, "order") 2986 null_handling = expression.args.get("null_handling") 2987 null_handling = f" {null_handling}" if null_handling else "" 2988 return_type = self.sql(expression, "return_type") 2989 return_type = f" RETURNING {return_type}" if return_type else "" 2990 strict = " STRICT" if expression.args.get("strict") else "" 2991 return self.func( 2992 "JSON_ARRAYAGG", 2993 this, 2994 suffix=f"{order}{null_handling}{return_type}{strict})", 2995 ) 2996 2997 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2998 path = self.sql(expression, "path") 2999 path = f" PATH {path}" if path else "" 3000 nested_schema = self.sql(expression, "nested_schema") 3001 3002 if nested_schema: 3003 return f"NESTED{path} {nested_schema}" 3004 3005 this = self.sql(expression, "this") 3006 kind = self.sql(expression, "kind") 3007 kind = f" {kind}" if kind else "" 3008 return f"{this}{kind}{path}" 3009 3010 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3011 return self.func("COLUMNS", *expression.expressions) 3012 3013 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3014 this = self.sql(expression, "this") 3015 path = self.sql(expression, "path") 3016 path = f", {path}" if path else "" 3017 error_handling = expression.args.get("error_handling") 3018 error_handling = f" {error_handling}" if error_handling else "" 3019 empty_handling = expression.args.get("empty_handling") 3020 empty_handling = f" {empty_handling}" if empty_handling else "" 3021 schema = self.sql(expression, "schema") 3022 return self.func( 3023 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3024 ) 3025 3026 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3027 this = self.sql(expression, "this") 3028 kind = self.sql(expression, "kind") 3029 path = self.sql(expression, "path") 3030 path = f" {path}" if path else "" 3031 as_json = " AS JSON" if expression.args.get("as_json") else "" 3032 return f"{this} {kind}{path}{as_json}" 3033 3034 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3035 this = self.sql(expression, "this") 3036 path = self.sql(expression, "path") 3037 path = f", {path}" if path else "" 3038 expressions = self.expressions(expression) 3039 with_ = ( 3040 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3041 if expressions 3042 else "" 3043 ) 3044 return f"OPENJSON({this}{path}){with_}" 3045 3046 def in_sql(self, expression: exp.In) -> str: 3047 query = expression.args.get("query") 3048 unnest = expression.args.get("unnest") 3049 field = expression.args.get("field") 3050 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3051 3052 if query: 3053 in_sql = self.sql(query) 3054 elif unnest: 3055 in_sql = self.in_unnest_op(unnest) 3056 elif field: 3057 in_sql = self.sql(field) 3058 else: 3059 in_sql = f"({self.expressions(expression, flat=True)})" 3060 3061 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3062 3063 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3064 return f"(SELECT {self.sql(unnest)})" 3065 3066 def interval_sql(self, expression: exp.Interval) -> str: 3067 unit = self.sql(expression, "unit") 3068 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3069 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3070 unit = f" {unit}" if unit else "" 3071 3072 if self.SINGLE_STRING_INTERVAL: 3073 this = expression.this.name if expression.this else "" 3074 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3075 3076 this = self.sql(expression, "this") 3077 if this: 3078 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3079 this = f" {this}" if unwrapped else f" ({this})" 3080 3081 return f"INTERVAL{this}{unit}" 3082 3083 def return_sql(self, expression: exp.Return) -> str: 3084 return f"RETURN {self.sql(expression, 'this')}" 3085 3086 def reference_sql(self, expression: exp.Reference) -> str: 3087 this = self.sql(expression, "this") 3088 expressions = self.expressions(expression, flat=True) 3089 expressions = f"({expressions})" if expressions else "" 3090 options = self.expressions(expression, key="options", flat=True, sep=" ") 3091 options = f" {options}" if options else "" 3092 return f"REFERENCES {this}{expressions}{options}" 3093 3094 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3095 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3096 parent = expression.parent 3097 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3098 return self.func( 3099 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3100 ) 3101 3102 def paren_sql(self, expression: exp.Paren) -> str: 3103 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3104 return f"({sql}{self.seg(')', sep='')}" 3105 3106 def neg_sql(self, expression: exp.Neg) -> str: 3107 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3108 this_sql = self.sql(expression, "this") 3109 sep = " " if this_sql[0] == "-" else "" 3110 return f"-{sep}{this_sql}" 3111 3112 def not_sql(self, expression: exp.Not) -> str: 3113 return f"NOT {self.sql(expression, 'this')}" 3114 3115 def alias_sql(self, expression: exp.Alias) -> str: 3116 alias = self.sql(expression, "alias") 3117 alias = f" AS {alias}" if alias else "" 3118 return f"{self.sql(expression, 'this')}{alias}" 3119 3120 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3121 alias = expression.args["alias"] 3122 3123 parent = expression.parent 3124 pivot = parent and parent.parent 3125 3126 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3127 identifier_alias = isinstance(alias, exp.Identifier) 3128 literal_alias = isinstance(alias, exp.Literal) 3129 3130 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3131 alias.replace(exp.Literal.string(alias.output_name)) 3132 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3133 alias.replace(exp.to_identifier(alias.output_name)) 3134 3135 return self.alias_sql(expression) 3136 3137 def aliases_sql(self, expression: exp.Aliases) -> str: 3138 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3139 3140 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3141 this = self.sql(expression, "this") 3142 index = self.sql(expression, "expression") 3143 return f"{this} AT {index}" 3144 3145 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3146 this = self.sql(expression, "this") 3147 zone = self.sql(expression, "zone") 3148 return f"{this} AT TIME ZONE {zone}" 3149 3150 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3151 this = self.sql(expression, "this") 3152 zone = self.sql(expression, "zone") 3153 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3154 3155 def add_sql(self, expression: exp.Add) -> str: 3156 return self.binary(expression, "+") 3157 3158 def and_sql( 3159 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3160 ) -> str: 3161 return self.connector_sql(expression, "AND", stack) 3162 3163 def or_sql( 3164 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3165 ) -> str: 3166 return self.connector_sql(expression, "OR", stack) 3167 3168 def xor_sql( 3169 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3170 ) -> str: 3171 return self.connector_sql(expression, "XOR", stack) 3172 3173 def connector_sql( 3174 self, 3175 expression: exp.Connector, 3176 op: str, 3177 stack: t.Optional[t.List[str | exp.Expression]] = None, 3178 ) -> str: 3179 if stack is not None: 3180 if expression.expressions: 3181 stack.append(self.expressions(expression, sep=f" {op} ")) 3182 else: 3183 stack.append(expression.right) 3184 if expression.comments and self.comments: 3185 for comment in expression.comments: 3186 if comment: 3187 op += f" /*{self.pad_comment(comment)}*/" 3188 stack.extend((op, expression.left)) 3189 return op 3190 3191 stack = [expression] 3192 sqls: t.List[str] = [] 3193 ops = set() 3194 3195 while stack: 3196 node = stack.pop() 3197 if isinstance(node, exp.Connector): 3198 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3199 else: 3200 sql = self.sql(node) 3201 if sqls and sqls[-1] in ops: 3202 sqls[-1] += f" {sql}" 3203 else: 3204 sqls.append(sql) 3205 3206 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3207 return sep.join(sqls) 3208 3209 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3210 return self.binary(expression, "&") 3211 3212 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3213 return self.binary(expression, "<<") 3214 3215 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3216 return f"~{self.sql(expression, 'this')}" 3217 3218 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3219 return self.binary(expression, "|") 3220 3221 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3222 return self.binary(expression, ">>") 3223 3224 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3225 return self.binary(expression, "^") 3226 3227 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3228 format_sql = self.sql(expression, "format") 3229 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3230 to_sql = self.sql(expression, "to") 3231 to_sql = f" {to_sql}" if to_sql else "" 3232 action = self.sql(expression, "action") 3233 action = f" {action}" if action else "" 3234 default = self.sql(expression, "default") 3235 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3236 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3237 3238 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3239 zone = self.sql(expression, "this") 3240 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3241 3242 def collate_sql(self, expression: exp.Collate) -> str: 3243 if self.COLLATE_IS_FUNC: 3244 return self.function_fallback_sql(expression) 3245 return self.binary(expression, "COLLATE") 3246 3247 def command_sql(self, expression: exp.Command) -> str: 3248 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3249 3250 def comment_sql(self, expression: exp.Comment) -> str: 3251 this = self.sql(expression, "this") 3252 kind = expression.args["kind"] 3253 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3254 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3255 expression_sql = self.sql(expression, "expression") 3256 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3257 3258 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3259 this = self.sql(expression, "this") 3260 delete = " DELETE" if expression.args.get("delete") else "" 3261 recompress = self.sql(expression, "recompress") 3262 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3263 to_disk = self.sql(expression, "to_disk") 3264 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3265 to_volume = self.sql(expression, "to_volume") 3266 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3267 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3268 3269 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3270 where = self.sql(expression, "where") 3271 group = self.sql(expression, "group") 3272 aggregates = self.expressions(expression, key="aggregates") 3273 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3274 3275 if not (where or group or aggregates) and len(expression.expressions) == 1: 3276 return f"TTL {self.expressions(expression, flat=True)}" 3277 3278 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3279 3280 def transaction_sql(self, expression: exp.Transaction) -> str: 3281 return "BEGIN" 3282 3283 def commit_sql(self, expression: exp.Commit) -> str: 3284 chain = expression.args.get("chain") 3285 if chain is not None: 3286 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3287 3288 return f"COMMIT{chain or ''}" 3289 3290 def rollback_sql(self, expression: exp.Rollback) -> str: 3291 savepoint = expression.args.get("savepoint") 3292 savepoint = f" TO {savepoint}" if savepoint else "" 3293 return f"ROLLBACK{savepoint}" 3294 3295 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3296 this = self.sql(expression, "this") 3297 3298 dtype = self.sql(expression, "dtype") 3299 if dtype: 3300 collate = self.sql(expression, "collate") 3301 collate = f" COLLATE {collate}" if collate else "" 3302 using = self.sql(expression, "using") 3303 using = f" USING {using}" if using else "" 3304 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3305 3306 default = self.sql(expression, "default") 3307 if default: 3308 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3309 3310 comment = self.sql(expression, "comment") 3311 if comment: 3312 return f"ALTER COLUMN {this} COMMENT {comment}" 3313 3314 visible = expression.args.get("visible") 3315 if visible: 3316 return f"ALTER COLUMN {this} SET {visible}" 3317 3318 allow_null = expression.args.get("allow_null") 3319 drop = expression.args.get("drop") 3320 3321 if not drop and not allow_null: 3322 self.unsupported("Unsupported ALTER COLUMN syntax") 3323 3324 if allow_null is not None: 3325 keyword = "DROP" if drop else "SET" 3326 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3327 3328 return f"ALTER COLUMN {this} DROP DEFAULT" 3329 3330 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3331 this = self.sql(expression, "this") 3332 3333 visible = expression.args.get("visible") 3334 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3335 3336 return f"ALTER INDEX {this} {visible_sql}" 3337 3338 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3339 this = self.sql(expression, "this") 3340 if not isinstance(expression.this, exp.Var): 3341 this = f"KEY DISTKEY {this}" 3342 return f"ALTER DISTSTYLE {this}" 3343 3344 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3345 compound = " COMPOUND" if expression.args.get("compound") else "" 3346 this = self.sql(expression, "this") 3347 expressions = self.expressions(expression, flat=True) 3348 expressions = f"({expressions})" if expressions else "" 3349 return f"ALTER{compound} SORTKEY {this or expressions}" 3350 3351 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3352 if not self.RENAME_TABLE_WITH_DB: 3353 # Remove db from tables 3354 expression = expression.transform( 3355 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3356 ).assert_is(exp.AlterRename) 3357 this = self.sql(expression, "this") 3358 return f"RENAME TO {this}" 3359 3360 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3361 exists = " IF EXISTS" if expression.args.get("exists") else "" 3362 old_column = self.sql(expression, "this") 3363 new_column = self.sql(expression, "to") 3364 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3365 3366 def alterset_sql(self, expression: exp.AlterSet) -> str: 3367 exprs = self.expressions(expression, flat=True) 3368 return f"SET {exprs}" 3369 3370 def alter_sql(self, expression: exp.Alter) -> str: 3371 actions = expression.args["actions"] 3372 3373 if isinstance(actions[0], exp.ColumnDef): 3374 actions = self.add_column_sql(expression) 3375 elif isinstance(actions[0], exp.Schema): 3376 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3377 elif isinstance(actions[0], exp.Delete): 3378 actions = self.expressions(expression, key="actions", flat=True) 3379 elif isinstance(actions[0], exp.Query): 3380 actions = "AS " + self.expressions(expression, key="actions") 3381 else: 3382 actions = self.expressions(expression, key="actions", flat=True) 3383 3384 exists = " IF EXISTS" if expression.args.get("exists") else "" 3385 on_cluster = self.sql(expression, "cluster") 3386 on_cluster = f" {on_cluster}" if on_cluster else "" 3387 only = " ONLY" if expression.args.get("only") else "" 3388 options = self.expressions(expression, key="options") 3389 options = f", {options}" if options else "" 3390 kind = self.sql(expression, "kind") 3391 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3392 3393 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3394 3395 def add_column_sql(self, expression: exp.Alter) -> str: 3396 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3397 return self.expressions( 3398 expression, 3399 key="actions", 3400 prefix="ADD COLUMN ", 3401 skip_first=True, 3402 ) 3403 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3404 3405 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3406 expressions = self.expressions(expression) 3407 exists = " IF EXISTS " if expression.args.get("exists") else " " 3408 return f"DROP{exists}{expressions}" 3409 3410 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3411 return f"ADD {self.expressions(expression)}" 3412 3413 def distinct_sql(self, expression: exp.Distinct) -> str: 3414 this = self.expressions(expression, flat=True) 3415 3416 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3417 case = exp.case() 3418 for arg in expression.expressions: 3419 case = case.when(arg.is_(exp.null()), exp.null()) 3420 this = self.sql(case.else_(f"({this})")) 3421 3422 this = f" {this}" if this else "" 3423 3424 on = self.sql(expression, "on") 3425 on = f" ON {on}" if on else "" 3426 return f"DISTINCT{this}{on}" 3427 3428 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3429 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3430 3431 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3432 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3433 3434 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3435 this_sql = self.sql(expression, "this") 3436 expression_sql = self.sql(expression, "expression") 3437 kind = "MAX" if expression.args.get("max") else "MIN" 3438 return f"{this_sql} HAVING {kind} {expression_sql}" 3439 3440 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3441 return self.sql( 3442 exp.Cast( 3443 this=exp.Div(this=expression.this, expression=expression.expression), 3444 to=exp.DataType(this=exp.DataType.Type.INT), 3445 ) 3446 ) 3447 3448 def dpipe_sql(self, expression: exp.DPipe) -> str: 3449 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3450 return self.func( 3451 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3452 ) 3453 return self.binary(expression, "||") 3454 3455 def div_sql(self, expression: exp.Div) -> str: 3456 l, r = expression.left, expression.right 3457 3458 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3459 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3460 3461 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3462 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3463 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3464 3465 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3466 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3467 return self.sql( 3468 exp.cast( 3469 l / r, 3470 to=exp.DataType.Type.BIGINT, 3471 ) 3472 ) 3473 3474 return self.binary(expression, "/") 3475 3476 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3477 n = exp._wrap(expression.this, exp.Binary) 3478 d = exp._wrap(expression.expression, exp.Binary) 3479 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3480 3481 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3482 return self.binary(expression, "OVERLAPS") 3483 3484 def distance_sql(self, expression: exp.Distance) -> str: 3485 return self.binary(expression, "<->") 3486 3487 def dot_sql(self, expression: exp.Dot) -> str: 3488 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3489 3490 def eq_sql(self, expression: exp.EQ) -> str: 3491 return self.binary(expression, "=") 3492 3493 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3494 return self.binary(expression, ":=") 3495 3496 def escape_sql(self, expression: exp.Escape) -> str: 3497 return self.binary(expression, "ESCAPE") 3498 3499 def glob_sql(self, expression: exp.Glob) -> str: 3500 return self.binary(expression, "GLOB") 3501 3502 def gt_sql(self, expression: exp.GT) -> str: 3503 return self.binary(expression, ">") 3504 3505 def gte_sql(self, expression: exp.GTE) -> str: 3506 return self.binary(expression, ">=") 3507 3508 def ilike_sql(self, expression: exp.ILike) -> str: 3509 return self.binary(expression, "ILIKE") 3510 3511 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3512 return self.binary(expression, "ILIKE ANY") 3513 3514 def is_sql(self, expression: exp.Is) -> str: 3515 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3516 return self.sql( 3517 expression.this if expression.expression.this else exp.not_(expression.this) 3518 ) 3519 return self.binary(expression, "IS") 3520 3521 def like_sql(self, expression: exp.Like) -> str: 3522 return self.binary(expression, "LIKE") 3523 3524 def likeany_sql(self, expression: exp.LikeAny) -> str: 3525 return self.binary(expression, "LIKE ANY") 3526 3527 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3528 return self.binary(expression, "SIMILAR TO") 3529 3530 def lt_sql(self, expression: exp.LT) -> str: 3531 return self.binary(expression, "<") 3532 3533 def lte_sql(self, expression: exp.LTE) -> str: 3534 return self.binary(expression, "<=") 3535 3536 def mod_sql(self, expression: exp.Mod) -> str: 3537 return self.binary(expression, "%") 3538 3539 def mul_sql(self, expression: exp.Mul) -> str: 3540 return self.binary(expression, "*") 3541 3542 def neq_sql(self, expression: exp.NEQ) -> str: 3543 return self.binary(expression, "<>") 3544 3545 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3546 return self.binary(expression, "IS NOT DISTINCT FROM") 3547 3548 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3549 return self.binary(expression, "IS DISTINCT FROM") 3550 3551 def slice_sql(self, expression: exp.Slice) -> str: 3552 return self.binary(expression, ":") 3553 3554 def sub_sql(self, expression: exp.Sub) -> str: 3555 return self.binary(expression, "-") 3556 3557 def trycast_sql(self, expression: exp.TryCast) -> str: 3558 return self.cast_sql(expression, safe_prefix="TRY_") 3559 3560 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3561 return self.cast_sql(expression) 3562 3563 def try_sql(self, expression: exp.Try) -> str: 3564 if not self.TRY_SUPPORTED: 3565 self.unsupported("Unsupported TRY function") 3566 return self.sql(expression, "this") 3567 3568 return self.func("TRY", expression.this) 3569 3570 def log_sql(self, expression: exp.Log) -> str: 3571 this = expression.this 3572 expr = expression.expression 3573 3574 if self.dialect.LOG_BASE_FIRST is False: 3575 this, expr = expr, this 3576 elif self.dialect.LOG_BASE_FIRST is None and expr: 3577 if this.name in ("2", "10"): 3578 return self.func(f"LOG{this.name}", expr) 3579 3580 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3581 3582 return self.func("LOG", this, expr) 3583 3584 def use_sql(self, expression: exp.Use) -> str: 3585 kind = self.sql(expression, "kind") 3586 kind = f" {kind}" if kind else "" 3587 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3588 this = f" {this}" if this else "" 3589 return f"USE{kind}{this}" 3590 3591 def binary(self, expression: exp.Binary, op: str) -> str: 3592 sqls: t.List[str] = [] 3593 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3594 binary_type = type(expression) 3595 3596 while stack: 3597 node = stack.pop() 3598 3599 if type(node) is binary_type: 3600 op_func = node.args.get("operator") 3601 if op_func: 3602 op = f"OPERATOR({self.sql(op_func)})" 3603 3604 stack.append(node.right) 3605 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3606 stack.append(node.left) 3607 else: 3608 sqls.append(self.sql(node)) 3609 3610 return "".join(sqls) 3611 3612 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3613 to_clause = self.sql(expression, "to") 3614 if to_clause: 3615 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3616 3617 return self.function_fallback_sql(expression) 3618 3619 def function_fallback_sql(self, expression: exp.Func) -> str: 3620 args = [] 3621 3622 for key in expression.arg_types: 3623 arg_value = expression.args.get(key) 3624 3625 if isinstance(arg_value, list): 3626 for value in arg_value: 3627 args.append(value) 3628 elif arg_value is not None: 3629 args.append(arg_value) 3630 3631 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3632 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3633 else: 3634 name = expression.sql_name() 3635 3636 return self.func(name, *args) 3637 3638 def func( 3639 self, 3640 name: str, 3641 *args: t.Optional[exp.Expression | str], 3642 prefix: str = "(", 3643 suffix: str = ")", 3644 normalize: bool = True, 3645 ) -> str: 3646 name = self.normalize_func(name) if normalize else name 3647 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3648 3649 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3650 arg_sqls = tuple( 3651 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3652 ) 3653 if self.pretty and self.too_wide(arg_sqls): 3654 return self.indent( 3655 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3656 ) 3657 return sep.join(arg_sqls) 3658 3659 def too_wide(self, args: t.Iterable) -> bool: 3660 return sum(len(arg) for arg in args) > self.max_text_width 3661 3662 def format_time( 3663 self, 3664 expression: exp.Expression, 3665 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3666 inverse_time_trie: t.Optional[t.Dict] = None, 3667 ) -> t.Optional[str]: 3668 return format_time( 3669 self.sql(expression, "format"), 3670 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3671 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3672 ) 3673 3674 def expressions( 3675 self, 3676 expression: t.Optional[exp.Expression] = None, 3677 key: t.Optional[str] = None, 3678 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3679 flat: bool = False, 3680 indent: bool = True, 3681 skip_first: bool = False, 3682 skip_last: bool = False, 3683 sep: str = ", ", 3684 prefix: str = "", 3685 dynamic: bool = False, 3686 new_line: bool = False, 3687 ) -> str: 3688 expressions = expression.args.get(key or "expressions") if expression else sqls 3689 3690 if not expressions: 3691 return "" 3692 3693 if flat: 3694 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3695 3696 num_sqls = len(expressions) 3697 result_sqls = [] 3698 3699 for i, e in enumerate(expressions): 3700 sql = self.sql(e, comment=False) 3701 if not sql: 3702 continue 3703 3704 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3705 3706 if self.pretty: 3707 if self.leading_comma: 3708 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3709 else: 3710 result_sqls.append( 3711 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3712 ) 3713 else: 3714 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3715 3716 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3717 if new_line: 3718 result_sqls.insert(0, "") 3719 result_sqls.append("") 3720 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3721 else: 3722 result_sql = "".join(result_sqls) 3723 3724 return ( 3725 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3726 if indent 3727 else result_sql 3728 ) 3729 3730 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3731 flat = flat or isinstance(expression.parent, exp.Properties) 3732 expressions_sql = self.expressions(expression, flat=flat) 3733 if flat: 3734 return f"{op} {expressions_sql}" 3735 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3736 3737 def naked_property(self, expression: exp.Property) -> str: 3738 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3739 if not property_name: 3740 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3741 return f"{property_name} {self.sql(expression, 'this')}" 3742 3743 def tag_sql(self, expression: exp.Tag) -> str: 3744 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3745 3746 def token_sql(self, token_type: TokenType) -> str: 3747 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3748 3749 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3750 this = self.sql(expression, "this") 3751 expressions = self.no_identify(self.expressions, expression) 3752 expressions = ( 3753 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3754 ) 3755 return f"{this}{expressions}" if expressions.strip() != "" else this 3756 3757 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3758 this = self.sql(expression, "this") 3759 expressions = self.expressions(expression, flat=True) 3760 return f"{this}({expressions})" 3761 3762 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3763 return self.binary(expression, "=>") 3764 3765 def when_sql(self, expression: exp.When) -> str: 3766 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3767 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3768 condition = self.sql(expression, "condition") 3769 condition = f" AND {condition}" if condition else "" 3770 3771 then_expression = expression.args.get("then") 3772 if isinstance(then_expression, exp.Insert): 3773 this = self.sql(then_expression, "this") 3774 this = f"INSERT {this}" if this else "INSERT" 3775 then = self.sql(then_expression, "expression") 3776 then = f"{this} VALUES {then}" if then else this 3777 elif isinstance(then_expression, exp.Update): 3778 if isinstance(then_expression.args.get("expressions"), exp.Star): 3779 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3780 else: 3781 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3782 else: 3783 then = self.sql(then_expression) 3784 return f"WHEN {matched}{source}{condition} THEN {then}" 3785 3786 def whens_sql(self, expression: exp.Whens) -> str: 3787 return self.expressions(expression, sep=" ", indent=False) 3788 3789 def merge_sql(self, expression: exp.Merge) -> str: 3790 table = expression.this 3791 table_alias = "" 3792 3793 hints = table.args.get("hints") 3794 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3795 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3796 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3797 3798 this = self.sql(table) 3799 using = f"USING {self.sql(expression, 'using')}" 3800 on = f"ON {self.sql(expression, 'on')}" 3801 whens = self.sql(expression, "whens") 3802 3803 returning = self.sql(expression, "returning") 3804 if returning: 3805 whens = f"{whens}{returning}" 3806 3807 sep = self.sep() 3808 3809 return self.prepend_ctes( 3810 expression, 3811 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3812 ) 3813 3814 @unsupported_args("format") 3815 def tochar_sql(self, expression: exp.ToChar) -> str: 3816 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3817 3818 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3819 if not self.SUPPORTS_TO_NUMBER: 3820 self.unsupported("Unsupported TO_NUMBER function") 3821 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3822 3823 fmt = expression.args.get("format") 3824 if not fmt: 3825 self.unsupported("Conversion format is required for TO_NUMBER") 3826 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3827 3828 return self.func("TO_NUMBER", expression.this, fmt) 3829 3830 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3831 this = self.sql(expression, "this") 3832 kind = self.sql(expression, "kind") 3833 settings_sql = self.expressions(expression, key="settings", sep=" ") 3834 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3835 return f"{this}({kind}{args})" 3836 3837 def dictrange_sql(self, expression: exp.DictRange) -> str: 3838 this = self.sql(expression, "this") 3839 max = self.sql(expression, "max") 3840 min = self.sql(expression, "min") 3841 return f"{this}(MIN {min} MAX {max})" 3842 3843 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3844 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3845 3846 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3847 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3848 3849 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3850 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3851 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3852 3853 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3854 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3855 expressions = self.expressions(expression, flat=True) 3856 expressions = f" {self.wrap(expressions)}" if expressions else "" 3857 buckets = self.sql(expression, "buckets") 3858 kind = self.sql(expression, "kind") 3859 buckets = f" BUCKETS {buckets}" if buckets else "" 3860 order = self.sql(expression, "order") 3861 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3862 3863 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3864 return "" 3865 3866 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3867 expressions = self.expressions(expression, key="expressions", flat=True) 3868 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3869 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3870 buckets = self.sql(expression, "buckets") 3871 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3872 3873 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3874 this = self.sql(expression, "this") 3875 having = self.sql(expression, "having") 3876 3877 if having: 3878 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3879 3880 return self.func("ANY_VALUE", this) 3881 3882 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3883 transform = self.func("TRANSFORM", *expression.expressions) 3884 row_format_before = self.sql(expression, "row_format_before") 3885 row_format_before = f" {row_format_before}" if row_format_before else "" 3886 record_writer = self.sql(expression, "record_writer") 3887 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3888 using = f" USING {self.sql(expression, 'command_script')}" 3889 schema = self.sql(expression, "schema") 3890 schema = f" AS {schema}" if schema else "" 3891 row_format_after = self.sql(expression, "row_format_after") 3892 row_format_after = f" {row_format_after}" if row_format_after else "" 3893 record_reader = self.sql(expression, "record_reader") 3894 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3895 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3896 3897 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3898 key_block_size = self.sql(expression, "key_block_size") 3899 if key_block_size: 3900 return f"KEY_BLOCK_SIZE = {key_block_size}" 3901 3902 using = self.sql(expression, "using") 3903 if using: 3904 return f"USING {using}" 3905 3906 parser = self.sql(expression, "parser") 3907 if parser: 3908 return f"WITH PARSER {parser}" 3909 3910 comment = self.sql(expression, "comment") 3911 if comment: 3912 return f"COMMENT {comment}" 3913 3914 visible = expression.args.get("visible") 3915 if visible is not None: 3916 return "VISIBLE" if visible else "INVISIBLE" 3917 3918 engine_attr = self.sql(expression, "engine_attr") 3919 if engine_attr: 3920 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3921 3922 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3923 if secondary_engine_attr: 3924 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3925 3926 self.unsupported("Unsupported index constraint option.") 3927 return "" 3928 3929 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3930 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3931 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3932 3933 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3934 kind = self.sql(expression, "kind") 3935 kind = f"{kind} INDEX" if kind else "INDEX" 3936 this = self.sql(expression, "this") 3937 this = f" {this}" if this else "" 3938 index_type = self.sql(expression, "index_type") 3939 index_type = f" USING {index_type}" if index_type else "" 3940 expressions = self.expressions(expression, flat=True) 3941 expressions = f" ({expressions})" if expressions else "" 3942 options = self.expressions(expression, key="options", sep=" ") 3943 options = f" {options}" if options else "" 3944 return f"{kind}{this}{index_type}{expressions}{options}" 3945 3946 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3947 if self.NVL2_SUPPORTED: 3948 return self.function_fallback_sql(expression) 3949 3950 case = exp.Case().when( 3951 expression.this.is_(exp.null()).not_(copy=False), 3952 expression.args["true"], 3953 copy=False, 3954 ) 3955 else_cond = expression.args.get("false") 3956 if else_cond: 3957 case.else_(else_cond, copy=False) 3958 3959 return self.sql(case) 3960 3961 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3962 this = self.sql(expression, "this") 3963 expr = self.sql(expression, "expression") 3964 iterator = self.sql(expression, "iterator") 3965 condition = self.sql(expression, "condition") 3966 condition = f" IF {condition}" if condition else "" 3967 return f"{this} FOR {expr} IN {iterator}{condition}" 3968 3969 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3970 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3971 3972 def opclass_sql(self, expression: exp.Opclass) -> str: 3973 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3974 3975 def predict_sql(self, expression: exp.Predict) -> str: 3976 model = self.sql(expression, "this") 3977 model = f"MODEL {model}" 3978 table = self.sql(expression, "expression") 3979 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3980 parameters = self.sql(expression, "params_struct") 3981 return self.func("PREDICT", model, table, parameters or None) 3982 3983 def forin_sql(self, expression: exp.ForIn) -> str: 3984 this = self.sql(expression, "this") 3985 expression_sql = self.sql(expression, "expression") 3986 return f"FOR {this} DO {expression_sql}" 3987 3988 def refresh_sql(self, expression: exp.Refresh) -> str: 3989 this = self.sql(expression, "this") 3990 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3991 return f"REFRESH {table}{this}" 3992 3993 def toarray_sql(self, expression: exp.ToArray) -> str: 3994 arg = expression.this 3995 if not arg.type: 3996 from sqlglot.optimizer.annotate_types import annotate_types 3997 3998 arg = annotate_types(arg) 3999 4000 if arg.is_type(exp.DataType.Type.ARRAY): 4001 return self.sql(arg) 4002 4003 cond_for_null = arg.is_(exp.null()) 4004 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4005 4006 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4007 this = expression.this 4008 time_format = self.format_time(expression) 4009 4010 if time_format: 4011 return self.sql( 4012 exp.cast( 4013 exp.StrToTime(this=this, format=expression.args["format"]), 4014 exp.DataType.Type.TIME, 4015 ) 4016 ) 4017 4018 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4019 return self.sql(this) 4020 4021 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4022 4023 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4024 this = expression.this 4025 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4026 return self.sql(this) 4027 4028 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4029 4030 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4031 this = expression.this 4032 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4033 return self.sql(this) 4034 4035 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4036 4037 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4038 this = expression.this 4039 time_format = self.format_time(expression) 4040 4041 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4042 return self.sql( 4043 exp.cast( 4044 exp.StrToTime(this=this, format=expression.args["format"]), 4045 exp.DataType.Type.DATE, 4046 ) 4047 ) 4048 4049 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4050 return self.sql(this) 4051 4052 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4053 4054 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4055 return self.sql( 4056 exp.func( 4057 "DATEDIFF", 4058 expression.this, 4059 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4060 "day", 4061 ) 4062 ) 4063 4064 def lastday_sql(self, expression: exp.LastDay) -> str: 4065 if self.LAST_DAY_SUPPORTS_DATE_PART: 4066 return self.function_fallback_sql(expression) 4067 4068 unit = expression.text("unit") 4069 if unit and unit != "MONTH": 4070 self.unsupported("Date parts are not supported in LAST_DAY.") 4071 4072 return self.func("LAST_DAY", expression.this) 4073 4074 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4075 from sqlglot.dialects.dialect import unit_to_str 4076 4077 return self.func( 4078 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4079 ) 4080 4081 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4082 if self.CAN_IMPLEMENT_ARRAY_ANY: 4083 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4084 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4085 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4086 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4087 4088 from sqlglot.dialects import Dialect 4089 4090 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4091 if self.dialect.__class__ != Dialect: 4092 self.unsupported("ARRAY_ANY is unsupported") 4093 4094 return self.function_fallback_sql(expression) 4095 4096 def struct_sql(self, expression: exp.Struct) -> str: 4097 expression.set( 4098 "expressions", 4099 [ 4100 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4101 if isinstance(e, exp.PropertyEQ) 4102 else e 4103 for e in expression.expressions 4104 ], 4105 ) 4106 4107 return self.function_fallback_sql(expression) 4108 4109 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4110 low = self.sql(expression, "this") 4111 high = self.sql(expression, "expression") 4112 4113 return f"{low} TO {high}" 4114 4115 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4116 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4117 tables = f" {self.expressions(expression)}" 4118 4119 exists = " IF EXISTS" if expression.args.get("exists") else "" 4120 4121 on_cluster = self.sql(expression, "cluster") 4122 on_cluster = f" {on_cluster}" if on_cluster else "" 4123 4124 identity = self.sql(expression, "identity") 4125 identity = f" {identity} IDENTITY" if identity else "" 4126 4127 option = self.sql(expression, "option") 4128 option = f" {option}" if option else "" 4129 4130 partition = self.sql(expression, "partition") 4131 partition = f" {partition}" if partition else "" 4132 4133 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4134 4135 # This transpiles T-SQL's CONVERT function 4136 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4137 def convert_sql(self, expression: exp.Convert) -> str: 4138 to = expression.this 4139 value = expression.expression 4140 style = expression.args.get("style") 4141 safe = expression.args.get("safe") 4142 strict = expression.args.get("strict") 4143 4144 if not to or not value: 4145 return "" 4146 4147 # Retrieve length of datatype and override to default if not specified 4148 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4149 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4150 4151 transformed: t.Optional[exp.Expression] = None 4152 cast = exp.Cast if strict else exp.TryCast 4153 4154 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4155 if isinstance(style, exp.Literal) and style.is_int: 4156 from sqlglot.dialects.tsql import TSQL 4157 4158 style_value = style.name 4159 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4160 if not converted_style: 4161 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4162 4163 fmt = exp.Literal.string(converted_style) 4164 4165 if to.this == exp.DataType.Type.DATE: 4166 transformed = exp.StrToDate(this=value, format=fmt) 4167 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4168 transformed = exp.StrToTime(this=value, format=fmt) 4169 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4170 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4171 elif to.this == exp.DataType.Type.TEXT: 4172 transformed = exp.TimeToStr(this=value, format=fmt) 4173 4174 if not transformed: 4175 transformed = cast(this=value, to=to, safe=safe) 4176 4177 return self.sql(transformed) 4178 4179 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4180 this = expression.this 4181 if isinstance(this, exp.JSONPathWildcard): 4182 this = self.json_path_part(this) 4183 return f".{this}" if this else "" 4184 4185 if exp.SAFE_IDENTIFIER_RE.match(this): 4186 return f".{this}" 4187 4188 this = self.json_path_part(this) 4189 return ( 4190 f"[{this}]" 4191 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4192 else f".{this}" 4193 ) 4194 4195 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4196 this = self.json_path_part(expression.this) 4197 return f"[{this}]" if this else "" 4198 4199 def _simplify_unless_literal(self, expression: E) -> E: 4200 if not isinstance(expression, exp.Literal): 4201 from sqlglot.optimizer.simplify import simplify 4202 4203 expression = simplify(expression, dialect=self.dialect) 4204 4205 return expression 4206 4207 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4208 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4209 # The first modifier here will be the one closest to the AggFunc's arg 4210 mods = sorted( 4211 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4212 key=lambda x: 0 4213 if isinstance(x, exp.HavingMax) 4214 else (1 if isinstance(x, exp.Order) else 2), 4215 ) 4216 4217 if mods: 4218 mod = mods[0] 4219 this = expression.__class__(this=mod.this.copy()) 4220 this.meta["inline"] = True 4221 mod.this.replace(this) 4222 return self.sql(expression.this) 4223 4224 agg_func = expression.find(exp.AggFunc) 4225 4226 if agg_func: 4227 return self.sql(agg_func)[:-1] + f" {text})" 4228 4229 return f"{self.sql(expression, 'this')} {text}" 4230 4231 def _replace_line_breaks(self, string: str) -> str: 4232 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4233 if self.pretty: 4234 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4235 return string 4236 4237 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4238 option = self.sql(expression, "this") 4239 4240 if expression.expressions: 4241 upper = option.upper() 4242 4243 # Snowflake FILE_FORMAT options are separated by whitespace 4244 sep = " " if upper == "FILE_FORMAT" else ", " 4245 4246 # Databricks copy/format options do not set their list of values with EQ 4247 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4248 values = self.expressions(expression, flat=True, sep=sep) 4249 return f"{option}{op}({values})" 4250 4251 value = self.sql(expression, "expression") 4252 4253 if not value: 4254 return option 4255 4256 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4257 4258 return f"{option}{op}{value}" 4259 4260 def credentials_sql(self, expression: exp.Credentials) -> str: 4261 cred_expr = expression.args.get("credentials") 4262 if isinstance(cred_expr, exp.Literal): 4263 # Redshift case: CREDENTIALS <string> 4264 credentials = self.sql(expression, "credentials") 4265 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4266 else: 4267 # Snowflake case: CREDENTIALS = (...) 4268 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4269 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4270 4271 storage = self.sql(expression, "storage") 4272 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4273 4274 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4275 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4276 4277 iam_role = self.sql(expression, "iam_role") 4278 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4279 4280 region = self.sql(expression, "region") 4281 region = f" REGION {region}" if region else "" 4282 4283 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4284 4285 def copy_sql(self, expression: exp.Copy) -> str: 4286 this = self.sql(expression, "this") 4287 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4288 4289 credentials = self.sql(expression, "credentials") 4290 credentials = self.seg(credentials) if credentials else "" 4291 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4292 files = self.expressions(expression, key="files", flat=True) 4293 4294 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4295 params = self.expressions( 4296 expression, 4297 key="params", 4298 sep=sep, 4299 new_line=True, 4300 skip_last=True, 4301 skip_first=True, 4302 indent=self.COPY_PARAMS_ARE_WRAPPED, 4303 ) 4304 4305 if params: 4306 if self.COPY_PARAMS_ARE_WRAPPED: 4307 params = f" WITH ({params})" 4308 elif not self.pretty: 4309 params = f" {params}" 4310 4311 return f"COPY{this}{kind} {files}{credentials}{params}" 4312 4313 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4314 return "" 4315 4316 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4317 on_sql = "ON" if expression.args.get("on") else "OFF" 4318 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4319 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4320 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4321 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4322 4323 if filter_col or retention_period: 4324 on_sql = self.func("ON", filter_col, retention_period) 4325 4326 return f"DATA_DELETION={on_sql}" 4327 4328 def maskingpolicycolumnconstraint_sql( 4329 self, expression: exp.MaskingPolicyColumnConstraint 4330 ) -> str: 4331 this = self.sql(expression, "this") 4332 expressions = self.expressions(expression, flat=True) 4333 expressions = f" USING ({expressions})" if expressions else "" 4334 return f"MASKING POLICY {this}{expressions}" 4335 4336 def gapfill_sql(self, expression: exp.GapFill) -> str: 4337 this = self.sql(expression, "this") 4338 this = f"TABLE {this}" 4339 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4340 4341 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4342 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4343 4344 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4345 this = self.sql(expression, "this") 4346 expr = expression.expression 4347 4348 if isinstance(expr, exp.Func): 4349 # T-SQL's CLR functions are case sensitive 4350 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4351 else: 4352 expr = self.sql(expression, "expression") 4353 4354 return self.scope_resolution(expr, this) 4355 4356 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4357 if self.PARSE_JSON_NAME is None: 4358 return self.sql(expression.this) 4359 4360 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4361 4362 def rand_sql(self, expression: exp.Rand) -> str: 4363 lower = self.sql(expression, "lower") 4364 upper = self.sql(expression, "upper") 4365 4366 if lower and upper: 4367 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4368 return self.func("RAND", expression.this) 4369 4370 def changes_sql(self, expression: exp.Changes) -> str: 4371 information = self.sql(expression, "information") 4372 information = f"INFORMATION => {information}" 4373 at_before = self.sql(expression, "at_before") 4374 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4375 end = self.sql(expression, "end") 4376 end = f"{self.seg('')}{end}" if end else "" 4377 4378 return f"CHANGES ({information}){at_before}{end}" 4379 4380 def pad_sql(self, expression: exp.Pad) -> str: 4381 prefix = "L" if expression.args.get("is_left") else "R" 4382 4383 fill_pattern = self.sql(expression, "fill_pattern") or None 4384 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4385 fill_pattern = "' '" 4386 4387 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4388 4389 def summarize_sql(self, expression: exp.Summarize) -> str: 4390 table = " TABLE" if expression.args.get("table") else "" 4391 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4392 4393 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4394 generate_series = exp.GenerateSeries(**expression.args) 4395 4396 parent = expression.parent 4397 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4398 parent = parent.parent 4399 4400 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4401 return self.sql(exp.Unnest(expressions=[generate_series])) 4402 4403 if isinstance(parent, exp.Select): 4404 self.unsupported("GenerateSeries projection unnesting is not supported.") 4405 4406 return self.sql(generate_series) 4407 4408 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4409 exprs = expression.expressions 4410 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4411 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4412 else: 4413 rhs = self.expressions(expression) 4414 4415 return self.func(name, expression.this, rhs or None) 4416 4417 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4418 if self.SUPPORTS_CONVERT_TIMEZONE: 4419 return self.function_fallback_sql(expression) 4420 4421 source_tz = expression.args.get("source_tz") 4422 target_tz = expression.args.get("target_tz") 4423 timestamp = expression.args.get("timestamp") 4424 4425 if source_tz and timestamp: 4426 timestamp = exp.AtTimeZone( 4427 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4428 ) 4429 4430 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4431 4432 return self.sql(expr) 4433 4434 def json_sql(self, expression: exp.JSON) -> str: 4435 this = self.sql(expression, "this") 4436 this = f" {this}" if this else "" 4437 4438 _with = expression.args.get("with") 4439 4440 if _with is None: 4441 with_sql = "" 4442 elif not _with: 4443 with_sql = " WITHOUT" 4444 else: 4445 with_sql = " WITH" 4446 4447 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4448 4449 return f"JSON{this}{with_sql}{unique_sql}" 4450 4451 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4452 def _generate_on_options(arg: t.Any) -> str: 4453 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4454 4455 path = self.sql(expression, "path") 4456 returning = self.sql(expression, "returning") 4457 returning = f" RETURNING {returning}" if returning else "" 4458 4459 on_condition = self.sql(expression, "on_condition") 4460 on_condition = f" {on_condition}" if on_condition else "" 4461 4462 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4463 4464 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4465 else_ = "ELSE " if expression.args.get("else_") else "" 4466 condition = self.sql(expression, "expression") 4467 condition = f"WHEN {condition} THEN " if condition else else_ 4468 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4469 return f"{condition}{insert}" 4470 4471 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4472 kind = self.sql(expression, "kind") 4473 expressions = self.seg(self.expressions(expression, sep=" ")) 4474 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4475 return res 4476 4477 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4478 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4479 empty = expression.args.get("empty") 4480 empty = ( 4481 f"DEFAULT {empty} ON EMPTY" 4482 if isinstance(empty, exp.Expression) 4483 else self.sql(expression, "empty") 4484 ) 4485 4486 error = expression.args.get("error") 4487 error = ( 4488 f"DEFAULT {error} ON ERROR" 4489 if isinstance(error, exp.Expression) 4490 else self.sql(expression, "error") 4491 ) 4492 4493 if error and empty: 4494 error = ( 4495 f"{empty} {error}" 4496 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4497 else f"{error} {empty}" 4498 ) 4499 empty = "" 4500 4501 null = self.sql(expression, "null") 4502 4503 return f"{empty}{error}{null}" 4504 4505 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4506 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4507 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4508 4509 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4510 this = self.sql(expression, "this") 4511 path = self.sql(expression, "path") 4512 4513 passing = self.expressions(expression, "passing") 4514 passing = f" PASSING {passing}" if passing else "" 4515 4516 on_condition = self.sql(expression, "on_condition") 4517 on_condition = f" {on_condition}" if on_condition else "" 4518 4519 path = f"{path}{passing}{on_condition}" 4520 4521 return self.func("JSON_EXISTS", this, path) 4522 4523 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4524 array_agg = self.function_fallback_sql(expression) 4525 4526 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4527 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4528 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4529 parent = expression.parent 4530 if isinstance(parent, exp.Filter): 4531 parent_cond = parent.expression.this 4532 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4533 else: 4534 this = expression.this 4535 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4536 if this.find(exp.Column): 4537 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4538 this_sql = ( 4539 self.expressions(this) 4540 if isinstance(this, exp.Distinct) 4541 else self.sql(expression, "this") 4542 ) 4543 4544 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4545 4546 return array_agg 4547 4548 def apply_sql(self, expression: exp.Apply) -> str: 4549 this = self.sql(expression, "this") 4550 expr = self.sql(expression, "expression") 4551 4552 return f"{this} APPLY({expr})" 4553 4554 def grant_sql(self, expression: exp.Grant) -> str: 4555 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4556 4557 kind = self.sql(expression, "kind") 4558 kind = f" {kind}" if kind else "" 4559 4560 securable = self.sql(expression, "securable") 4561 securable = f" {securable}" if securable else "" 4562 4563 principals = self.expressions(expression, key="principals", flat=True) 4564 4565 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4566 4567 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4568 4569 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4570 this = self.sql(expression, "this") 4571 columns = self.expressions(expression, flat=True) 4572 columns = f"({columns})" if columns else "" 4573 4574 return f"{this}{columns}" 4575 4576 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4577 this = self.sql(expression, "this") 4578 4579 kind = self.sql(expression, "kind") 4580 kind = f"{kind} " if kind else "" 4581 4582 return f"{kind}{this}" 4583 4584 def columns_sql(self, expression: exp.Columns): 4585 func = self.function_fallback_sql(expression) 4586 if expression.args.get("unpack"): 4587 func = f"*{func}" 4588 4589 return func 4590 4591 def overlay_sql(self, expression: exp.Overlay): 4592 this = self.sql(expression, "this") 4593 expr = self.sql(expression, "expression") 4594 from_sql = self.sql(expression, "from") 4595 for_sql = self.sql(expression, "for") 4596 for_sql = f" FOR {for_sql}" if for_sql else "" 4597 4598 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4599 4600 @unsupported_args("format") 4601 def todouble_sql(self, expression: exp.ToDouble) -> str: 4602 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4603 4604 def string_sql(self, expression: exp.String) -> str: 4605 this = expression.this 4606 zone = expression.args.get("zone") 4607 4608 if zone: 4609 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4610 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4611 # set for source_tz to transpile the time conversion before the STRING cast 4612 this = exp.ConvertTimezone( 4613 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4614 ) 4615 4616 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4617 4618 def median_sql(self, expression: exp.Median): 4619 if not self.SUPPORTS_MEDIAN: 4620 return self.sql( 4621 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4622 ) 4623 4624 return self.function_fallback_sql(expression) 4625 4626 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4627 filler = self.sql(expression, "this") 4628 filler = f" {filler}" if filler else "" 4629 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4630 return f"TRUNCATE{filler} {with_count}" 4631 4632 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4633 if self.SUPPORTS_UNIX_SECONDS: 4634 return self.function_fallback_sql(expression) 4635 4636 start_ts = exp.cast( 4637 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4638 ) 4639 4640 return self.sql( 4641 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4642 ) 4643 4644 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4645 dim = expression.expression 4646 4647 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4648 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4649 if not (dim.is_int and dim.name == "1"): 4650 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4651 dim = None 4652 4653 # If dimension is required but not specified, default initialize it 4654 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4655 dim = exp.Literal.number(1) 4656 4657 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4658 4659 def attach_sql(self, expression: exp.Attach) -> str: 4660 this = self.sql(expression, "this") 4661 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4662 expressions = self.expressions(expression) 4663 expressions = f" ({expressions})" if expressions else "" 4664 4665 return f"ATTACH{exists_sql} {this}{expressions}" 4666 4667 def detach_sql(self, expression: exp.Detach) -> str: 4668 this = self.sql(expression, "this") 4669 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4670 4671 return f"DETACH{exists_sql} {this}" 4672 4673 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4674 this = self.sql(expression, "this") 4675 value = self.sql(expression, "expression") 4676 value = f" {value}" if value else "" 4677 return f"{this}{value}" 4678 4679 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4680 this_sql = self.sql(expression, "this") 4681 if isinstance(expression.this, exp.Table): 4682 this_sql = f"TABLE {this_sql}" 4683 4684 return self.func( 4685 "FEATURES_AT_TIME", 4686 this_sql, 4687 expression.args.get("time"), 4688 expression.args.get("num_rows"), 4689 expression.args.get("ignore_feature_nulls"), 4690 ) 4691 4692 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4693 return ( 4694 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4695 ) 4696 4697 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4698 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4699 encode = f"{encode} {self.sql(expression, 'this')}" 4700 4701 properties = expression.args.get("properties") 4702 if properties: 4703 encode = f"{encode} {self.properties(properties)}" 4704 4705 return encode 4706 4707 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4708 this = self.sql(expression, "this") 4709 include = f"INCLUDE {this}" 4710 4711 column_def = self.sql(expression, "column_def") 4712 if column_def: 4713 include = f"{include} {column_def}" 4714 4715 alias = self.sql(expression, "alias") 4716 if alias: 4717 include = f"{include} AS {alias}" 4718 4719 return include 4720 4721 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4722 name = f"NAME {self.sql(expression, 'this')}" 4723 return self.func("XMLELEMENT", name, *expression.expressions) 4724 4725 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4726 partitions = self.expressions(expression, "partition_expressions") 4727 create = self.expressions(expression, "create_expressions") 4728 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4729 4730 def partitionbyrangepropertydynamic_sql( 4731 self, expression: exp.PartitionByRangePropertyDynamic 4732 ) -> str: 4733 start = self.sql(expression, "start") 4734 end = self.sql(expression, "end") 4735 4736 every = expression.args["every"] 4737 if isinstance(every, exp.Interval) and every.this.is_string: 4738 every.this.replace(exp.Literal.number(every.name)) 4739 4740 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4741 4742 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4743 name = self.sql(expression, "this") 4744 values = self.expressions(expression, flat=True) 4745 4746 return f"NAME {name} VALUE {values}" 4747 4748 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4749 kind = self.sql(expression, "kind") 4750 sample = self.sql(expression, "sample") 4751 return f"SAMPLE {sample} {kind}" 4752 4753 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4754 kind = self.sql(expression, "kind") 4755 option = self.sql(expression, "option") 4756 option = f" {option}" if option else "" 4757 this = self.sql(expression, "this") 4758 this = f" {this}" if this else "" 4759 columns = self.expressions(expression) 4760 columns = f" {columns}" if columns else "" 4761 return f"{kind}{option} STATISTICS{this}{columns}" 4762 4763 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4764 this = self.sql(expression, "this") 4765 columns = self.expressions(expression) 4766 inner_expression = self.sql(expression, "expression") 4767 inner_expression = f" {inner_expression}" if inner_expression else "" 4768 update_options = self.sql(expression, "update_options") 4769 update_options = f" {update_options} UPDATE" if update_options else "" 4770 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4771 4772 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4773 kind = self.sql(expression, "kind") 4774 kind = f" {kind}" if kind else "" 4775 return f"DELETE{kind} STATISTICS" 4776 4777 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4778 inner_expression = self.sql(expression, "expression") 4779 return f"LIST CHAINED ROWS{inner_expression}" 4780 4781 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4782 kind = self.sql(expression, "kind") 4783 this = self.sql(expression, "this") 4784 this = f" {this}" if this else "" 4785 inner_expression = self.sql(expression, "expression") 4786 return f"VALIDATE {kind}{this}{inner_expression}" 4787 4788 def analyze_sql(self, expression: exp.Analyze) -> str: 4789 options = self.expressions(expression, key="options", sep=" ") 4790 options = f" {options}" if options else "" 4791 kind = self.sql(expression, "kind") 4792 kind = f" {kind}" if kind else "" 4793 this = self.sql(expression, "this") 4794 this = f" {this}" if this else "" 4795 mode = self.sql(expression, "mode") 4796 mode = f" {mode}" if mode else "" 4797 properties = self.sql(expression, "properties") 4798 properties = f" {properties}" if properties else "" 4799 partition = self.sql(expression, "partition") 4800 partition = f" {partition}" if partition else "" 4801 inner_expression = self.sql(expression, "expression") 4802 inner_expression = f" {inner_expression}" if inner_expression else "" 4803 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4804 4805 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4806 this = self.sql(expression, "this") 4807 namespaces = self.expressions(expression, key="namespaces") 4808 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4809 passing = self.expressions(expression, key="passing") 4810 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4811 columns = self.expressions(expression, key="columns") 4812 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4813 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4814 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4815 4816 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4817 this = self.sql(expression, "this") 4818 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4819 4820 def export_sql(self, expression: exp.Export) -> str: 4821 this = self.sql(expression, "this") 4822 connection = self.sql(expression, "connection") 4823 connection = f"WITH CONNECTION {connection} " if connection else "" 4824 options = self.sql(expression, "options") 4825 return f"EXPORT DATA {connection}{options} AS {this}" 4826 4827 def declare_sql(self, expression: exp.Declare) -> str: 4828 return f"DECLARE {self.expressions(expression, flat=True)}" 4829 4830 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4831 variable = self.sql(expression, "this") 4832 default = self.sql(expression, "default") 4833 default = f" = {default}" if default else "" 4834 4835 kind = self.sql(expression, "kind") 4836 if isinstance(expression.args.get("kind"), exp.Schema): 4837 kind = f"TABLE {kind}" 4838 4839 return f"{variable} AS {kind}{default}" 4840 4841 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4842 kind = self.sql(expression, "kind") 4843 this = self.sql(expression, "this") 4844 set = self.sql(expression, "expression") 4845 using = self.sql(expression, "using") 4846 using = f" USING {using}" if using else "" 4847 4848 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4849 4850 return f"{kind_sql} {this} SET {set}{using}" 4851 4852 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4853 params = self.expressions(expression, key="params", flat=True) 4854 return self.func(expression.name, *expression.expressions) + f"({params})" 4855 4856 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4857 return self.func(expression.name, *expression.expressions) 4858 4859 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4860 return self.anonymousaggfunc_sql(expression) 4861 4862 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4863 return self.parameterizedagg_sql(expression) 4864 4865 def show_sql(self, expression: exp.Show) -> str: 4866 self.unsupported("Unsupported SHOW statement") 4867 return "" 4868 4869 def put_sql(self, expression: exp.Put) -> str: 4870 props = expression.args.get("properties") 4871 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4872 this = self.sql(expression, "this") 4873 target = self.sql(expression, "target") 4874 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.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.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 601 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 602 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 603 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 604 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 605 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 606 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 607 exp.ForceProperty: exp.Properties.Location.POST_CREATE, 608 } 609 610 # Keywords that can't be used as unquoted identifier names 611 RESERVED_KEYWORDS: t.Set[str] = set() 612 613 # Expressions whose comments are separated from them for better formatting 614 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 615 exp.Command, 616 exp.Create, 617 exp.Describe, 618 exp.Delete, 619 exp.Drop, 620 exp.From, 621 exp.Insert, 622 exp.Join, 623 exp.MultitableInserts, 624 exp.Select, 625 exp.SetOperation, 626 exp.Update, 627 exp.Where, 628 exp.With, 629 ) 630 631 # Expressions that should not have their comments generated in maybe_comment 632 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 633 exp.Binary, 634 exp.SetOperation, 635 ) 636 637 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 638 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 639 exp.Column, 640 exp.Literal, 641 exp.Neg, 642 exp.Paren, 643 ) 644 645 PARAMETERIZABLE_TEXT_TYPES = { 646 exp.DataType.Type.NVARCHAR, 647 exp.DataType.Type.VARCHAR, 648 exp.DataType.Type.CHAR, 649 exp.DataType.Type.NCHAR, 650 } 651 652 # Expressions that need to have all CTEs under them bubbled up to them 653 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 654 655 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 656 657 __slots__ = ( 658 "pretty", 659 "identify", 660 "normalize", 661 "pad", 662 "_indent", 663 "normalize_functions", 664 "unsupported_level", 665 "max_unsupported", 666 "leading_comma", 667 "max_text_width", 668 "comments", 669 "dialect", 670 "unsupported_messages", 671 "_escaped_quote_end", 672 "_escaped_identifier_end", 673 "_next_name", 674 "_identifier_start", 675 "_identifier_end", 676 "_quote_json_path_key_using_brackets", 677 ) 678 679 def __init__( 680 self, 681 pretty: t.Optional[bool] = None, 682 identify: str | bool = False, 683 normalize: bool = False, 684 pad: int = 2, 685 indent: int = 2, 686 normalize_functions: t.Optional[str | bool] = None, 687 unsupported_level: ErrorLevel = ErrorLevel.WARN, 688 max_unsupported: int = 3, 689 leading_comma: bool = False, 690 max_text_width: int = 80, 691 comments: bool = True, 692 dialect: DialectType = None, 693 ): 694 import sqlglot 695 from sqlglot.dialects import Dialect 696 697 self.pretty = pretty if pretty is not None else sqlglot.pretty 698 self.identify = identify 699 self.normalize = normalize 700 self.pad = pad 701 self._indent = indent 702 self.unsupported_level = unsupported_level 703 self.max_unsupported = max_unsupported 704 self.leading_comma = leading_comma 705 self.max_text_width = max_text_width 706 self.comments = comments 707 self.dialect = Dialect.get_or_raise(dialect) 708 709 # This is both a Dialect property and a Generator argument, so we prioritize the latter 710 self.normalize_functions = ( 711 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 712 ) 713 714 self.unsupported_messages: t.List[str] = [] 715 self._escaped_quote_end: str = ( 716 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 717 ) 718 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 719 720 self._next_name = name_sequence("_t") 721 722 self._identifier_start = self.dialect.IDENTIFIER_START 723 self._identifier_end = self.dialect.IDENTIFIER_END 724 725 self._quote_json_path_key_using_brackets = True 726 727 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 728 """ 729 Generates the SQL string corresponding to the given syntax tree. 730 731 Args: 732 expression: The syntax tree. 733 copy: Whether to copy the expression. The generator performs mutations so 734 it is safer to copy. 735 736 Returns: 737 The SQL string corresponding to `expression`. 738 """ 739 if copy: 740 expression = expression.copy() 741 742 expression = self.preprocess(expression) 743 744 self.unsupported_messages = [] 745 sql = self.sql(expression).strip() 746 747 if self.pretty: 748 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 749 750 if self.unsupported_level == ErrorLevel.IGNORE: 751 return sql 752 753 if self.unsupported_level == ErrorLevel.WARN: 754 for msg in self.unsupported_messages: 755 logger.warning(msg) 756 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 757 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 758 759 return sql 760 761 def preprocess(self, expression: exp.Expression) -> exp.Expression: 762 """Apply generic preprocessing transformations to a given expression.""" 763 expression = self._move_ctes_to_top_level(expression) 764 765 if self.ENSURE_BOOLS: 766 from sqlglot.transforms import ensure_bools 767 768 expression = ensure_bools(expression) 769 770 return expression 771 772 def _move_ctes_to_top_level(self, expression: E) -> E: 773 if ( 774 not expression.parent 775 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 776 and any(node.parent is not expression for node in expression.find_all(exp.With)) 777 ): 778 from sqlglot.transforms import move_ctes_to_top_level 779 780 expression = move_ctes_to_top_level(expression) 781 return expression 782 783 def unsupported(self, message: str) -> None: 784 if self.unsupported_level == ErrorLevel.IMMEDIATE: 785 raise UnsupportedError(message) 786 self.unsupported_messages.append(message) 787 788 def sep(self, sep: str = " ") -> str: 789 return f"{sep.strip()}\n" if self.pretty else sep 790 791 def seg(self, sql: str, sep: str = " ") -> str: 792 return f"{self.sep(sep)}{sql}" 793 794 def pad_comment(self, comment: str) -> str: 795 comment = " " + comment if comment[0].strip() else comment 796 comment = comment + " " if comment[-1].strip() else comment 797 return comment 798 799 def maybe_comment( 800 self, 801 sql: str, 802 expression: t.Optional[exp.Expression] = None, 803 comments: t.Optional[t.List[str]] = None, 804 separated: bool = False, 805 ) -> str: 806 comments = ( 807 ((expression and expression.comments) if comments is None else comments) # type: ignore 808 if self.comments 809 else None 810 ) 811 812 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 813 return sql 814 815 comments_sql = " ".join( 816 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 817 ) 818 819 if not comments_sql: 820 return sql 821 822 comments_sql = self._replace_line_breaks(comments_sql) 823 824 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 825 return ( 826 f"{self.sep()}{comments_sql}{sql}" 827 if not sql or sql[0].isspace() 828 else f"{comments_sql}{self.sep()}{sql}" 829 ) 830 831 return f"{sql} {comments_sql}" 832 833 def wrap(self, expression: exp.Expression | str) -> str: 834 this_sql = ( 835 self.sql(expression) 836 if isinstance(expression, exp.UNWRAPPED_QUERIES) 837 else self.sql(expression, "this") 838 ) 839 if not this_sql: 840 return "()" 841 842 this_sql = self.indent(this_sql, level=1, pad=0) 843 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 844 845 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 846 original = self.identify 847 self.identify = False 848 result = func(*args, **kwargs) 849 self.identify = original 850 return result 851 852 def normalize_func(self, name: str) -> str: 853 if self.normalize_functions == "upper" or self.normalize_functions is True: 854 return name.upper() 855 if self.normalize_functions == "lower": 856 return name.lower() 857 return name 858 859 def indent( 860 self, 861 sql: str, 862 level: int = 0, 863 pad: t.Optional[int] = None, 864 skip_first: bool = False, 865 skip_last: bool = False, 866 ) -> str: 867 if not self.pretty or not sql: 868 return sql 869 870 pad = self.pad if pad is None else pad 871 lines = sql.split("\n") 872 873 return "\n".join( 874 ( 875 line 876 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 877 else f"{' ' * (level * self._indent + pad)}{line}" 878 ) 879 for i, line in enumerate(lines) 880 ) 881 882 def sql( 883 self, 884 expression: t.Optional[str | exp.Expression], 885 key: t.Optional[str] = None, 886 comment: bool = True, 887 ) -> str: 888 if not expression: 889 return "" 890 891 if isinstance(expression, str): 892 return expression 893 894 if key: 895 value = expression.args.get(key) 896 if value: 897 return self.sql(value) 898 return "" 899 900 transform = self.TRANSFORMS.get(expression.__class__) 901 902 if callable(transform): 903 sql = transform(self, expression) 904 elif isinstance(expression, exp.Expression): 905 exp_handler_name = f"{expression.key}_sql" 906 907 if hasattr(self, exp_handler_name): 908 sql = getattr(self, exp_handler_name)(expression) 909 elif isinstance(expression, exp.Func): 910 sql = self.function_fallback_sql(expression) 911 elif isinstance(expression, exp.Property): 912 sql = self.property_sql(expression) 913 else: 914 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 915 else: 916 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 917 918 return self.maybe_comment(sql, expression) if self.comments and comment else sql 919 920 def uncache_sql(self, expression: exp.Uncache) -> str: 921 table = self.sql(expression, "this") 922 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 923 return f"UNCACHE TABLE{exists_sql} {table}" 924 925 def cache_sql(self, expression: exp.Cache) -> str: 926 lazy = " LAZY" if expression.args.get("lazy") else "" 927 table = self.sql(expression, "this") 928 options = expression.args.get("options") 929 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 930 sql = self.sql(expression, "expression") 931 sql = f" AS{self.sep()}{sql}" if sql else "" 932 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 933 return self.prepend_ctes(expression, sql) 934 935 def characterset_sql(self, expression: exp.CharacterSet) -> str: 936 if isinstance(expression.parent, exp.Cast): 937 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 938 default = "DEFAULT " if expression.args.get("default") else "" 939 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 940 941 def column_parts(self, expression: exp.Column) -> str: 942 return ".".join( 943 self.sql(part) 944 for part in ( 945 expression.args.get("catalog"), 946 expression.args.get("db"), 947 expression.args.get("table"), 948 expression.args.get("this"), 949 ) 950 if part 951 ) 952 953 def column_sql(self, expression: exp.Column) -> str: 954 join_mark = " (+)" if expression.args.get("join_mark") else "" 955 956 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 957 join_mark = "" 958 self.unsupported("Outer join syntax using the (+) operator is not supported.") 959 960 return f"{self.column_parts(expression)}{join_mark}" 961 962 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 963 this = self.sql(expression, "this") 964 this = f" {this}" if this else "" 965 position = self.sql(expression, "position") 966 return f"{position}{this}" 967 968 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 969 column = self.sql(expression, "this") 970 kind = self.sql(expression, "kind") 971 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 972 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 973 kind = f"{sep}{kind}" if kind else "" 974 constraints = f" {constraints}" if constraints else "" 975 position = self.sql(expression, "position") 976 position = f" {position}" if position else "" 977 978 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 979 kind = "" 980 981 return f"{exists}{column}{kind}{constraints}{position}" 982 983 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 984 this = self.sql(expression, "this") 985 kind_sql = self.sql(expression, "kind").strip() 986 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 987 988 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 989 this = self.sql(expression, "this") 990 if expression.args.get("not_null"): 991 persisted = " PERSISTED NOT NULL" 992 elif expression.args.get("persisted"): 993 persisted = " PERSISTED" 994 else: 995 persisted = "" 996 return f"AS {this}{persisted}" 997 998 def autoincrementcolumnconstraint_sql(self, _) -> str: 999 return self.token_sql(TokenType.AUTO_INCREMENT) 1000 1001 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 1002 if isinstance(expression.this, list): 1003 this = self.wrap(self.expressions(expression, key="this", flat=True)) 1004 else: 1005 this = self.sql(expression, "this") 1006 1007 return f"COMPRESS {this}" 1008 1009 def generatedasidentitycolumnconstraint_sql( 1010 self, expression: exp.GeneratedAsIdentityColumnConstraint 1011 ) -> str: 1012 this = "" 1013 if expression.this is not None: 1014 on_null = " ON NULL" if expression.args.get("on_null") else "" 1015 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1016 1017 start = expression.args.get("start") 1018 start = f"START WITH {start}" if start else "" 1019 increment = expression.args.get("increment") 1020 increment = f" INCREMENT BY {increment}" if increment else "" 1021 minvalue = expression.args.get("minvalue") 1022 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1023 maxvalue = expression.args.get("maxvalue") 1024 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1025 cycle = expression.args.get("cycle") 1026 cycle_sql = "" 1027 1028 if cycle is not None: 1029 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1030 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1031 1032 sequence_opts = "" 1033 if start or increment or cycle_sql: 1034 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1035 sequence_opts = f" ({sequence_opts.strip()})" 1036 1037 expr = self.sql(expression, "expression") 1038 expr = f"({expr})" if expr else "IDENTITY" 1039 1040 return f"GENERATED{this} AS {expr}{sequence_opts}" 1041 1042 def generatedasrowcolumnconstraint_sql( 1043 self, expression: exp.GeneratedAsRowColumnConstraint 1044 ) -> str: 1045 start = "START" if expression.args.get("start") else "END" 1046 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1047 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1048 1049 def periodforsystemtimeconstraint_sql( 1050 self, expression: exp.PeriodForSystemTimeConstraint 1051 ) -> str: 1052 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1053 1054 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1055 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1056 1057 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1058 return f"AS {self.sql(expression, 'this')}" 1059 1060 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1061 desc = expression.args.get("desc") 1062 if desc is not None: 1063 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1064 return "PRIMARY KEY" 1065 1066 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1067 this = self.sql(expression, "this") 1068 this = f" {this}" if this else "" 1069 index_type = expression.args.get("index_type") 1070 index_type = f" USING {index_type}" if index_type else "" 1071 on_conflict = self.sql(expression, "on_conflict") 1072 on_conflict = f" {on_conflict}" if on_conflict else "" 1073 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1074 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1075 1076 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1077 return self.sql(expression, "this") 1078 1079 def create_sql(self, expression: exp.Create) -> str: 1080 kind = self.sql(expression, "kind") 1081 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1082 properties = expression.args.get("properties") 1083 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1084 1085 this = self.createable_sql(expression, properties_locs) 1086 1087 properties_sql = "" 1088 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1089 exp.Properties.Location.POST_WITH 1090 ): 1091 properties_sql = self.sql( 1092 exp.Properties( 1093 expressions=[ 1094 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1095 *properties_locs[exp.Properties.Location.POST_WITH], 1096 ] 1097 ) 1098 ) 1099 1100 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1101 properties_sql = self.sep() + properties_sql 1102 elif not self.pretty: 1103 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1104 properties_sql = f" {properties_sql}" 1105 1106 begin = " BEGIN" if expression.args.get("begin") else "" 1107 end = " END" if expression.args.get("end") else "" 1108 1109 expression_sql = self.sql(expression, "expression") 1110 if expression_sql: 1111 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1112 1113 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1114 postalias_props_sql = "" 1115 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1116 postalias_props_sql = self.properties( 1117 exp.Properties( 1118 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1119 ), 1120 wrapped=False, 1121 ) 1122 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1123 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1124 1125 postindex_props_sql = "" 1126 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1127 postindex_props_sql = self.properties( 1128 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1129 wrapped=False, 1130 prefix=" ", 1131 ) 1132 1133 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1134 indexes = f" {indexes}" if indexes else "" 1135 index_sql = indexes + postindex_props_sql 1136 1137 replace = " OR REPLACE" if expression.args.get("replace") else "" 1138 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1139 unique = " UNIQUE" if expression.args.get("unique") else "" 1140 1141 clustered = expression.args.get("clustered") 1142 if clustered is None: 1143 clustered_sql = "" 1144 elif clustered: 1145 clustered_sql = " CLUSTERED COLUMNSTORE" 1146 else: 1147 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1148 1149 postcreate_props_sql = "" 1150 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1151 postcreate_props_sql = self.properties( 1152 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1153 sep=" ", 1154 prefix=" ", 1155 wrapped=False, 1156 ) 1157 1158 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1159 1160 postexpression_props_sql = "" 1161 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1162 postexpression_props_sql = self.properties( 1163 exp.Properties( 1164 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1165 ), 1166 sep=" ", 1167 prefix=" ", 1168 wrapped=False, 1169 ) 1170 1171 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1172 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1173 no_schema_binding = ( 1174 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1175 ) 1176 1177 clone = self.sql(expression, "clone") 1178 clone = f" {clone}" if clone else "" 1179 1180 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1181 properties_expression = f"{expression_sql}{properties_sql}" 1182 else: 1183 properties_expression = f"{properties_sql}{expression_sql}" 1184 1185 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1186 return self.prepend_ctes(expression, expression_sql) 1187 1188 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1189 start = self.sql(expression, "start") 1190 start = f"START WITH {start}" if start else "" 1191 increment = self.sql(expression, "increment") 1192 increment = f" INCREMENT BY {increment}" if increment else "" 1193 minvalue = self.sql(expression, "minvalue") 1194 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1195 maxvalue = self.sql(expression, "maxvalue") 1196 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1197 owned = self.sql(expression, "owned") 1198 owned = f" OWNED BY {owned}" if owned else "" 1199 1200 cache = expression.args.get("cache") 1201 if cache is None: 1202 cache_str = "" 1203 elif cache is True: 1204 cache_str = " CACHE" 1205 else: 1206 cache_str = f" CACHE {cache}" 1207 1208 options = self.expressions(expression, key="options", flat=True, sep=" ") 1209 options = f" {options}" if options else "" 1210 1211 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1212 1213 def clone_sql(self, expression: exp.Clone) -> str: 1214 this = self.sql(expression, "this") 1215 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1216 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1217 return f"{shallow}{keyword} {this}" 1218 1219 def describe_sql(self, expression: exp.Describe) -> str: 1220 style = expression.args.get("style") 1221 style = f" {style}" if style else "" 1222 partition = self.sql(expression, "partition") 1223 partition = f" {partition}" if partition else "" 1224 format = self.sql(expression, "format") 1225 format = f" {format}" if format else "" 1226 1227 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1228 1229 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1230 tag = self.sql(expression, "tag") 1231 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1232 1233 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1234 with_ = self.sql(expression, "with") 1235 if with_: 1236 sql = f"{with_}{self.sep()}{sql}" 1237 return sql 1238 1239 def with_sql(self, expression: exp.With) -> str: 1240 sql = self.expressions(expression, flat=True) 1241 recursive = ( 1242 "RECURSIVE " 1243 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1244 else "" 1245 ) 1246 search = self.sql(expression, "search") 1247 search = f" {search}" if search else "" 1248 1249 return f"WITH {recursive}{sql}{search}" 1250 1251 def cte_sql(self, expression: exp.CTE) -> str: 1252 alias = expression.args.get("alias") 1253 if alias: 1254 alias.add_comments(expression.pop_comments()) 1255 1256 alias_sql = self.sql(expression, "alias") 1257 1258 materialized = expression.args.get("materialized") 1259 if materialized is False: 1260 materialized = "NOT MATERIALIZED " 1261 elif materialized: 1262 materialized = "MATERIALIZED " 1263 1264 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1265 1266 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1267 alias = self.sql(expression, "this") 1268 columns = self.expressions(expression, key="columns", flat=True) 1269 columns = f"({columns})" if columns else "" 1270 1271 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1272 columns = "" 1273 self.unsupported("Named columns are not supported in table alias.") 1274 1275 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1276 alias = self._next_name() 1277 1278 return f"{alias}{columns}" 1279 1280 def bitstring_sql(self, expression: exp.BitString) -> str: 1281 this = self.sql(expression, "this") 1282 if self.dialect.BIT_START: 1283 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1284 return f"{int(this, 2)}" 1285 1286 def hexstring_sql( 1287 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1288 ) -> str: 1289 this = self.sql(expression, "this") 1290 is_integer_type = expression.args.get("is_integer") 1291 1292 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1293 not self.dialect.HEX_START and not binary_function_repr 1294 ): 1295 # Integer representation will be returned if: 1296 # - The read dialect treats the hex value as integer literal but not the write 1297 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1298 return f"{int(this, 16)}" 1299 1300 if not is_integer_type: 1301 # Read dialect treats the hex value as BINARY/BLOB 1302 if binary_function_repr: 1303 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1304 return self.func(binary_function_repr, exp.Literal.string(this)) 1305 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1306 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1307 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1308 1309 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1310 1311 def bytestring_sql(self, expression: exp.ByteString) -> str: 1312 this = self.sql(expression, "this") 1313 if self.dialect.BYTE_START: 1314 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1315 return this 1316 1317 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1318 this = self.sql(expression, "this") 1319 escape = expression.args.get("escape") 1320 1321 if self.dialect.UNICODE_START: 1322 escape_substitute = r"\\\1" 1323 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1324 else: 1325 escape_substitute = r"\\u\1" 1326 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1327 1328 if escape: 1329 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1330 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1331 else: 1332 escape_pattern = ESCAPED_UNICODE_RE 1333 escape_sql = "" 1334 1335 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1336 this = escape_pattern.sub(escape_substitute, this) 1337 1338 return f"{left_quote}{this}{right_quote}{escape_sql}" 1339 1340 def rawstring_sql(self, expression: exp.RawString) -> str: 1341 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1342 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1343 1344 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1345 this = self.sql(expression, "this") 1346 specifier = self.sql(expression, "expression") 1347 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1348 return f"{this}{specifier}" 1349 1350 def datatype_sql(self, expression: exp.DataType) -> str: 1351 nested = "" 1352 values = "" 1353 interior = self.expressions(expression, flat=True) 1354 1355 type_value = expression.this 1356 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1357 type_sql = self.sql(expression, "kind") 1358 else: 1359 type_sql = ( 1360 self.TYPE_MAPPING.get(type_value, type_value.value) 1361 if isinstance(type_value, exp.DataType.Type) 1362 else type_value 1363 ) 1364 1365 if interior: 1366 if expression.args.get("nested"): 1367 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1368 if expression.args.get("values") is not None: 1369 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1370 values = self.expressions(expression, key="values", flat=True) 1371 values = f"{delimiters[0]}{values}{delimiters[1]}" 1372 elif type_value == exp.DataType.Type.INTERVAL: 1373 nested = f" {interior}" 1374 else: 1375 nested = f"({interior})" 1376 1377 type_sql = f"{type_sql}{nested}{values}" 1378 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1379 exp.DataType.Type.TIMETZ, 1380 exp.DataType.Type.TIMESTAMPTZ, 1381 ): 1382 type_sql = f"{type_sql} WITH TIME ZONE" 1383 1384 return type_sql 1385 1386 def directory_sql(self, expression: exp.Directory) -> str: 1387 local = "LOCAL " if expression.args.get("local") else "" 1388 row_format = self.sql(expression, "row_format") 1389 row_format = f" {row_format}" if row_format else "" 1390 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1391 1392 def delete_sql(self, expression: exp.Delete) -> str: 1393 this = self.sql(expression, "this") 1394 this = f" FROM {this}" if this else "" 1395 using = self.sql(expression, "using") 1396 using = f" USING {using}" if using else "" 1397 cluster = self.sql(expression, "cluster") 1398 cluster = f" {cluster}" if cluster else "" 1399 where = self.sql(expression, "where") 1400 returning = self.sql(expression, "returning") 1401 limit = self.sql(expression, "limit") 1402 tables = self.expressions(expression, key="tables") 1403 tables = f" {tables}" if tables else "" 1404 if self.RETURNING_END: 1405 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1406 else: 1407 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1408 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1409 1410 def drop_sql(self, expression: exp.Drop) -> str: 1411 this = self.sql(expression, "this") 1412 expressions = self.expressions(expression, flat=True) 1413 expressions = f" ({expressions})" if expressions else "" 1414 kind = expression.args["kind"] 1415 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1416 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1417 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1418 on_cluster = self.sql(expression, "cluster") 1419 on_cluster = f" {on_cluster}" if on_cluster else "" 1420 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1421 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1422 cascade = " CASCADE" if expression.args.get("cascade") else "" 1423 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1424 purge = " PURGE" if expression.args.get("purge") else "" 1425 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1426 1427 def set_operation(self, expression: exp.SetOperation) -> str: 1428 op_type = type(expression) 1429 op_name = op_type.key.upper() 1430 1431 distinct = expression.args.get("distinct") 1432 if ( 1433 distinct is False 1434 and op_type in (exp.Except, exp.Intersect) 1435 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1436 ): 1437 self.unsupported(f"{op_name} ALL is not supported") 1438 1439 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1440 1441 if distinct is None: 1442 distinct = default_distinct 1443 if distinct is None: 1444 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1445 1446 if distinct is default_distinct: 1447 kind = "" 1448 else: 1449 kind = " DISTINCT" if distinct else " ALL" 1450 1451 by_name = " BY NAME" if expression.args.get("by_name") else "" 1452 return f"{op_name}{kind}{by_name}" 1453 1454 def set_operations(self, expression: exp.SetOperation) -> str: 1455 if not self.SET_OP_MODIFIERS: 1456 limit = expression.args.get("limit") 1457 order = expression.args.get("order") 1458 1459 if limit or order: 1460 select = self._move_ctes_to_top_level( 1461 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1462 ) 1463 1464 if limit: 1465 select = select.limit(limit.pop(), copy=False) 1466 if order: 1467 select = select.order_by(order.pop(), copy=False) 1468 return self.sql(select) 1469 1470 sqls: t.List[str] = [] 1471 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1472 1473 while stack: 1474 node = stack.pop() 1475 1476 if isinstance(node, exp.SetOperation): 1477 stack.append(node.expression) 1478 stack.append( 1479 self.maybe_comment( 1480 self.set_operation(node), comments=node.comments, separated=True 1481 ) 1482 ) 1483 stack.append(node.this) 1484 else: 1485 sqls.append(self.sql(node)) 1486 1487 this = self.sep().join(sqls) 1488 this = self.query_modifiers(expression, this) 1489 return self.prepend_ctes(expression, this) 1490 1491 def fetch_sql(self, expression: exp.Fetch) -> str: 1492 direction = expression.args.get("direction") 1493 direction = f" {direction}" if direction else "" 1494 count = self.sql(expression, "count") 1495 count = f" {count}" if count else "" 1496 limit_options = self.sql(expression, "limit_options") 1497 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1498 return f"{self.seg('FETCH')}{direction}{count}{limit_options}" 1499 1500 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1501 percent = " PERCENT" if expression.args.get("percent") else "" 1502 rows = " ROWS" if expression.args.get("rows") else "" 1503 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1504 if not with_ties and rows: 1505 with_ties = " ONLY" 1506 return f"{percent}{rows}{with_ties}" 1507 1508 def filter_sql(self, expression: exp.Filter) -> str: 1509 if self.AGGREGATE_FILTER_SUPPORTED: 1510 this = self.sql(expression, "this") 1511 where = self.sql(expression, "expression").strip() 1512 return f"{this} FILTER({where})" 1513 1514 agg = expression.this 1515 agg_arg = agg.this 1516 cond = expression.expression.this 1517 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1518 return self.sql(agg) 1519 1520 def hint_sql(self, expression: exp.Hint) -> str: 1521 if not self.QUERY_HINTS: 1522 self.unsupported("Hints are not supported") 1523 return "" 1524 1525 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1526 1527 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1528 using = self.sql(expression, "using") 1529 using = f" USING {using}" if using else "" 1530 columns = self.expressions(expression, key="columns", flat=True) 1531 columns = f"({columns})" if columns else "" 1532 partition_by = self.expressions(expression, key="partition_by", flat=True) 1533 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1534 where = self.sql(expression, "where") 1535 include = self.expressions(expression, key="include", flat=True) 1536 if include: 1537 include = f" INCLUDE ({include})" 1538 with_storage = self.expressions(expression, key="with_storage", flat=True) 1539 with_storage = f" WITH ({with_storage})" if with_storage else "" 1540 tablespace = self.sql(expression, "tablespace") 1541 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1542 on = self.sql(expression, "on") 1543 on = f" ON {on}" if on else "" 1544 1545 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1546 1547 def index_sql(self, expression: exp.Index) -> str: 1548 unique = "UNIQUE " if expression.args.get("unique") else "" 1549 primary = "PRIMARY " if expression.args.get("primary") else "" 1550 amp = "AMP " if expression.args.get("amp") else "" 1551 name = self.sql(expression, "this") 1552 name = f"{name} " if name else "" 1553 table = self.sql(expression, "table") 1554 table = f"{self.INDEX_ON} {table}" if table else "" 1555 1556 index = "INDEX " if not table else "" 1557 1558 params = self.sql(expression, "params") 1559 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1560 1561 def identifier_sql(self, expression: exp.Identifier) -> str: 1562 text = expression.name 1563 lower = text.lower() 1564 text = lower if self.normalize and not expression.quoted else text 1565 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1566 if ( 1567 expression.quoted 1568 or self.dialect.can_identify(text, self.identify) 1569 or lower in self.RESERVED_KEYWORDS 1570 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1571 ): 1572 text = f"{self._identifier_start}{text}{self._identifier_end}" 1573 return text 1574 1575 def hex_sql(self, expression: exp.Hex) -> str: 1576 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1577 if self.dialect.HEX_LOWERCASE: 1578 text = self.func("LOWER", text) 1579 1580 return text 1581 1582 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1583 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1584 if not self.dialect.HEX_LOWERCASE: 1585 text = self.func("LOWER", text) 1586 return text 1587 1588 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1589 input_format = self.sql(expression, "input_format") 1590 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1591 output_format = self.sql(expression, "output_format") 1592 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1593 return self.sep().join((input_format, output_format)) 1594 1595 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1596 string = self.sql(exp.Literal.string(expression.name)) 1597 return f"{prefix}{string}" 1598 1599 def partition_sql(self, expression: exp.Partition) -> str: 1600 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1601 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1602 1603 def properties_sql(self, expression: exp.Properties) -> str: 1604 root_properties = [] 1605 with_properties = [] 1606 1607 for p in expression.expressions: 1608 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1609 if p_loc == exp.Properties.Location.POST_WITH: 1610 with_properties.append(p) 1611 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1612 root_properties.append(p) 1613 1614 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1615 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1616 1617 if root_props and with_props and not self.pretty: 1618 with_props = " " + with_props 1619 1620 return root_props + with_props 1621 1622 def root_properties(self, properties: exp.Properties) -> str: 1623 if properties.expressions: 1624 return self.expressions(properties, indent=False, sep=" ") 1625 return "" 1626 1627 def properties( 1628 self, 1629 properties: exp.Properties, 1630 prefix: str = "", 1631 sep: str = ", ", 1632 suffix: str = "", 1633 wrapped: bool = True, 1634 ) -> str: 1635 if properties.expressions: 1636 expressions = self.expressions(properties, sep=sep, indent=False) 1637 if expressions: 1638 expressions = self.wrap(expressions) if wrapped else expressions 1639 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1640 return "" 1641 1642 def with_properties(self, properties: exp.Properties) -> str: 1643 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1644 1645 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1646 properties_locs = defaultdict(list) 1647 for p in properties.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc != exp.Properties.Location.UNSUPPORTED: 1650 properties_locs[p_loc].append(p) 1651 else: 1652 self.unsupported(f"Unsupported property {p.key}") 1653 1654 return properties_locs 1655 1656 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1657 if isinstance(expression.this, exp.Dot): 1658 return self.sql(expression, "this") 1659 return f"'{expression.name}'" if string_key else expression.name 1660 1661 def property_sql(self, expression: exp.Property) -> str: 1662 property_cls = expression.__class__ 1663 if property_cls == exp.Property: 1664 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1665 1666 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1667 if not property_name: 1668 self.unsupported(f"Unsupported property {expression.key}") 1669 1670 return f"{property_name}={self.sql(expression, 'this')}" 1671 1672 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1673 if self.SUPPORTS_CREATE_TABLE_LIKE: 1674 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1675 options = f" {options}" if options else "" 1676 1677 like = f"LIKE {self.sql(expression, 'this')}{options}" 1678 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1679 like = f"({like})" 1680 1681 return like 1682 1683 if expression.expressions: 1684 self.unsupported("Transpilation of LIKE property options is unsupported") 1685 1686 select = exp.select("*").from_(expression.this).limit(0) 1687 return f"AS {self.sql(select)}" 1688 1689 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1690 no = "NO " if expression.args.get("no") else "" 1691 protection = " PROTECTION" if expression.args.get("protection") else "" 1692 return f"{no}FALLBACK{protection}" 1693 1694 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1695 no = "NO " if expression.args.get("no") else "" 1696 local = expression.args.get("local") 1697 local = f"{local} " if local else "" 1698 dual = "DUAL " if expression.args.get("dual") else "" 1699 before = "BEFORE " if expression.args.get("before") else "" 1700 after = "AFTER " if expression.args.get("after") else "" 1701 return f"{no}{local}{dual}{before}{after}JOURNAL" 1702 1703 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1704 freespace = self.sql(expression, "this") 1705 percent = " PERCENT" if expression.args.get("percent") else "" 1706 return f"FREESPACE={freespace}{percent}" 1707 1708 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1709 if expression.args.get("default"): 1710 property = "DEFAULT" 1711 elif expression.args.get("on"): 1712 property = "ON" 1713 else: 1714 property = "OFF" 1715 return f"CHECKSUM={property}" 1716 1717 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1718 if expression.args.get("no"): 1719 return "NO MERGEBLOCKRATIO" 1720 if expression.args.get("default"): 1721 return "DEFAULT MERGEBLOCKRATIO" 1722 1723 percent = " PERCENT" if expression.args.get("percent") else "" 1724 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1725 1726 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1727 default = expression.args.get("default") 1728 minimum = expression.args.get("minimum") 1729 maximum = expression.args.get("maximum") 1730 if default or minimum or maximum: 1731 if default: 1732 prop = "DEFAULT" 1733 elif minimum: 1734 prop = "MINIMUM" 1735 else: 1736 prop = "MAXIMUM" 1737 return f"{prop} DATABLOCKSIZE" 1738 units = expression.args.get("units") 1739 units = f" {units}" if units else "" 1740 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1741 1742 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1743 autotemp = expression.args.get("autotemp") 1744 always = expression.args.get("always") 1745 default = expression.args.get("default") 1746 manual = expression.args.get("manual") 1747 never = expression.args.get("never") 1748 1749 if autotemp is not None: 1750 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1751 elif always: 1752 prop = "ALWAYS" 1753 elif default: 1754 prop = "DEFAULT" 1755 elif manual: 1756 prop = "MANUAL" 1757 elif never: 1758 prop = "NEVER" 1759 return f"BLOCKCOMPRESSION={prop}" 1760 1761 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1762 no = expression.args.get("no") 1763 no = " NO" if no else "" 1764 concurrent = expression.args.get("concurrent") 1765 concurrent = " CONCURRENT" if concurrent else "" 1766 target = self.sql(expression, "target") 1767 target = f" {target}" if target else "" 1768 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1769 1770 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1771 if isinstance(expression.this, list): 1772 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1773 if expression.this: 1774 modulus = self.sql(expression, "this") 1775 remainder = self.sql(expression, "expression") 1776 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1777 1778 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1779 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1780 return f"FROM ({from_expressions}) TO ({to_expressions})" 1781 1782 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1783 this = self.sql(expression, "this") 1784 1785 for_values_or_default = expression.expression 1786 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1787 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1788 else: 1789 for_values_or_default = " DEFAULT" 1790 1791 return f"PARTITION OF {this}{for_values_or_default}" 1792 1793 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1794 kind = expression.args.get("kind") 1795 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1796 for_or_in = expression.args.get("for_or_in") 1797 for_or_in = f" {for_or_in}" if for_or_in else "" 1798 lock_type = expression.args.get("lock_type") 1799 override = " OVERRIDE" if expression.args.get("override") else "" 1800 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1801 1802 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1803 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1804 statistics = expression.args.get("statistics") 1805 statistics_sql = "" 1806 if statistics is not None: 1807 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1808 return f"{data_sql}{statistics_sql}" 1809 1810 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1811 this = self.sql(expression, "this") 1812 this = f"HISTORY_TABLE={this}" if this else "" 1813 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1814 data_consistency = ( 1815 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1816 ) 1817 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1818 retention_period = ( 1819 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1820 ) 1821 1822 if this: 1823 on_sql = self.func("ON", this, data_consistency, retention_period) 1824 else: 1825 on_sql = "ON" if expression.args.get("on") else "OFF" 1826 1827 sql = f"SYSTEM_VERSIONING={on_sql}" 1828 1829 return f"WITH({sql})" if expression.args.get("with") else sql 1830 1831 def insert_sql(self, expression: exp.Insert) -> str: 1832 hint = self.sql(expression, "hint") 1833 overwrite = expression.args.get("overwrite") 1834 1835 if isinstance(expression.this, exp.Directory): 1836 this = " OVERWRITE" if overwrite else " INTO" 1837 else: 1838 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1839 1840 stored = self.sql(expression, "stored") 1841 stored = f" {stored}" if stored else "" 1842 alternative = expression.args.get("alternative") 1843 alternative = f" OR {alternative}" if alternative else "" 1844 ignore = " IGNORE" if expression.args.get("ignore") else "" 1845 is_function = expression.args.get("is_function") 1846 if is_function: 1847 this = f"{this} FUNCTION" 1848 this = f"{this} {self.sql(expression, 'this')}" 1849 1850 exists = " IF EXISTS" if expression.args.get("exists") else "" 1851 where = self.sql(expression, "where") 1852 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1853 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1854 on_conflict = self.sql(expression, "conflict") 1855 on_conflict = f" {on_conflict}" if on_conflict else "" 1856 by_name = " BY NAME" if expression.args.get("by_name") else "" 1857 returning = self.sql(expression, "returning") 1858 1859 if self.RETURNING_END: 1860 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1861 else: 1862 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1863 1864 partition_by = self.sql(expression, "partition") 1865 partition_by = f" {partition_by}" if partition_by else "" 1866 settings = self.sql(expression, "settings") 1867 settings = f" {settings}" if settings else "" 1868 1869 source = self.sql(expression, "source") 1870 source = f"TABLE {source}" if source else "" 1871 1872 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1873 return self.prepend_ctes(expression, sql) 1874 1875 def introducer_sql(self, expression: exp.Introducer) -> str: 1876 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1877 1878 def kill_sql(self, expression: exp.Kill) -> str: 1879 kind = self.sql(expression, "kind") 1880 kind = f" {kind}" if kind else "" 1881 this = self.sql(expression, "this") 1882 this = f" {this}" if this else "" 1883 return f"KILL{kind}{this}" 1884 1885 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1886 return expression.name 1887 1888 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1889 return expression.name 1890 1891 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1892 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1893 1894 constraint = self.sql(expression, "constraint") 1895 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1896 1897 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1898 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1899 action = self.sql(expression, "action") 1900 1901 expressions = self.expressions(expression, flat=True) 1902 if expressions: 1903 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1904 expressions = f" {set_keyword}{expressions}" 1905 1906 where = self.sql(expression, "where") 1907 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1908 1909 def returning_sql(self, expression: exp.Returning) -> str: 1910 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1911 1912 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1913 fields = self.sql(expression, "fields") 1914 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1915 escaped = self.sql(expression, "escaped") 1916 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1917 items = self.sql(expression, "collection_items") 1918 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1919 keys = self.sql(expression, "map_keys") 1920 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1921 lines = self.sql(expression, "lines") 1922 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1923 null = self.sql(expression, "null") 1924 null = f" NULL DEFINED AS {null}" if null else "" 1925 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1926 1927 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1928 return f"WITH ({self.expressions(expression, flat=True)})" 1929 1930 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1931 this = f"{self.sql(expression, 'this')} INDEX" 1932 target = self.sql(expression, "target") 1933 target = f" FOR {target}" if target else "" 1934 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1935 1936 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1937 this = self.sql(expression, "this") 1938 kind = self.sql(expression, "kind") 1939 expr = self.sql(expression, "expression") 1940 return f"{this} ({kind} => {expr})" 1941 1942 def table_parts(self, expression: exp.Table) -> str: 1943 return ".".join( 1944 self.sql(part) 1945 for part in ( 1946 expression.args.get("catalog"), 1947 expression.args.get("db"), 1948 expression.args.get("this"), 1949 ) 1950 if part is not None 1951 ) 1952 1953 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1954 table = self.table_parts(expression) 1955 only = "ONLY " if expression.args.get("only") else "" 1956 partition = self.sql(expression, "partition") 1957 partition = f" {partition}" if partition else "" 1958 version = self.sql(expression, "version") 1959 version = f" {version}" if version else "" 1960 alias = self.sql(expression, "alias") 1961 alias = f"{sep}{alias}" if alias else "" 1962 1963 sample = self.sql(expression, "sample") 1964 if self.dialect.ALIAS_POST_TABLESAMPLE: 1965 sample_pre_alias = sample 1966 sample_post_alias = "" 1967 else: 1968 sample_pre_alias = "" 1969 sample_post_alias = sample 1970 1971 hints = self.expressions(expression, key="hints", sep=" ") 1972 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1973 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1974 joins = self.indent( 1975 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1976 ) 1977 laterals = self.expressions(expression, key="laterals", sep="") 1978 1979 file_format = self.sql(expression, "format") 1980 if file_format: 1981 pattern = self.sql(expression, "pattern") 1982 pattern = f", PATTERN => {pattern}" if pattern else "" 1983 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1984 1985 ordinality = expression.args.get("ordinality") or "" 1986 if ordinality: 1987 ordinality = f" WITH ORDINALITY{alias}" 1988 alias = "" 1989 1990 when = self.sql(expression, "when") 1991 if when: 1992 table = f"{table} {when}" 1993 1994 changes = self.sql(expression, "changes") 1995 changes = f" {changes}" if changes else "" 1996 1997 rows_from = self.expressions(expression, key="rows_from") 1998 if rows_from: 1999 table = f"ROWS FROM {self.wrap(rows_from)}" 2000 2001 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 2002 2003 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2004 table = self.func("TABLE", expression.this) 2005 alias = self.sql(expression, "alias") 2006 alias = f" AS {alias}" if alias else "" 2007 sample = self.sql(expression, "sample") 2008 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2009 joins = self.indent( 2010 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2011 ) 2012 return f"{table}{alias}{pivots}{sample}{joins}" 2013 2014 def tablesample_sql( 2015 self, 2016 expression: exp.TableSample, 2017 tablesample_keyword: t.Optional[str] = None, 2018 ) -> str: 2019 method = self.sql(expression, "method") 2020 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2021 numerator = self.sql(expression, "bucket_numerator") 2022 denominator = self.sql(expression, "bucket_denominator") 2023 field = self.sql(expression, "bucket_field") 2024 field = f" ON {field}" if field else "" 2025 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2026 seed = self.sql(expression, "seed") 2027 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2028 2029 size = self.sql(expression, "size") 2030 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2031 size = f"{size} ROWS" 2032 2033 percent = self.sql(expression, "percent") 2034 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2035 percent = f"{percent} PERCENT" 2036 2037 expr = f"{bucket}{percent}{size}" 2038 if self.TABLESAMPLE_REQUIRES_PARENS: 2039 expr = f"({expr})" 2040 2041 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 2042 2043 def pivot_sql(self, expression: exp.Pivot) -> str: 2044 expressions = self.expressions(expression, flat=True) 2045 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2046 2047 if expression.this: 2048 this = self.sql(expression, "this") 2049 if not expressions: 2050 return f"UNPIVOT {this}" 2051 2052 on = f"{self.seg('ON')} {expressions}" 2053 into = self.sql(expression, "into") 2054 into = f"{self.seg('INTO')} {into}" if into else "" 2055 using = self.expressions(expression, key="using", flat=True) 2056 using = f"{self.seg('USING')} {using}" if using else "" 2057 group = self.sql(expression, "group") 2058 return f"{direction} {this}{on}{into}{using}{group}" 2059 2060 alias = self.sql(expression, "alias") 2061 alias = f" AS {alias}" if alias else "" 2062 2063 field = self.sql(expression, "field") 2064 2065 include_nulls = expression.args.get("include_nulls") 2066 if include_nulls is not None: 2067 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2068 else: 2069 nulls = "" 2070 2071 default_on_null = self.sql(expression, "default_on_null") 2072 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2073 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2074 2075 def version_sql(self, expression: exp.Version) -> str: 2076 this = f"FOR {expression.name}" 2077 kind = expression.text("kind") 2078 expr = self.sql(expression, "expression") 2079 return f"{this} {kind} {expr}" 2080 2081 def tuple_sql(self, expression: exp.Tuple) -> str: 2082 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2083 2084 def update_sql(self, expression: exp.Update) -> str: 2085 this = self.sql(expression, "this") 2086 set_sql = self.expressions(expression, flat=True) 2087 from_sql = self.sql(expression, "from") 2088 where_sql = self.sql(expression, "where") 2089 returning = self.sql(expression, "returning") 2090 order = self.sql(expression, "order") 2091 limit = self.sql(expression, "limit") 2092 if self.RETURNING_END: 2093 expression_sql = f"{from_sql}{where_sql}{returning}" 2094 else: 2095 expression_sql = f"{returning}{from_sql}{where_sql}" 2096 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2097 return self.prepend_ctes(expression, sql) 2098 2099 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2100 values_as_table = values_as_table and self.VALUES_AS_TABLE 2101 2102 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2103 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2104 args = self.expressions(expression) 2105 alias = self.sql(expression, "alias") 2106 values = f"VALUES{self.seg('')}{args}" 2107 values = ( 2108 f"({values})" 2109 if self.WRAP_DERIVED_VALUES 2110 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2111 else values 2112 ) 2113 return f"{values} AS {alias}" if alias else values 2114 2115 # Converts `VALUES...` expression into a series of select unions. 2116 alias_node = expression.args.get("alias") 2117 column_names = alias_node and alias_node.columns 2118 2119 selects: t.List[exp.Query] = [] 2120 2121 for i, tup in enumerate(expression.expressions): 2122 row = tup.expressions 2123 2124 if i == 0 and column_names: 2125 row = [ 2126 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2127 ] 2128 2129 selects.append(exp.Select(expressions=row)) 2130 2131 if self.pretty: 2132 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2133 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2134 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2135 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2136 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2137 2138 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2139 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2140 return f"({unions}){alias}" 2141 2142 def var_sql(self, expression: exp.Var) -> str: 2143 return self.sql(expression, "this") 2144 2145 @unsupported_args("expressions") 2146 def into_sql(self, expression: exp.Into) -> str: 2147 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2148 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2149 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2150 2151 def from_sql(self, expression: exp.From) -> str: 2152 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2153 2154 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2155 grouping_sets = self.expressions(expression, indent=False) 2156 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2157 2158 def rollup_sql(self, expression: exp.Rollup) -> str: 2159 expressions = self.expressions(expression, indent=False) 2160 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2161 2162 def cube_sql(self, expression: exp.Cube) -> str: 2163 expressions = self.expressions(expression, indent=False) 2164 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2165 2166 def group_sql(self, expression: exp.Group) -> str: 2167 group_by_all = expression.args.get("all") 2168 if group_by_all is True: 2169 modifier = " ALL" 2170 elif group_by_all is False: 2171 modifier = " DISTINCT" 2172 else: 2173 modifier = "" 2174 2175 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2176 2177 grouping_sets = self.expressions(expression, key="grouping_sets") 2178 cube = self.expressions(expression, key="cube") 2179 rollup = self.expressions(expression, key="rollup") 2180 2181 groupings = csv( 2182 self.seg(grouping_sets) if grouping_sets else "", 2183 self.seg(cube) if cube else "", 2184 self.seg(rollup) if rollup else "", 2185 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2186 sep=self.GROUPINGS_SEP, 2187 ) 2188 2189 if ( 2190 expression.expressions 2191 and groupings 2192 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2193 ): 2194 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2195 2196 return f"{group_by}{groupings}" 2197 2198 def having_sql(self, expression: exp.Having) -> str: 2199 this = self.indent(self.sql(expression, "this")) 2200 return f"{self.seg('HAVING')}{self.sep()}{this}" 2201 2202 def connect_sql(self, expression: exp.Connect) -> str: 2203 start = self.sql(expression, "start") 2204 start = self.seg(f"START WITH {start}") if start else "" 2205 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2206 connect = self.sql(expression, "connect") 2207 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2208 return start + connect 2209 2210 def prior_sql(self, expression: exp.Prior) -> str: 2211 return f"PRIOR {self.sql(expression, 'this')}" 2212 2213 def join_sql(self, expression: exp.Join) -> str: 2214 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2215 side = None 2216 else: 2217 side = expression.side 2218 2219 op_sql = " ".join( 2220 op 2221 for op in ( 2222 expression.method, 2223 "GLOBAL" if expression.args.get("global") else None, 2224 side, 2225 expression.kind, 2226 expression.hint if self.JOIN_HINTS else None, 2227 ) 2228 if op 2229 ) 2230 match_cond = self.sql(expression, "match_condition") 2231 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2232 on_sql = self.sql(expression, "on") 2233 using = expression.args.get("using") 2234 2235 if not on_sql and using: 2236 on_sql = csv(*(self.sql(column) for column in using)) 2237 2238 this = expression.this 2239 this_sql = self.sql(this) 2240 2241 exprs = self.expressions(expression) 2242 if exprs: 2243 this_sql = f"{this_sql},{self.seg(exprs)}" 2244 2245 if on_sql: 2246 on_sql = self.indent(on_sql, skip_first=True) 2247 space = self.seg(" " * self.pad) if self.pretty else " " 2248 if using: 2249 on_sql = f"{space}USING ({on_sql})" 2250 else: 2251 on_sql = f"{space}ON {on_sql}" 2252 elif not op_sql: 2253 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2254 return f" {this_sql}" 2255 2256 return f", {this_sql}" 2257 2258 if op_sql != "STRAIGHT_JOIN": 2259 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2260 2261 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2262 2263 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2264 args = self.expressions(expression, flat=True) 2265 args = f"({args})" if len(args.split(",")) > 1 else args 2266 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2267 2268 def lateral_op(self, expression: exp.Lateral) -> str: 2269 cross_apply = expression.args.get("cross_apply") 2270 2271 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2272 if cross_apply is True: 2273 op = "INNER JOIN " 2274 elif cross_apply is False: 2275 op = "LEFT JOIN " 2276 else: 2277 op = "" 2278 2279 return f"{op}LATERAL" 2280 2281 def lateral_sql(self, expression: exp.Lateral) -> str: 2282 this = self.sql(expression, "this") 2283 2284 if expression.args.get("view"): 2285 alias = expression.args["alias"] 2286 columns = self.expressions(alias, key="columns", flat=True) 2287 table = f" {alias.name}" if alias.name else "" 2288 columns = f" AS {columns}" if columns else "" 2289 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2290 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2291 2292 alias = self.sql(expression, "alias") 2293 alias = f" AS {alias}" if alias else "" 2294 return f"{self.lateral_op(expression)} {this}{alias}" 2295 2296 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2297 this = self.sql(expression, "this") 2298 2299 args = [ 2300 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2301 for e in (expression.args.get(k) for k in ("offset", "expression")) 2302 if e 2303 ] 2304 2305 args_sql = ", ".join(self.sql(e) for e in args) 2306 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2307 expressions = self.expressions(expression, flat=True) 2308 limit_options = self.sql(expression, "limit_options") 2309 expressions = f" BY {expressions}" if expressions else "" 2310 2311 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}" 2312 2313 def offset_sql(self, expression: exp.Offset) -> str: 2314 this = self.sql(expression, "this") 2315 value = expression.expression 2316 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2317 expressions = self.expressions(expression, flat=True) 2318 expressions = f" BY {expressions}" if expressions else "" 2319 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2320 2321 def setitem_sql(self, expression: exp.SetItem) -> str: 2322 kind = self.sql(expression, "kind") 2323 kind = f"{kind} " if kind else "" 2324 this = self.sql(expression, "this") 2325 expressions = self.expressions(expression) 2326 collate = self.sql(expression, "collate") 2327 collate = f" COLLATE {collate}" if collate else "" 2328 global_ = "GLOBAL " if expression.args.get("global") else "" 2329 return f"{global_}{kind}{this}{expressions}{collate}" 2330 2331 def set_sql(self, expression: exp.Set) -> str: 2332 expressions = f" {self.expressions(expression, flat=True)}" 2333 tag = " TAG" if expression.args.get("tag") else "" 2334 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2335 2336 def pragma_sql(self, expression: exp.Pragma) -> str: 2337 return f"PRAGMA {self.sql(expression, 'this')}" 2338 2339 def lock_sql(self, expression: exp.Lock) -> str: 2340 if not self.LOCKING_READS_SUPPORTED: 2341 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2342 return "" 2343 2344 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2345 expressions = self.expressions(expression, flat=True) 2346 expressions = f" OF {expressions}" if expressions else "" 2347 wait = expression.args.get("wait") 2348 2349 if wait is not None: 2350 if isinstance(wait, exp.Literal): 2351 wait = f" WAIT {self.sql(wait)}" 2352 else: 2353 wait = " NOWAIT" if wait else " SKIP LOCKED" 2354 2355 return f"{lock_type}{expressions}{wait or ''}" 2356 2357 def literal_sql(self, expression: exp.Literal) -> str: 2358 text = expression.this or "" 2359 if expression.is_string: 2360 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2361 return text 2362 2363 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2364 if self.dialect.ESCAPED_SEQUENCES: 2365 to_escaped = self.dialect.ESCAPED_SEQUENCES 2366 text = "".join( 2367 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2368 ) 2369 2370 return self._replace_line_breaks(text).replace( 2371 self.dialect.QUOTE_END, self._escaped_quote_end 2372 ) 2373 2374 def loaddata_sql(self, expression: exp.LoadData) -> str: 2375 local = " LOCAL" if expression.args.get("local") else "" 2376 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2377 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2378 this = f" INTO TABLE {self.sql(expression, 'this')}" 2379 partition = self.sql(expression, "partition") 2380 partition = f" {partition}" if partition else "" 2381 input_format = self.sql(expression, "input_format") 2382 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2383 serde = self.sql(expression, "serde") 2384 serde = f" SERDE {serde}" if serde else "" 2385 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2386 2387 def null_sql(self, *_) -> str: 2388 return "NULL" 2389 2390 def boolean_sql(self, expression: exp.Boolean) -> str: 2391 return "TRUE" if expression.this else "FALSE" 2392 2393 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2394 this = self.sql(expression, "this") 2395 this = f"{this} " if this else this 2396 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2397 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2398 2399 def withfill_sql(self, expression: exp.WithFill) -> str: 2400 from_sql = self.sql(expression, "from") 2401 from_sql = f" FROM {from_sql}" if from_sql else "" 2402 to_sql = self.sql(expression, "to") 2403 to_sql = f" TO {to_sql}" if to_sql else "" 2404 step_sql = self.sql(expression, "step") 2405 step_sql = f" STEP {step_sql}" if step_sql else "" 2406 interpolated_values = [ 2407 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2408 if isinstance(e, exp.Alias) 2409 else self.sql(e, "this") 2410 for e in expression.args.get("interpolate") or [] 2411 ] 2412 interpolate = ( 2413 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2414 ) 2415 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2416 2417 def cluster_sql(self, expression: exp.Cluster) -> str: 2418 return self.op_expressions("CLUSTER BY", expression) 2419 2420 def distribute_sql(self, expression: exp.Distribute) -> str: 2421 return self.op_expressions("DISTRIBUTE BY", expression) 2422 2423 def sort_sql(self, expression: exp.Sort) -> str: 2424 return self.op_expressions("SORT BY", expression) 2425 2426 def ordered_sql(self, expression: exp.Ordered) -> str: 2427 desc = expression.args.get("desc") 2428 asc = not desc 2429 2430 nulls_first = expression.args.get("nulls_first") 2431 nulls_last = not nulls_first 2432 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2433 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2434 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2435 2436 this = self.sql(expression, "this") 2437 2438 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2439 nulls_sort_change = "" 2440 if nulls_first and ( 2441 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2442 ): 2443 nulls_sort_change = " NULLS FIRST" 2444 elif ( 2445 nulls_last 2446 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2447 and not nulls_are_last 2448 ): 2449 nulls_sort_change = " NULLS LAST" 2450 2451 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2452 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2453 window = expression.find_ancestor(exp.Window, exp.Select) 2454 if isinstance(window, exp.Window) and window.args.get("spec"): 2455 self.unsupported( 2456 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2457 ) 2458 nulls_sort_change = "" 2459 elif self.NULL_ORDERING_SUPPORTED is False and ( 2460 (asc and nulls_sort_change == " NULLS LAST") 2461 or (desc and nulls_sort_change == " NULLS FIRST") 2462 ): 2463 # BigQuery does not allow these ordering/nulls combinations when used under 2464 # an aggregation func or under a window containing one 2465 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2466 2467 if isinstance(ancestor, exp.Window): 2468 ancestor = ancestor.this 2469 if isinstance(ancestor, exp.AggFunc): 2470 self.unsupported( 2471 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2472 ) 2473 nulls_sort_change = "" 2474 elif self.NULL_ORDERING_SUPPORTED is None: 2475 if expression.this.is_int: 2476 self.unsupported( 2477 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2478 ) 2479 elif not isinstance(expression.this, exp.Rand): 2480 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2481 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2482 nulls_sort_change = "" 2483 2484 with_fill = self.sql(expression, "with_fill") 2485 with_fill = f" {with_fill}" if with_fill else "" 2486 2487 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2488 2489 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2490 window_frame = self.sql(expression, "window_frame") 2491 window_frame = f"{window_frame} " if window_frame else "" 2492 2493 this = self.sql(expression, "this") 2494 2495 return f"{window_frame}{this}" 2496 2497 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2498 partition = self.partition_by_sql(expression) 2499 order = self.sql(expression, "order") 2500 measures = self.expressions(expression, key="measures") 2501 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2502 rows = self.sql(expression, "rows") 2503 rows = self.seg(rows) if rows else "" 2504 after = self.sql(expression, "after") 2505 after = self.seg(after) if after else "" 2506 pattern = self.sql(expression, "pattern") 2507 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2508 definition_sqls = [ 2509 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2510 for definition in expression.args.get("define", []) 2511 ] 2512 definitions = self.expressions(sqls=definition_sqls) 2513 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2514 body = "".join( 2515 ( 2516 partition, 2517 order, 2518 measures, 2519 rows, 2520 after, 2521 pattern, 2522 define, 2523 ) 2524 ) 2525 alias = self.sql(expression, "alias") 2526 alias = f" {alias}" if alias else "" 2527 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2528 2529 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2530 limit = expression.args.get("limit") 2531 2532 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2533 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2534 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2535 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2536 2537 return csv( 2538 *sqls, 2539 *[self.sql(join) for join in expression.args.get("joins") or []], 2540 self.sql(expression, "match"), 2541 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2542 self.sql(expression, "prewhere"), 2543 self.sql(expression, "where"), 2544 self.sql(expression, "connect"), 2545 self.sql(expression, "group"), 2546 self.sql(expression, "having"), 2547 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2548 self.sql(expression, "order"), 2549 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2550 *self.after_limit_modifiers(expression), 2551 self.options_modifier(expression), 2552 sep="", 2553 ) 2554 2555 def options_modifier(self, expression: exp.Expression) -> str: 2556 options = self.expressions(expression, key="options") 2557 return f" {options}" if options else "" 2558 2559 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2560 return "" 2561 2562 def offset_limit_modifiers( 2563 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2564 ) -> t.List[str]: 2565 return [ 2566 self.sql(expression, "offset") if fetch else self.sql(limit), 2567 self.sql(limit) if fetch else self.sql(expression, "offset"), 2568 ] 2569 2570 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2571 locks = self.expressions(expression, key="locks", sep=" ") 2572 locks = f" {locks}" if locks else "" 2573 return [locks, self.sql(expression, "sample")] 2574 2575 def select_sql(self, expression: exp.Select) -> str: 2576 into = expression.args.get("into") 2577 if not self.SUPPORTS_SELECT_INTO and into: 2578 into.pop() 2579 2580 hint = self.sql(expression, "hint") 2581 distinct = self.sql(expression, "distinct") 2582 distinct = f" {distinct}" if distinct else "" 2583 kind = self.sql(expression, "kind") 2584 2585 limit = expression.args.get("limit") 2586 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2587 top = self.limit_sql(limit, top=True) 2588 limit.pop() 2589 else: 2590 top = "" 2591 2592 expressions = self.expressions(expression) 2593 2594 if kind: 2595 if kind in self.SELECT_KINDS: 2596 kind = f" AS {kind}" 2597 else: 2598 if kind == "STRUCT": 2599 expressions = self.expressions( 2600 sqls=[ 2601 self.sql( 2602 exp.Struct( 2603 expressions=[ 2604 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2605 if isinstance(e, exp.Alias) 2606 else e 2607 for e in expression.expressions 2608 ] 2609 ) 2610 ) 2611 ] 2612 ) 2613 kind = "" 2614 2615 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2616 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2617 2618 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2619 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2620 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2621 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2622 sql = self.query_modifiers( 2623 expression, 2624 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2625 self.sql(expression, "into", comment=False), 2626 self.sql(expression, "from", comment=False), 2627 ) 2628 2629 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2630 if expression.args.get("with"): 2631 sql = self.maybe_comment(sql, expression) 2632 expression.pop_comments() 2633 2634 sql = self.prepend_ctes(expression, sql) 2635 2636 if not self.SUPPORTS_SELECT_INTO and into: 2637 if into.args.get("temporary"): 2638 table_kind = " TEMPORARY" 2639 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2640 table_kind = " UNLOGGED" 2641 else: 2642 table_kind = "" 2643 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2644 2645 return sql 2646 2647 def schema_sql(self, expression: exp.Schema) -> str: 2648 this = self.sql(expression, "this") 2649 sql = self.schema_columns_sql(expression) 2650 return f"{this} {sql}" if this and sql else this or sql 2651 2652 def schema_columns_sql(self, expression: exp.Schema) -> str: 2653 if expression.expressions: 2654 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2655 return "" 2656 2657 def star_sql(self, expression: exp.Star) -> str: 2658 except_ = self.expressions(expression, key="except", flat=True) 2659 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2660 replace = self.expressions(expression, key="replace", flat=True) 2661 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2662 rename = self.expressions(expression, key="rename", flat=True) 2663 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2664 return f"*{except_}{replace}{rename}" 2665 2666 def parameter_sql(self, expression: exp.Parameter) -> str: 2667 this = self.sql(expression, "this") 2668 return f"{self.PARAMETER_TOKEN}{this}" 2669 2670 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2671 this = self.sql(expression, "this") 2672 kind = expression.text("kind") 2673 if kind: 2674 kind = f"{kind}." 2675 return f"@@{kind}{this}" 2676 2677 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2678 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2679 2680 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2681 alias = self.sql(expression, "alias") 2682 alias = f"{sep}{alias}" if alias else "" 2683 sample = self.sql(expression, "sample") 2684 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2685 alias = f"{sample}{alias}" 2686 2687 # Set to None so it's not generated again by self.query_modifiers() 2688 expression.set("sample", None) 2689 2690 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2691 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2692 return self.prepend_ctes(expression, sql) 2693 2694 def qualify_sql(self, expression: exp.Qualify) -> str: 2695 this = self.indent(self.sql(expression, "this")) 2696 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2697 2698 def unnest_sql(self, expression: exp.Unnest) -> str: 2699 args = self.expressions(expression, flat=True) 2700 2701 alias = expression.args.get("alias") 2702 offset = expression.args.get("offset") 2703 2704 if self.UNNEST_WITH_ORDINALITY: 2705 if alias and isinstance(offset, exp.Expression): 2706 alias.append("columns", offset) 2707 2708 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2709 columns = alias.columns 2710 alias = self.sql(columns[0]) if columns else "" 2711 else: 2712 alias = self.sql(alias) 2713 2714 alias = f" AS {alias}" if alias else alias 2715 if self.UNNEST_WITH_ORDINALITY: 2716 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2717 else: 2718 if isinstance(offset, exp.Expression): 2719 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2720 elif offset: 2721 suffix = f"{alias} WITH OFFSET" 2722 else: 2723 suffix = alias 2724 2725 return f"UNNEST({args}){suffix}" 2726 2727 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2728 return "" 2729 2730 def where_sql(self, expression: exp.Where) -> str: 2731 this = self.indent(self.sql(expression, "this")) 2732 return f"{self.seg('WHERE')}{self.sep()}{this}" 2733 2734 def window_sql(self, expression: exp.Window) -> str: 2735 this = self.sql(expression, "this") 2736 partition = self.partition_by_sql(expression) 2737 order = expression.args.get("order") 2738 order = self.order_sql(order, flat=True) if order else "" 2739 spec = self.sql(expression, "spec") 2740 alias = self.sql(expression, "alias") 2741 over = self.sql(expression, "over") or "OVER" 2742 2743 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2744 2745 first = expression.args.get("first") 2746 if first is None: 2747 first = "" 2748 else: 2749 first = "FIRST" if first else "LAST" 2750 2751 if not partition and not order and not spec and alias: 2752 return f"{this} {alias}" 2753 2754 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2755 return f"{this} ({args})" 2756 2757 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2758 partition = self.expressions(expression, key="partition_by", flat=True) 2759 return f"PARTITION BY {partition}" if partition else "" 2760 2761 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2762 kind = self.sql(expression, "kind") 2763 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2764 end = ( 2765 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2766 or "CURRENT ROW" 2767 ) 2768 return f"{kind} BETWEEN {start} AND {end}" 2769 2770 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2771 this = self.sql(expression, "this") 2772 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2773 return f"{this} WITHIN GROUP ({expression_sql})" 2774 2775 def between_sql(self, expression: exp.Between) -> str: 2776 this = self.sql(expression, "this") 2777 low = self.sql(expression, "low") 2778 high = self.sql(expression, "high") 2779 return f"{this} BETWEEN {low} AND {high}" 2780 2781 def bracket_offset_expressions( 2782 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2783 ) -> t.List[exp.Expression]: 2784 return apply_index_offset( 2785 expression.this, 2786 expression.expressions, 2787 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2788 ) 2789 2790 def bracket_sql(self, expression: exp.Bracket) -> str: 2791 expressions = self.bracket_offset_expressions(expression) 2792 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2793 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2794 2795 def all_sql(self, expression: exp.All) -> str: 2796 return f"ALL {self.wrap(expression)}" 2797 2798 def any_sql(self, expression: exp.Any) -> str: 2799 this = self.sql(expression, "this") 2800 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2801 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2802 this = self.wrap(this) 2803 return f"ANY{this}" 2804 return f"ANY {this}" 2805 2806 def exists_sql(self, expression: exp.Exists) -> str: 2807 return f"EXISTS{self.wrap(expression)}" 2808 2809 def case_sql(self, expression: exp.Case) -> str: 2810 this = self.sql(expression, "this") 2811 statements = [f"CASE {this}" if this else "CASE"] 2812 2813 for e in expression.args["ifs"]: 2814 statements.append(f"WHEN {self.sql(e, 'this')}") 2815 statements.append(f"THEN {self.sql(e, 'true')}") 2816 2817 default = self.sql(expression, "default") 2818 2819 if default: 2820 statements.append(f"ELSE {default}") 2821 2822 statements.append("END") 2823 2824 if self.pretty and self.too_wide(statements): 2825 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2826 2827 return " ".join(statements) 2828 2829 def constraint_sql(self, expression: exp.Constraint) -> str: 2830 this = self.sql(expression, "this") 2831 expressions = self.expressions(expression, flat=True) 2832 return f"CONSTRAINT {this} {expressions}" 2833 2834 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2835 order = expression.args.get("order") 2836 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2837 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2838 2839 def extract_sql(self, expression: exp.Extract) -> str: 2840 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2841 expression_sql = self.sql(expression, "expression") 2842 return f"EXTRACT({this} FROM {expression_sql})" 2843 2844 def trim_sql(self, expression: exp.Trim) -> str: 2845 trim_type = self.sql(expression, "position") 2846 2847 if trim_type == "LEADING": 2848 func_name = "LTRIM" 2849 elif trim_type == "TRAILING": 2850 func_name = "RTRIM" 2851 else: 2852 func_name = "TRIM" 2853 2854 return self.func(func_name, expression.this, expression.expression) 2855 2856 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2857 args = expression.expressions 2858 if isinstance(expression, exp.ConcatWs): 2859 args = args[1:] # Skip the delimiter 2860 2861 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2862 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2863 2864 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2865 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2866 2867 return args 2868 2869 def concat_sql(self, expression: exp.Concat) -> str: 2870 expressions = self.convert_concat_args(expression) 2871 2872 # Some dialects don't allow a single-argument CONCAT call 2873 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2874 return self.sql(expressions[0]) 2875 2876 return self.func("CONCAT", *expressions) 2877 2878 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2879 return self.func( 2880 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2881 ) 2882 2883 def check_sql(self, expression: exp.Check) -> str: 2884 this = self.sql(expression, key="this") 2885 return f"CHECK ({this})" 2886 2887 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2888 expressions = self.expressions(expression, flat=True) 2889 expressions = f" ({expressions})" if expressions else "" 2890 reference = self.sql(expression, "reference") 2891 reference = f" {reference}" if reference else "" 2892 delete = self.sql(expression, "delete") 2893 delete = f" ON DELETE {delete}" if delete else "" 2894 update = self.sql(expression, "update") 2895 update = f" ON UPDATE {update}" if update else "" 2896 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2897 2898 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2899 expressions = self.expressions(expression, flat=True) 2900 options = self.expressions(expression, key="options", flat=True, sep=" ") 2901 options = f" {options}" if options else "" 2902 return f"PRIMARY KEY ({expressions}){options}" 2903 2904 def if_sql(self, expression: exp.If) -> str: 2905 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2906 2907 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2908 modifier = expression.args.get("modifier") 2909 modifier = f" {modifier}" if modifier else "" 2910 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2911 2912 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2913 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2914 2915 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2916 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2917 2918 if expression.args.get("escape"): 2919 path = self.escape_str(path) 2920 2921 if self.QUOTE_JSON_PATH: 2922 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2923 2924 return path 2925 2926 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2927 if isinstance(expression, exp.JSONPathPart): 2928 transform = self.TRANSFORMS.get(expression.__class__) 2929 if not callable(transform): 2930 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2931 return "" 2932 2933 return transform(self, expression) 2934 2935 if isinstance(expression, int): 2936 return str(expression) 2937 2938 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2939 escaped = expression.replace("'", "\\'") 2940 escaped = f"\\'{expression}\\'" 2941 else: 2942 escaped = expression.replace('"', '\\"') 2943 escaped = f'"{escaped}"' 2944 2945 return escaped 2946 2947 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2948 return f"{self.sql(expression, 'this')} FORMAT JSON" 2949 2950 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2951 null_handling = expression.args.get("null_handling") 2952 null_handling = f" {null_handling}" if null_handling else "" 2953 2954 unique_keys = expression.args.get("unique_keys") 2955 if unique_keys is not None: 2956 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2957 else: 2958 unique_keys = "" 2959 2960 return_type = self.sql(expression, "return_type") 2961 return_type = f" RETURNING {return_type}" if return_type else "" 2962 encoding = self.sql(expression, "encoding") 2963 encoding = f" ENCODING {encoding}" if encoding else "" 2964 2965 return self.func( 2966 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2967 *expression.expressions, 2968 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2969 ) 2970 2971 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2972 return self.jsonobject_sql(expression) 2973 2974 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2975 null_handling = expression.args.get("null_handling") 2976 null_handling = f" {null_handling}" if null_handling else "" 2977 return_type = self.sql(expression, "return_type") 2978 return_type = f" RETURNING {return_type}" if return_type else "" 2979 strict = " STRICT" if expression.args.get("strict") else "" 2980 return self.func( 2981 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2982 ) 2983 2984 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2985 this = self.sql(expression, "this") 2986 order = self.sql(expression, "order") 2987 null_handling = expression.args.get("null_handling") 2988 null_handling = f" {null_handling}" if null_handling else "" 2989 return_type = self.sql(expression, "return_type") 2990 return_type = f" RETURNING {return_type}" if return_type else "" 2991 strict = " STRICT" if expression.args.get("strict") else "" 2992 return self.func( 2993 "JSON_ARRAYAGG", 2994 this, 2995 suffix=f"{order}{null_handling}{return_type}{strict})", 2996 ) 2997 2998 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2999 path = self.sql(expression, "path") 3000 path = f" PATH {path}" if path else "" 3001 nested_schema = self.sql(expression, "nested_schema") 3002 3003 if nested_schema: 3004 return f"NESTED{path} {nested_schema}" 3005 3006 this = self.sql(expression, "this") 3007 kind = self.sql(expression, "kind") 3008 kind = f" {kind}" if kind else "" 3009 return f"{this}{kind}{path}" 3010 3011 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 3012 return self.func("COLUMNS", *expression.expressions) 3013 3014 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3015 this = self.sql(expression, "this") 3016 path = self.sql(expression, "path") 3017 path = f", {path}" if path else "" 3018 error_handling = expression.args.get("error_handling") 3019 error_handling = f" {error_handling}" if error_handling else "" 3020 empty_handling = expression.args.get("empty_handling") 3021 empty_handling = f" {empty_handling}" if empty_handling else "" 3022 schema = self.sql(expression, "schema") 3023 return self.func( 3024 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3025 ) 3026 3027 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3028 this = self.sql(expression, "this") 3029 kind = self.sql(expression, "kind") 3030 path = self.sql(expression, "path") 3031 path = f" {path}" if path else "" 3032 as_json = " AS JSON" if expression.args.get("as_json") else "" 3033 return f"{this} {kind}{path}{as_json}" 3034 3035 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3036 this = self.sql(expression, "this") 3037 path = self.sql(expression, "path") 3038 path = f", {path}" if path else "" 3039 expressions = self.expressions(expression) 3040 with_ = ( 3041 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3042 if expressions 3043 else "" 3044 ) 3045 return f"OPENJSON({this}{path}){with_}" 3046 3047 def in_sql(self, expression: exp.In) -> str: 3048 query = expression.args.get("query") 3049 unnest = expression.args.get("unnest") 3050 field = expression.args.get("field") 3051 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3052 3053 if query: 3054 in_sql = self.sql(query) 3055 elif unnest: 3056 in_sql = self.in_unnest_op(unnest) 3057 elif field: 3058 in_sql = self.sql(field) 3059 else: 3060 in_sql = f"({self.expressions(expression, flat=True)})" 3061 3062 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3063 3064 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3065 return f"(SELECT {self.sql(unnest)})" 3066 3067 def interval_sql(self, expression: exp.Interval) -> str: 3068 unit = self.sql(expression, "unit") 3069 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3070 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3071 unit = f" {unit}" if unit else "" 3072 3073 if self.SINGLE_STRING_INTERVAL: 3074 this = expression.this.name if expression.this else "" 3075 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3076 3077 this = self.sql(expression, "this") 3078 if this: 3079 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3080 this = f" {this}" if unwrapped else f" ({this})" 3081 3082 return f"INTERVAL{this}{unit}" 3083 3084 def return_sql(self, expression: exp.Return) -> str: 3085 return f"RETURN {self.sql(expression, 'this')}" 3086 3087 def reference_sql(self, expression: exp.Reference) -> str: 3088 this = self.sql(expression, "this") 3089 expressions = self.expressions(expression, flat=True) 3090 expressions = f"({expressions})" if expressions else "" 3091 options = self.expressions(expression, key="options", flat=True, sep=" ") 3092 options = f" {options}" if options else "" 3093 return f"REFERENCES {this}{expressions}{options}" 3094 3095 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3096 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3097 parent = expression.parent 3098 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3099 return self.func( 3100 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3101 ) 3102 3103 def paren_sql(self, expression: exp.Paren) -> str: 3104 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3105 return f"({sql}{self.seg(')', sep='')}" 3106 3107 def neg_sql(self, expression: exp.Neg) -> str: 3108 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3109 this_sql = self.sql(expression, "this") 3110 sep = " " if this_sql[0] == "-" else "" 3111 return f"-{sep}{this_sql}" 3112 3113 def not_sql(self, expression: exp.Not) -> str: 3114 return f"NOT {self.sql(expression, 'this')}" 3115 3116 def alias_sql(self, expression: exp.Alias) -> str: 3117 alias = self.sql(expression, "alias") 3118 alias = f" AS {alias}" if alias else "" 3119 return f"{self.sql(expression, 'this')}{alias}" 3120 3121 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3122 alias = expression.args["alias"] 3123 3124 parent = expression.parent 3125 pivot = parent and parent.parent 3126 3127 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3128 identifier_alias = isinstance(alias, exp.Identifier) 3129 literal_alias = isinstance(alias, exp.Literal) 3130 3131 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3132 alias.replace(exp.Literal.string(alias.output_name)) 3133 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3134 alias.replace(exp.to_identifier(alias.output_name)) 3135 3136 return self.alias_sql(expression) 3137 3138 def aliases_sql(self, expression: exp.Aliases) -> str: 3139 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3140 3141 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3142 this = self.sql(expression, "this") 3143 index = self.sql(expression, "expression") 3144 return f"{this} AT {index}" 3145 3146 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3147 this = self.sql(expression, "this") 3148 zone = self.sql(expression, "zone") 3149 return f"{this} AT TIME ZONE {zone}" 3150 3151 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3152 this = self.sql(expression, "this") 3153 zone = self.sql(expression, "zone") 3154 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3155 3156 def add_sql(self, expression: exp.Add) -> str: 3157 return self.binary(expression, "+") 3158 3159 def and_sql( 3160 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3161 ) -> str: 3162 return self.connector_sql(expression, "AND", stack) 3163 3164 def or_sql( 3165 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3166 ) -> str: 3167 return self.connector_sql(expression, "OR", stack) 3168 3169 def xor_sql( 3170 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3171 ) -> str: 3172 return self.connector_sql(expression, "XOR", stack) 3173 3174 def connector_sql( 3175 self, 3176 expression: exp.Connector, 3177 op: str, 3178 stack: t.Optional[t.List[str | exp.Expression]] = None, 3179 ) -> str: 3180 if stack is not None: 3181 if expression.expressions: 3182 stack.append(self.expressions(expression, sep=f" {op} ")) 3183 else: 3184 stack.append(expression.right) 3185 if expression.comments and self.comments: 3186 for comment in expression.comments: 3187 if comment: 3188 op += f" /*{self.pad_comment(comment)}*/" 3189 stack.extend((op, expression.left)) 3190 return op 3191 3192 stack = [expression] 3193 sqls: t.List[str] = [] 3194 ops = set() 3195 3196 while stack: 3197 node = stack.pop() 3198 if isinstance(node, exp.Connector): 3199 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3200 else: 3201 sql = self.sql(node) 3202 if sqls and sqls[-1] in ops: 3203 sqls[-1] += f" {sql}" 3204 else: 3205 sqls.append(sql) 3206 3207 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3208 return sep.join(sqls) 3209 3210 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3211 return self.binary(expression, "&") 3212 3213 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3214 return self.binary(expression, "<<") 3215 3216 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3217 return f"~{self.sql(expression, 'this')}" 3218 3219 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3220 return self.binary(expression, "|") 3221 3222 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3223 return self.binary(expression, ">>") 3224 3225 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3226 return self.binary(expression, "^") 3227 3228 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3229 format_sql = self.sql(expression, "format") 3230 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3231 to_sql = self.sql(expression, "to") 3232 to_sql = f" {to_sql}" if to_sql else "" 3233 action = self.sql(expression, "action") 3234 action = f" {action}" if action else "" 3235 default = self.sql(expression, "default") 3236 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3237 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})" 3238 3239 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3240 zone = self.sql(expression, "this") 3241 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3242 3243 def collate_sql(self, expression: exp.Collate) -> str: 3244 if self.COLLATE_IS_FUNC: 3245 return self.function_fallback_sql(expression) 3246 return self.binary(expression, "COLLATE") 3247 3248 def command_sql(self, expression: exp.Command) -> str: 3249 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3250 3251 def comment_sql(self, expression: exp.Comment) -> str: 3252 this = self.sql(expression, "this") 3253 kind = expression.args["kind"] 3254 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3255 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3256 expression_sql = self.sql(expression, "expression") 3257 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3258 3259 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3260 this = self.sql(expression, "this") 3261 delete = " DELETE" if expression.args.get("delete") else "" 3262 recompress = self.sql(expression, "recompress") 3263 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3264 to_disk = self.sql(expression, "to_disk") 3265 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3266 to_volume = self.sql(expression, "to_volume") 3267 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3268 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3269 3270 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3271 where = self.sql(expression, "where") 3272 group = self.sql(expression, "group") 3273 aggregates = self.expressions(expression, key="aggregates") 3274 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3275 3276 if not (where or group or aggregates) and len(expression.expressions) == 1: 3277 return f"TTL {self.expressions(expression, flat=True)}" 3278 3279 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3280 3281 def transaction_sql(self, expression: exp.Transaction) -> str: 3282 return "BEGIN" 3283 3284 def commit_sql(self, expression: exp.Commit) -> str: 3285 chain = expression.args.get("chain") 3286 if chain is not None: 3287 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3288 3289 return f"COMMIT{chain or ''}" 3290 3291 def rollback_sql(self, expression: exp.Rollback) -> str: 3292 savepoint = expression.args.get("savepoint") 3293 savepoint = f" TO {savepoint}" if savepoint else "" 3294 return f"ROLLBACK{savepoint}" 3295 3296 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3297 this = self.sql(expression, "this") 3298 3299 dtype = self.sql(expression, "dtype") 3300 if dtype: 3301 collate = self.sql(expression, "collate") 3302 collate = f" COLLATE {collate}" if collate else "" 3303 using = self.sql(expression, "using") 3304 using = f" USING {using}" if using else "" 3305 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3306 3307 default = self.sql(expression, "default") 3308 if default: 3309 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3310 3311 comment = self.sql(expression, "comment") 3312 if comment: 3313 return f"ALTER COLUMN {this} COMMENT {comment}" 3314 3315 visible = expression.args.get("visible") 3316 if visible: 3317 return f"ALTER COLUMN {this} SET {visible}" 3318 3319 allow_null = expression.args.get("allow_null") 3320 drop = expression.args.get("drop") 3321 3322 if not drop and not allow_null: 3323 self.unsupported("Unsupported ALTER COLUMN syntax") 3324 3325 if allow_null is not None: 3326 keyword = "DROP" if drop else "SET" 3327 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3328 3329 return f"ALTER COLUMN {this} DROP DEFAULT" 3330 3331 def alterindex_sql(self, expression: exp.AlterIndex) -> str: 3332 this = self.sql(expression, "this") 3333 3334 visible = expression.args.get("visible") 3335 visible_sql = "VISIBLE" if visible else "INVISIBLE" 3336 3337 return f"ALTER INDEX {this} {visible_sql}" 3338 3339 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3340 this = self.sql(expression, "this") 3341 if not isinstance(expression.this, exp.Var): 3342 this = f"KEY DISTKEY {this}" 3343 return f"ALTER DISTSTYLE {this}" 3344 3345 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3346 compound = " COMPOUND" if expression.args.get("compound") else "" 3347 this = self.sql(expression, "this") 3348 expressions = self.expressions(expression, flat=True) 3349 expressions = f"({expressions})" if expressions else "" 3350 return f"ALTER{compound} SORTKEY {this or expressions}" 3351 3352 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3353 if not self.RENAME_TABLE_WITH_DB: 3354 # Remove db from tables 3355 expression = expression.transform( 3356 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3357 ).assert_is(exp.AlterRename) 3358 this = self.sql(expression, "this") 3359 return f"RENAME TO {this}" 3360 3361 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3362 exists = " IF EXISTS" if expression.args.get("exists") else "" 3363 old_column = self.sql(expression, "this") 3364 new_column = self.sql(expression, "to") 3365 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3366 3367 def alterset_sql(self, expression: exp.AlterSet) -> str: 3368 exprs = self.expressions(expression, flat=True) 3369 return f"SET {exprs}" 3370 3371 def alter_sql(self, expression: exp.Alter) -> str: 3372 actions = expression.args["actions"] 3373 3374 if isinstance(actions[0], exp.ColumnDef): 3375 actions = self.add_column_sql(expression) 3376 elif isinstance(actions[0], exp.Schema): 3377 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3378 elif isinstance(actions[0], exp.Delete): 3379 actions = self.expressions(expression, key="actions", flat=True) 3380 elif isinstance(actions[0], exp.Query): 3381 actions = "AS " + self.expressions(expression, key="actions") 3382 else: 3383 actions = self.expressions(expression, key="actions", flat=True) 3384 3385 exists = " IF EXISTS" if expression.args.get("exists") else "" 3386 on_cluster = self.sql(expression, "cluster") 3387 on_cluster = f" {on_cluster}" if on_cluster else "" 3388 only = " ONLY" if expression.args.get("only") else "" 3389 options = self.expressions(expression, key="options") 3390 options = f", {options}" if options else "" 3391 kind = self.sql(expression, "kind") 3392 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3393 3394 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3395 3396 def add_column_sql(self, expression: exp.Alter) -> str: 3397 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3398 return self.expressions( 3399 expression, 3400 key="actions", 3401 prefix="ADD COLUMN ", 3402 skip_first=True, 3403 ) 3404 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3405 3406 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3407 expressions = self.expressions(expression) 3408 exists = " IF EXISTS " if expression.args.get("exists") else " " 3409 return f"DROP{exists}{expressions}" 3410 3411 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3412 return f"ADD {self.expressions(expression)}" 3413 3414 def distinct_sql(self, expression: exp.Distinct) -> str: 3415 this = self.expressions(expression, flat=True) 3416 3417 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3418 case = exp.case() 3419 for arg in expression.expressions: 3420 case = case.when(arg.is_(exp.null()), exp.null()) 3421 this = self.sql(case.else_(f"({this})")) 3422 3423 this = f" {this}" if this else "" 3424 3425 on = self.sql(expression, "on") 3426 on = f" ON {on}" if on else "" 3427 return f"DISTINCT{this}{on}" 3428 3429 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3430 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3431 3432 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3433 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3434 3435 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3436 this_sql = self.sql(expression, "this") 3437 expression_sql = self.sql(expression, "expression") 3438 kind = "MAX" if expression.args.get("max") else "MIN" 3439 return f"{this_sql} HAVING {kind} {expression_sql}" 3440 3441 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3442 return self.sql( 3443 exp.Cast( 3444 this=exp.Div(this=expression.this, expression=expression.expression), 3445 to=exp.DataType(this=exp.DataType.Type.INT), 3446 ) 3447 ) 3448 3449 def dpipe_sql(self, expression: exp.DPipe) -> str: 3450 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3451 return self.func( 3452 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3453 ) 3454 return self.binary(expression, "||") 3455 3456 def div_sql(self, expression: exp.Div) -> str: 3457 l, r = expression.left, expression.right 3458 3459 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3460 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3461 3462 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3463 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3464 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3465 3466 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3467 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3468 return self.sql( 3469 exp.cast( 3470 l / r, 3471 to=exp.DataType.Type.BIGINT, 3472 ) 3473 ) 3474 3475 return self.binary(expression, "/") 3476 3477 def safedivide_sql(self, expression: exp.SafeDivide) -> str: 3478 n = exp._wrap(expression.this, exp.Binary) 3479 d = exp._wrap(expression.expression, exp.Binary) 3480 return self.sql(exp.If(this=d.neq(0), true=n / d, false=exp.Null())) 3481 3482 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3483 return self.binary(expression, "OVERLAPS") 3484 3485 def distance_sql(self, expression: exp.Distance) -> str: 3486 return self.binary(expression, "<->") 3487 3488 def dot_sql(self, expression: exp.Dot) -> str: 3489 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3490 3491 def eq_sql(self, expression: exp.EQ) -> str: 3492 return self.binary(expression, "=") 3493 3494 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3495 return self.binary(expression, ":=") 3496 3497 def escape_sql(self, expression: exp.Escape) -> str: 3498 return self.binary(expression, "ESCAPE") 3499 3500 def glob_sql(self, expression: exp.Glob) -> str: 3501 return self.binary(expression, "GLOB") 3502 3503 def gt_sql(self, expression: exp.GT) -> str: 3504 return self.binary(expression, ">") 3505 3506 def gte_sql(self, expression: exp.GTE) -> str: 3507 return self.binary(expression, ">=") 3508 3509 def ilike_sql(self, expression: exp.ILike) -> str: 3510 return self.binary(expression, "ILIKE") 3511 3512 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3513 return self.binary(expression, "ILIKE ANY") 3514 3515 def is_sql(self, expression: exp.Is) -> str: 3516 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3517 return self.sql( 3518 expression.this if expression.expression.this else exp.not_(expression.this) 3519 ) 3520 return self.binary(expression, "IS") 3521 3522 def like_sql(self, expression: exp.Like) -> str: 3523 return self.binary(expression, "LIKE") 3524 3525 def likeany_sql(self, expression: exp.LikeAny) -> str: 3526 return self.binary(expression, "LIKE ANY") 3527 3528 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3529 return self.binary(expression, "SIMILAR TO") 3530 3531 def lt_sql(self, expression: exp.LT) -> str: 3532 return self.binary(expression, "<") 3533 3534 def lte_sql(self, expression: exp.LTE) -> str: 3535 return self.binary(expression, "<=") 3536 3537 def mod_sql(self, expression: exp.Mod) -> str: 3538 return self.binary(expression, "%") 3539 3540 def mul_sql(self, expression: exp.Mul) -> str: 3541 return self.binary(expression, "*") 3542 3543 def neq_sql(self, expression: exp.NEQ) -> str: 3544 return self.binary(expression, "<>") 3545 3546 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3547 return self.binary(expression, "IS NOT DISTINCT FROM") 3548 3549 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3550 return self.binary(expression, "IS DISTINCT FROM") 3551 3552 def slice_sql(self, expression: exp.Slice) -> str: 3553 return self.binary(expression, ":") 3554 3555 def sub_sql(self, expression: exp.Sub) -> str: 3556 return self.binary(expression, "-") 3557 3558 def trycast_sql(self, expression: exp.TryCast) -> str: 3559 return self.cast_sql(expression, safe_prefix="TRY_") 3560 3561 def jsoncast_sql(self, expression: exp.JSONCast) -> str: 3562 return self.cast_sql(expression) 3563 3564 def try_sql(self, expression: exp.Try) -> str: 3565 if not self.TRY_SUPPORTED: 3566 self.unsupported("Unsupported TRY function") 3567 return self.sql(expression, "this") 3568 3569 return self.func("TRY", expression.this) 3570 3571 def log_sql(self, expression: exp.Log) -> str: 3572 this = expression.this 3573 expr = expression.expression 3574 3575 if self.dialect.LOG_BASE_FIRST is False: 3576 this, expr = expr, this 3577 elif self.dialect.LOG_BASE_FIRST is None and expr: 3578 if this.name in ("2", "10"): 3579 return self.func(f"LOG{this.name}", expr) 3580 3581 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3582 3583 return self.func("LOG", this, expr) 3584 3585 def use_sql(self, expression: exp.Use) -> str: 3586 kind = self.sql(expression, "kind") 3587 kind = f" {kind}" if kind else "" 3588 this = self.sql(expression, "this") or self.expressions(expression, flat=True) 3589 this = f" {this}" if this else "" 3590 return f"USE{kind}{this}" 3591 3592 def binary(self, expression: exp.Binary, op: str) -> str: 3593 sqls: t.List[str] = [] 3594 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3595 binary_type = type(expression) 3596 3597 while stack: 3598 node = stack.pop() 3599 3600 if type(node) is binary_type: 3601 op_func = node.args.get("operator") 3602 if op_func: 3603 op = f"OPERATOR({self.sql(op_func)})" 3604 3605 stack.append(node.right) 3606 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3607 stack.append(node.left) 3608 else: 3609 sqls.append(self.sql(node)) 3610 3611 return "".join(sqls) 3612 3613 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3614 to_clause = self.sql(expression, "to") 3615 if to_clause: 3616 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3617 3618 return self.function_fallback_sql(expression) 3619 3620 def function_fallback_sql(self, expression: exp.Func) -> str: 3621 args = [] 3622 3623 for key in expression.arg_types: 3624 arg_value = expression.args.get(key) 3625 3626 if isinstance(arg_value, list): 3627 for value in arg_value: 3628 args.append(value) 3629 elif arg_value is not None: 3630 args.append(arg_value) 3631 3632 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3633 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3634 else: 3635 name = expression.sql_name() 3636 3637 return self.func(name, *args) 3638 3639 def func( 3640 self, 3641 name: str, 3642 *args: t.Optional[exp.Expression | str], 3643 prefix: str = "(", 3644 suffix: str = ")", 3645 normalize: bool = True, 3646 ) -> str: 3647 name = self.normalize_func(name) if normalize else name 3648 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3649 3650 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3651 arg_sqls = tuple( 3652 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3653 ) 3654 if self.pretty and self.too_wide(arg_sqls): 3655 return self.indent( 3656 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3657 ) 3658 return sep.join(arg_sqls) 3659 3660 def too_wide(self, args: t.Iterable) -> bool: 3661 return sum(len(arg) for arg in args) > self.max_text_width 3662 3663 def format_time( 3664 self, 3665 expression: exp.Expression, 3666 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3667 inverse_time_trie: t.Optional[t.Dict] = None, 3668 ) -> t.Optional[str]: 3669 return format_time( 3670 self.sql(expression, "format"), 3671 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3672 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3673 ) 3674 3675 def expressions( 3676 self, 3677 expression: t.Optional[exp.Expression] = None, 3678 key: t.Optional[str] = None, 3679 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3680 flat: bool = False, 3681 indent: bool = True, 3682 skip_first: bool = False, 3683 skip_last: bool = False, 3684 sep: str = ", ", 3685 prefix: str = "", 3686 dynamic: bool = False, 3687 new_line: bool = False, 3688 ) -> str: 3689 expressions = expression.args.get(key or "expressions") if expression else sqls 3690 3691 if not expressions: 3692 return "" 3693 3694 if flat: 3695 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3696 3697 num_sqls = len(expressions) 3698 result_sqls = [] 3699 3700 for i, e in enumerate(expressions): 3701 sql = self.sql(e, comment=False) 3702 if not sql: 3703 continue 3704 3705 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3706 3707 if self.pretty: 3708 if self.leading_comma: 3709 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3710 else: 3711 result_sqls.append( 3712 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3713 ) 3714 else: 3715 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3716 3717 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3718 if new_line: 3719 result_sqls.insert(0, "") 3720 result_sqls.append("") 3721 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3722 else: 3723 result_sql = "".join(result_sqls) 3724 3725 return ( 3726 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3727 if indent 3728 else result_sql 3729 ) 3730 3731 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3732 flat = flat or isinstance(expression.parent, exp.Properties) 3733 expressions_sql = self.expressions(expression, flat=flat) 3734 if flat: 3735 return f"{op} {expressions_sql}" 3736 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3737 3738 def naked_property(self, expression: exp.Property) -> str: 3739 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3740 if not property_name: 3741 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3742 return f"{property_name} {self.sql(expression, 'this')}" 3743 3744 def tag_sql(self, expression: exp.Tag) -> str: 3745 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3746 3747 def token_sql(self, token_type: TokenType) -> str: 3748 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3749 3750 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3751 this = self.sql(expression, "this") 3752 expressions = self.no_identify(self.expressions, expression) 3753 expressions = ( 3754 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3755 ) 3756 return f"{this}{expressions}" if expressions.strip() != "" else this 3757 3758 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3759 this = self.sql(expression, "this") 3760 expressions = self.expressions(expression, flat=True) 3761 return f"{this}({expressions})" 3762 3763 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3764 return self.binary(expression, "=>") 3765 3766 def when_sql(self, expression: exp.When) -> str: 3767 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3768 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3769 condition = self.sql(expression, "condition") 3770 condition = f" AND {condition}" if condition else "" 3771 3772 then_expression = expression.args.get("then") 3773 if isinstance(then_expression, exp.Insert): 3774 this = self.sql(then_expression, "this") 3775 this = f"INSERT {this}" if this else "INSERT" 3776 then = self.sql(then_expression, "expression") 3777 then = f"{this} VALUES {then}" if then else this 3778 elif isinstance(then_expression, exp.Update): 3779 if isinstance(then_expression.args.get("expressions"), exp.Star): 3780 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3781 else: 3782 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3783 else: 3784 then = self.sql(then_expression) 3785 return f"WHEN {matched}{source}{condition} THEN {then}" 3786 3787 def whens_sql(self, expression: exp.Whens) -> str: 3788 return self.expressions(expression, sep=" ", indent=False) 3789 3790 def merge_sql(self, expression: exp.Merge) -> str: 3791 table = expression.this 3792 table_alias = "" 3793 3794 hints = table.args.get("hints") 3795 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3796 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3797 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3798 3799 this = self.sql(table) 3800 using = f"USING {self.sql(expression, 'using')}" 3801 on = f"ON {self.sql(expression, 'on')}" 3802 whens = self.sql(expression, "whens") 3803 3804 returning = self.sql(expression, "returning") 3805 if returning: 3806 whens = f"{whens}{returning}" 3807 3808 sep = self.sep() 3809 3810 return self.prepend_ctes( 3811 expression, 3812 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3813 ) 3814 3815 @unsupported_args("format") 3816 def tochar_sql(self, expression: exp.ToChar) -> str: 3817 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3818 3819 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3820 if not self.SUPPORTS_TO_NUMBER: 3821 self.unsupported("Unsupported TO_NUMBER function") 3822 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3823 3824 fmt = expression.args.get("format") 3825 if not fmt: 3826 self.unsupported("Conversion format is required for TO_NUMBER") 3827 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3828 3829 return self.func("TO_NUMBER", expression.this, fmt) 3830 3831 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3832 this = self.sql(expression, "this") 3833 kind = self.sql(expression, "kind") 3834 settings_sql = self.expressions(expression, key="settings", sep=" ") 3835 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3836 return f"{this}({kind}{args})" 3837 3838 def dictrange_sql(self, expression: exp.DictRange) -> str: 3839 this = self.sql(expression, "this") 3840 max = self.sql(expression, "max") 3841 min = self.sql(expression, "min") 3842 return f"{this}(MIN {min} MAX {max})" 3843 3844 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3845 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3846 3847 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3848 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3849 3850 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3851 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3852 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3853 3854 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3855 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3856 expressions = self.expressions(expression, flat=True) 3857 expressions = f" {self.wrap(expressions)}" if expressions else "" 3858 buckets = self.sql(expression, "buckets") 3859 kind = self.sql(expression, "kind") 3860 buckets = f" BUCKETS {buckets}" if buckets else "" 3861 order = self.sql(expression, "order") 3862 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3863 3864 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3865 return "" 3866 3867 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3868 expressions = self.expressions(expression, key="expressions", flat=True) 3869 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3870 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3871 buckets = self.sql(expression, "buckets") 3872 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3873 3874 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3875 this = self.sql(expression, "this") 3876 having = self.sql(expression, "having") 3877 3878 if having: 3879 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3880 3881 return self.func("ANY_VALUE", this) 3882 3883 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3884 transform = self.func("TRANSFORM", *expression.expressions) 3885 row_format_before = self.sql(expression, "row_format_before") 3886 row_format_before = f" {row_format_before}" if row_format_before else "" 3887 record_writer = self.sql(expression, "record_writer") 3888 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3889 using = f" USING {self.sql(expression, 'command_script')}" 3890 schema = self.sql(expression, "schema") 3891 schema = f" AS {schema}" if schema else "" 3892 row_format_after = self.sql(expression, "row_format_after") 3893 row_format_after = f" {row_format_after}" if row_format_after else "" 3894 record_reader = self.sql(expression, "record_reader") 3895 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3896 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3897 3898 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3899 key_block_size = self.sql(expression, "key_block_size") 3900 if key_block_size: 3901 return f"KEY_BLOCK_SIZE = {key_block_size}" 3902 3903 using = self.sql(expression, "using") 3904 if using: 3905 return f"USING {using}" 3906 3907 parser = self.sql(expression, "parser") 3908 if parser: 3909 return f"WITH PARSER {parser}" 3910 3911 comment = self.sql(expression, "comment") 3912 if comment: 3913 return f"COMMENT {comment}" 3914 3915 visible = expression.args.get("visible") 3916 if visible is not None: 3917 return "VISIBLE" if visible else "INVISIBLE" 3918 3919 engine_attr = self.sql(expression, "engine_attr") 3920 if engine_attr: 3921 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3922 3923 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3924 if secondary_engine_attr: 3925 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3926 3927 self.unsupported("Unsupported index constraint option.") 3928 return "" 3929 3930 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3931 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3932 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3933 3934 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3935 kind = self.sql(expression, "kind") 3936 kind = f"{kind} INDEX" if kind else "INDEX" 3937 this = self.sql(expression, "this") 3938 this = f" {this}" if this else "" 3939 index_type = self.sql(expression, "index_type") 3940 index_type = f" USING {index_type}" if index_type else "" 3941 expressions = self.expressions(expression, flat=True) 3942 expressions = f" ({expressions})" if expressions else "" 3943 options = self.expressions(expression, key="options", sep=" ") 3944 options = f" {options}" if options else "" 3945 return f"{kind}{this}{index_type}{expressions}{options}" 3946 3947 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3948 if self.NVL2_SUPPORTED: 3949 return self.function_fallback_sql(expression) 3950 3951 case = exp.Case().when( 3952 expression.this.is_(exp.null()).not_(copy=False), 3953 expression.args["true"], 3954 copy=False, 3955 ) 3956 else_cond = expression.args.get("false") 3957 if else_cond: 3958 case.else_(else_cond, copy=False) 3959 3960 return self.sql(case) 3961 3962 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3963 this = self.sql(expression, "this") 3964 expr = self.sql(expression, "expression") 3965 iterator = self.sql(expression, "iterator") 3966 condition = self.sql(expression, "condition") 3967 condition = f" IF {condition}" if condition else "" 3968 return f"{this} FOR {expr} IN {iterator}{condition}" 3969 3970 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3971 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3972 3973 def opclass_sql(self, expression: exp.Opclass) -> str: 3974 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3975 3976 def predict_sql(self, expression: exp.Predict) -> str: 3977 model = self.sql(expression, "this") 3978 model = f"MODEL {model}" 3979 table = self.sql(expression, "expression") 3980 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3981 parameters = self.sql(expression, "params_struct") 3982 return self.func("PREDICT", model, table, parameters or None) 3983 3984 def forin_sql(self, expression: exp.ForIn) -> str: 3985 this = self.sql(expression, "this") 3986 expression_sql = self.sql(expression, "expression") 3987 return f"FOR {this} DO {expression_sql}" 3988 3989 def refresh_sql(self, expression: exp.Refresh) -> str: 3990 this = self.sql(expression, "this") 3991 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3992 return f"REFRESH {table}{this}" 3993 3994 def toarray_sql(self, expression: exp.ToArray) -> str: 3995 arg = expression.this 3996 if not arg.type: 3997 from sqlglot.optimizer.annotate_types import annotate_types 3998 3999 arg = annotate_types(arg) 4000 4001 if arg.is_type(exp.DataType.Type.ARRAY): 4002 return self.sql(arg) 4003 4004 cond_for_null = arg.is_(exp.null()) 4005 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 4006 4007 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4008 this = expression.this 4009 time_format = self.format_time(expression) 4010 4011 if time_format: 4012 return self.sql( 4013 exp.cast( 4014 exp.StrToTime(this=this, format=expression.args["format"]), 4015 exp.DataType.Type.TIME, 4016 ) 4017 ) 4018 4019 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4020 return self.sql(this) 4021 4022 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 4023 4024 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4025 this = expression.this 4026 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4027 return self.sql(this) 4028 4029 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 4030 4031 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4032 this = expression.this 4033 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4034 return self.sql(this) 4035 4036 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 4037 4038 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4039 this = expression.this 4040 time_format = self.format_time(expression) 4041 4042 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4043 return self.sql( 4044 exp.cast( 4045 exp.StrToTime(this=this, format=expression.args["format"]), 4046 exp.DataType.Type.DATE, 4047 ) 4048 ) 4049 4050 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4051 return self.sql(this) 4052 4053 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 4054 4055 def unixdate_sql(self, expression: exp.UnixDate) -> str: 4056 return self.sql( 4057 exp.func( 4058 "DATEDIFF", 4059 expression.this, 4060 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 4061 "day", 4062 ) 4063 ) 4064 4065 def lastday_sql(self, expression: exp.LastDay) -> str: 4066 if self.LAST_DAY_SUPPORTS_DATE_PART: 4067 return self.function_fallback_sql(expression) 4068 4069 unit = expression.text("unit") 4070 if unit and unit != "MONTH": 4071 self.unsupported("Date parts are not supported in LAST_DAY.") 4072 4073 return self.func("LAST_DAY", expression.this) 4074 4075 def dateadd_sql(self, expression: exp.DateAdd) -> str: 4076 from sqlglot.dialects.dialect import unit_to_str 4077 4078 return self.func( 4079 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 4080 ) 4081 4082 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4083 if self.CAN_IMPLEMENT_ARRAY_ANY: 4084 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4085 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4086 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4087 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4088 4089 from sqlglot.dialects import Dialect 4090 4091 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4092 if self.dialect.__class__ != Dialect: 4093 self.unsupported("ARRAY_ANY is unsupported") 4094 4095 return self.function_fallback_sql(expression) 4096 4097 def struct_sql(self, expression: exp.Struct) -> str: 4098 expression.set( 4099 "expressions", 4100 [ 4101 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4102 if isinstance(e, exp.PropertyEQ) 4103 else e 4104 for e in expression.expressions 4105 ], 4106 ) 4107 4108 return self.function_fallback_sql(expression) 4109 4110 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4111 low = self.sql(expression, "this") 4112 high = self.sql(expression, "expression") 4113 4114 return f"{low} TO {high}" 4115 4116 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4117 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4118 tables = f" {self.expressions(expression)}" 4119 4120 exists = " IF EXISTS" if expression.args.get("exists") else "" 4121 4122 on_cluster = self.sql(expression, "cluster") 4123 on_cluster = f" {on_cluster}" if on_cluster else "" 4124 4125 identity = self.sql(expression, "identity") 4126 identity = f" {identity} IDENTITY" if identity else "" 4127 4128 option = self.sql(expression, "option") 4129 option = f" {option}" if option else "" 4130 4131 partition = self.sql(expression, "partition") 4132 partition = f" {partition}" if partition else "" 4133 4134 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4135 4136 # This transpiles T-SQL's CONVERT function 4137 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4138 def convert_sql(self, expression: exp.Convert) -> str: 4139 to = expression.this 4140 value = expression.expression 4141 style = expression.args.get("style") 4142 safe = expression.args.get("safe") 4143 strict = expression.args.get("strict") 4144 4145 if not to or not value: 4146 return "" 4147 4148 # Retrieve length of datatype and override to default if not specified 4149 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4150 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4151 4152 transformed: t.Optional[exp.Expression] = None 4153 cast = exp.Cast if strict else exp.TryCast 4154 4155 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4156 if isinstance(style, exp.Literal) and style.is_int: 4157 from sqlglot.dialects.tsql import TSQL 4158 4159 style_value = style.name 4160 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4161 if not converted_style: 4162 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4163 4164 fmt = exp.Literal.string(converted_style) 4165 4166 if to.this == exp.DataType.Type.DATE: 4167 transformed = exp.StrToDate(this=value, format=fmt) 4168 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4169 transformed = exp.StrToTime(this=value, format=fmt) 4170 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4171 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4172 elif to.this == exp.DataType.Type.TEXT: 4173 transformed = exp.TimeToStr(this=value, format=fmt) 4174 4175 if not transformed: 4176 transformed = cast(this=value, to=to, safe=safe) 4177 4178 return self.sql(transformed) 4179 4180 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4181 this = expression.this 4182 if isinstance(this, exp.JSONPathWildcard): 4183 this = self.json_path_part(this) 4184 return f".{this}" if this else "" 4185 4186 if exp.SAFE_IDENTIFIER_RE.match(this): 4187 return f".{this}" 4188 4189 this = self.json_path_part(this) 4190 return ( 4191 f"[{this}]" 4192 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4193 else f".{this}" 4194 ) 4195 4196 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4197 this = self.json_path_part(expression.this) 4198 return f"[{this}]" if this else "" 4199 4200 def _simplify_unless_literal(self, expression: E) -> E: 4201 if not isinstance(expression, exp.Literal): 4202 from sqlglot.optimizer.simplify import simplify 4203 4204 expression = simplify(expression, dialect=self.dialect) 4205 4206 return expression 4207 4208 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4209 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4210 # The first modifier here will be the one closest to the AggFunc's arg 4211 mods = sorted( 4212 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4213 key=lambda x: 0 4214 if isinstance(x, exp.HavingMax) 4215 else (1 if isinstance(x, exp.Order) else 2), 4216 ) 4217 4218 if mods: 4219 mod = mods[0] 4220 this = expression.__class__(this=mod.this.copy()) 4221 this.meta["inline"] = True 4222 mod.this.replace(this) 4223 return self.sql(expression.this) 4224 4225 agg_func = expression.find(exp.AggFunc) 4226 4227 if agg_func: 4228 return self.sql(agg_func)[:-1] + f" {text})" 4229 4230 return f"{self.sql(expression, 'this')} {text}" 4231 4232 def _replace_line_breaks(self, string: str) -> str: 4233 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4234 if self.pretty: 4235 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4236 return string 4237 4238 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4239 option = self.sql(expression, "this") 4240 4241 if expression.expressions: 4242 upper = option.upper() 4243 4244 # Snowflake FILE_FORMAT options are separated by whitespace 4245 sep = " " if upper == "FILE_FORMAT" else ", " 4246 4247 # Databricks copy/format options do not set their list of values with EQ 4248 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4249 values = self.expressions(expression, flat=True, sep=sep) 4250 return f"{option}{op}({values})" 4251 4252 value = self.sql(expression, "expression") 4253 4254 if not value: 4255 return option 4256 4257 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4258 4259 return f"{option}{op}{value}" 4260 4261 def credentials_sql(self, expression: exp.Credentials) -> str: 4262 cred_expr = expression.args.get("credentials") 4263 if isinstance(cred_expr, exp.Literal): 4264 # Redshift case: CREDENTIALS <string> 4265 credentials = self.sql(expression, "credentials") 4266 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4267 else: 4268 # Snowflake case: CREDENTIALS = (...) 4269 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4270 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4271 4272 storage = self.sql(expression, "storage") 4273 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4274 4275 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4276 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4277 4278 iam_role = self.sql(expression, "iam_role") 4279 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4280 4281 region = self.sql(expression, "region") 4282 region = f" REGION {region}" if region else "" 4283 4284 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4285 4286 def copy_sql(self, expression: exp.Copy) -> str: 4287 this = self.sql(expression, "this") 4288 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4289 4290 credentials = self.sql(expression, "credentials") 4291 credentials = self.seg(credentials) if credentials else "" 4292 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4293 files = self.expressions(expression, key="files", flat=True) 4294 4295 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4296 params = self.expressions( 4297 expression, 4298 key="params", 4299 sep=sep, 4300 new_line=True, 4301 skip_last=True, 4302 skip_first=True, 4303 indent=self.COPY_PARAMS_ARE_WRAPPED, 4304 ) 4305 4306 if params: 4307 if self.COPY_PARAMS_ARE_WRAPPED: 4308 params = f" WITH ({params})" 4309 elif not self.pretty: 4310 params = f" {params}" 4311 4312 return f"COPY{this}{kind} {files}{credentials}{params}" 4313 4314 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4315 return "" 4316 4317 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4318 on_sql = "ON" if expression.args.get("on") else "OFF" 4319 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4320 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4321 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4322 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4323 4324 if filter_col or retention_period: 4325 on_sql = self.func("ON", filter_col, retention_period) 4326 4327 return f"DATA_DELETION={on_sql}" 4328 4329 def maskingpolicycolumnconstraint_sql( 4330 self, expression: exp.MaskingPolicyColumnConstraint 4331 ) -> str: 4332 this = self.sql(expression, "this") 4333 expressions = self.expressions(expression, flat=True) 4334 expressions = f" USING ({expressions})" if expressions else "" 4335 return f"MASKING POLICY {this}{expressions}" 4336 4337 def gapfill_sql(self, expression: exp.GapFill) -> str: 4338 this = self.sql(expression, "this") 4339 this = f"TABLE {this}" 4340 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4341 4342 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4343 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4344 4345 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4346 this = self.sql(expression, "this") 4347 expr = expression.expression 4348 4349 if isinstance(expr, exp.Func): 4350 # T-SQL's CLR functions are case sensitive 4351 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4352 else: 4353 expr = self.sql(expression, "expression") 4354 4355 return self.scope_resolution(expr, this) 4356 4357 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4358 if self.PARSE_JSON_NAME is None: 4359 return self.sql(expression.this) 4360 4361 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4362 4363 def rand_sql(self, expression: exp.Rand) -> str: 4364 lower = self.sql(expression, "lower") 4365 upper = self.sql(expression, "upper") 4366 4367 if lower and upper: 4368 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4369 return self.func("RAND", expression.this) 4370 4371 def changes_sql(self, expression: exp.Changes) -> str: 4372 information = self.sql(expression, "information") 4373 information = f"INFORMATION => {information}" 4374 at_before = self.sql(expression, "at_before") 4375 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4376 end = self.sql(expression, "end") 4377 end = f"{self.seg('')}{end}" if end else "" 4378 4379 return f"CHANGES ({information}){at_before}{end}" 4380 4381 def pad_sql(self, expression: exp.Pad) -> str: 4382 prefix = "L" if expression.args.get("is_left") else "R" 4383 4384 fill_pattern = self.sql(expression, "fill_pattern") or None 4385 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4386 fill_pattern = "' '" 4387 4388 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4389 4390 def summarize_sql(self, expression: exp.Summarize) -> str: 4391 table = " TABLE" if expression.args.get("table") else "" 4392 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4393 4394 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4395 generate_series = exp.GenerateSeries(**expression.args) 4396 4397 parent = expression.parent 4398 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4399 parent = parent.parent 4400 4401 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4402 return self.sql(exp.Unnest(expressions=[generate_series])) 4403 4404 if isinstance(parent, exp.Select): 4405 self.unsupported("GenerateSeries projection unnesting is not supported.") 4406 4407 return self.sql(generate_series) 4408 4409 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4410 exprs = expression.expressions 4411 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4412 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4413 else: 4414 rhs = self.expressions(expression) 4415 4416 return self.func(name, expression.this, rhs or None) 4417 4418 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4419 if self.SUPPORTS_CONVERT_TIMEZONE: 4420 return self.function_fallback_sql(expression) 4421 4422 source_tz = expression.args.get("source_tz") 4423 target_tz = expression.args.get("target_tz") 4424 timestamp = expression.args.get("timestamp") 4425 4426 if source_tz and timestamp: 4427 timestamp = exp.AtTimeZone( 4428 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4429 ) 4430 4431 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4432 4433 return self.sql(expr) 4434 4435 def json_sql(self, expression: exp.JSON) -> str: 4436 this = self.sql(expression, "this") 4437 this = f" {this}" if this else "" 4438 4439 _with = expression.args.get("with") 4440 4441 if _with is None: 4442 with_sql = "" 4443 elif not _with: 4444 with_sql = " WITHOUT" 4445 else: 4446 with_sql = " WITH" 4447 4448 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4449 4450 return f"JSON{this}{with_sql}{unique_sql}" 4451 4452 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4453 def _generate_on_options(arg: t.Any) -> str: 4454 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4455 4456 path = self.sql(expression, "path") 4457 returning = self.sql(expression, "returning") 4458 returning = f" RETURNING {returning}" if returning else "" 4459 4460 on_condition = self.sql(expression, "on_condition") 4461 on_condition = f" {on_condition}" if on_condition else "" 4462 4463 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4464 4465 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4466 else_ = "ELSE " if expression.args.get("else_") else "" 4467 condition = self.sql(expression, "expression") 4468 condition = f"WHEN {condition} THEN " if condition else else_ 4469 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4470 return f"{condition}{insert}" 4471 4472 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4473 kind = self.sql(expression, "kind") 4474 expressions = self.seg(self.expressions(expression, sep=" ")) 4475 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4476 return res 4477 4478 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4479 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4480 empty = expression.args.get("empty") 4481 empty = ( 4482 f"DEFAULT {empty} ON EMPTY" 4483 if isinstance(empty, exp.Expression) 4484 else self.sql(expression, "empty") 4485 ) 4486 4487 error = expression.args.get("error") 4488 error = ( 4489 f"DEFAULT {error} ON ERROR" 4490 if isinstance(error, exp.Expression) 4491 else self.sql(expression, "error") 4492 ) 4493 4494 if error and empty: 4495 error = ( 4496 f"{empty} {error}" 4497 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4498 else f"{error} {empty}" 4499 ) 4500 empty = "" 4501 4502 null = self.sql(expression, "null") 4503 4504 return f"{empty}{error}{null}" 4505 4506 def jsonextractquote_sql(self, expression: exp.JSONExtractQuote) -> str: 4507 scalar = " ON SCALAR STRING" if expression.args.get("scalar") else "" 4508 return f"{self.sql(expression, 'option')} QUOTES{scalar}" 4509 4510 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4511 this = self.sql(expression, "this") 4512 path = self.sql(expression, "path") 4513 4514 passing = self.expressions(expression, "passing") 4515 passing = f" PASSING {passing}" if passing else "" 4516 4517 on_condition = self.sql(expression, "on_condition") 4518 on_condition = f" {on_condition}" if on_condition else "" 4519 4520 path = f"{path}{passing}{on_condition}" 4521 4522 return self.func("JSON_EXISTS", this, path) 4523 4524 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4525 array_agg = self.function_fallback_sql(expression) 4526 4527 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4528 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4529 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4530 parent = expression.parent 4531 if isinstance(parent, exp.Filter): 4532 parent_cond = parent.expression.this 4533 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4534 else: 4535 this = expression.this 4536 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4537 if this.find(exp.Column): 4538 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4539 this_sql = ( 4540 self.expressions(this) 4541 if isinstance(this, exp.Distinct) 4542 else self.sql(expression, "this") 4543 ) 4544 4545 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4546 4547 return array_agg 4548 4549 def apply_sql(self, expression: exp.Apply) -> str: 4550 this = self.sql(expression, "this") 4551 expr = self.sql(expression, "expression") 4552 4553 return f"{this} APPLY({expr})" 4554 4555 def grant_sql(self, expression: exp.Grant) -> str: 4556 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4557 4558 kind = self.sql(expression, "kind") 4559 kind = f" {kind}" if kind else "" 4560 4561 securable = self.sql(expression, "securable") 4562 securable = f" {securable}" if securable else "" 4563 4564 principals = self.expressions(expression, key="principals", flat=True) 4565 4566 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4567 4568 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4569 4570 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4571 this = self.sql(expression, "this") 4572 columns = self.expressions(expression, flat=True) 4573 columns = f"({columns})" if columns else "" 4574 4575 return f"{this}{columns}" 4576 4577 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4578 this = self.sql(expression, "this") 4579 4580 kind = self.sql(expression, "kind") 4581 kind = f"{kind} " if kind else "" 4582 4583 return f"{kind}{this}" 4584 4585 def columns_sql(self, expression: exp.Columns): 4586 func = self.function_fallback_sql(expression) 4587 if expression.args.get("unpack"): 4588 func = f"*{func}" 4589 4590 return func 4591 4592 def overlay_sql(self, expression: exp.Overlay): 4593 this = self.sql(expression, "this") 4594 expr = self.sql(expression, "expression") 4595 from_sql = self.sql(expression, "from") 4596 for_sql = self.sql(expression, "for") 4597 for_sql = f" FOR {for_sql}" if for_sql else "" 4598 4599 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4600 4601 @unsupported_args("format") 4602 def todouble_sql(self, expression: exp.ToDouble) -> str: 4603 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4604 4605 def string_sql(self, expression: exp.String) -> str: 4606 this = expression.this 4607 zone = expression.args.get("zone") 4608 4609 if zone: 4610 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4611 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4612 # set for source_tz to transpile the time conversion before the STRING cast 4613 this = exp.ConvertTimezone( 4614 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4615 ) 4616 4617 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4618 4619 def median_sql(self, expression: exp.Median): 4620 if not self.SUPPORTS_MEDIAN: 4621 return self.sql( 4622 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4623 ) 4624 4625 return self.function_fallback_sql(expression) 4626 4627 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4628 filler = self.sql(expression, "this") 4629 filler = f" {filler}" if filler else "" 4630 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4631 return f"TRUNCATE{filler} {with_count}" 4632 4633 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4634 if self.SUPPORTS_UNIX_SECONDS: 4635 return self.function_fallback_sql(expression) 4636 4637 start_ts = exp.cast( 4638 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4639 ) 4640 4641 return self.sql( 4642 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4643 ) 4644 4645 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4646 dim = expression.expression 4647 4648 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4649 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4650 if not (dim.is_int and dim.name == "1"): 4651 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4652 dim = None 4653 4654 # If dimension is required but not specified, default initialize it 4655 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4656 dim = exp.Literal.number(1) 4657 4658 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4659 4660 def attach_sql(self, expression: exp.Attach) -> str: 4661 this = self.sql(expression, "this") 4662 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4663 expressions = self.expressions(expression) 4664 expressions = f" ({expressions})" if expressions else "" 4665 4666 return f"ATTACH{exists_sql} {this}{expressions}" 4667 4668 def detach_sql(self, expression: exp.Detach) -> str: 4669 this = self.sql(expression, "this") 4670 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4671 4672 return f"DETACH{exists_sql} {this}" 4673 4674 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4675 this = self.sql(expression, "this") 4676 value = self.sql(expression, "expression") 4677 value = f" {value}" if value else "" 4678 return f"{this}{value}" 4679 4680 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4681 this_sql = self.sql(expression, "this") 4682 if isinstance(expression.this, exp.Table): 4683 this_sql = f"TABLE {this_sql}" 4684 4685 return self.func( 4686 "FEATURES_AT_TIME", 4687 this_sql, 4688 expression.args.get("time"), 4689 expression.args.get("num_rows"), 4690 expression.args.get("ignore_feature_nulls"), 4691 ) 4692 4693 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4694 return ( 4695 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4696 ) 4697 4698 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4699 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4700 encode = f"{encode} {self.sql(expression, 'this')}" 4701 4702 properties = expression.args.get("properties") 4703 if properties: 4704 encode = f"{encode} {self.properties(properties)}" 4705 4706 return encode 4707 4708 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4709 this = self.sql(expression, "this") 4710 include = f"INCLUDE {this}" 4711 4712 column_def = self.sql(expression, "column_def") 4713 if column_def: 4714 include = f"{include} {column_def}" 4715 4716 alias = self.sql(expression, "alias") 4717 if alias: 4718 include = f"{include} AS {alias}" 4719 4720 return include 4721 4722 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4723 name = f"NAME {self.sql(expression, 'this')}" 4724 return self.func("XMLELEMENT", name, *expression.expressions) 4725 4726 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4727 partitions = self.expressions(expression, "partition_expressions") 4728 create = self.expressions(expression, "create_expressions") 4729 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4730 4731 def partitionbyrangepropertydynamic_sql( 4732 self, expression: exp.PartitionByRangePropertyDynamic 4733 ) -> str: 4734 start = self.sql(expression, "start") 4735 end = self.sql(expression, "end") 4736 4737 every = expression.args["every"] 4738 if isinstance(every, exp.Interval) and every.this.is_string: 4739 every.this.replace(exp.Literal.number(every.name)) 4740 4741 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4742 4743 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4744 name = self.sql(expression, "this") 4745 values = self.expressions(expression, flat=True) 4746 4747 return f"NAME {name} VALUE {values}" 4748 4749 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4750 kind = self.sql(expression, "kind") 4751 sample = self.sql(expression, "sample") 4752 return f"SAMPLE {sample} {kind}" 4753 4754 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4755 kind = self.sql(expression, "kind") 4756 option = self.sql(expression, "option") 4757 option = f" {option}" if option else "" 4758 this = self.sql(expression, "this") 4759 this = f" {this}" if this else "" 4760 columns = self.expressions(expression) 4761 columns = f" {columns}" if columns else "" 4762 return f"{kind}{option} STATISTICS{this}{columns}" 4763 4764 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4765 this = self.sql(expression, "this") 4766 columns = self.expressions(expression) 4767 inner_expression = self.sql(expression, "expression") 4768 inner_expression = f" {inner_expression}" if inner_expression else "" 4769 update_options = self.sql(expression, "update_options") 4770 update_options = f" {update_options} UPDATE" if update_options else "" 4771 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4772 4773 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4774 kind = self.sql(expression, "kind") 4775 kind = f" {kind}" if kind else "" 4776 return f"DELETE{kind} STATISTICS" 4777 4778 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4779 inner_expression = self.sql(expression, "expression") 4780 return f"LIST CHAINED ROWS{inner_expression}" 4781 4782 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4783 kind = self.sql(expression, "kind") 4784 this = self.sql(expression, "this") 4785 this = f" {this}" if this else "" 4786 inner_expression = self.sql(expression, "expression") 4787 return f"VALIDATE {kind}{this}{inner_expression}" 4788 4789 def analyze_sql(self, expression: exp.Analyze) -> str: 4790 options = self.expressions(expression, key="options", sep=" ") 4791 options = f" {options}" if options else "" 4792 kind = self.sql(expression, "kind") 4793 kind = f" {kind}" if kind else "" 4794 this = self.sql(expression, "this") 4795 this = f" {this}" if this else "" 4796 mode = self.sql(expression, "mode") 4797 mode = f" {mode}" if mode else "" 4798 properties = self.sql(expression, "properties") 4799 properties = f" {properties}" if properties else "" 4800 partition = self.sql(expression, "partition") 4801 partition = f" {partition}" if partition else "" 4802 inner_expression = self.sql(expression, "expression") 4803 inner_expression = f" {inner_expression}" if inner_expression else "" 4804 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4805 4806 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4807 this = self.sql(expression, "this") 4808 namespaces = self.expressions(expression, key="namespaces") 4809 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4810 passing = self.expressions(expression, key="passing") 4811 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4812 columns = self.expressions(expression, key="columns") 4813 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4814 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4815 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}" 4816 4817 def xmlnamespace_sql(self, expression: exp.XMLNamespace) -> str: 4818 this = self.sql(expression, "this") 4819 return this if isinstance(expression.this, exp.Alias) else f"DEFAULT {this}" 4820 4821 def export_sql(self, expression: exp.Export) -> str: 4822 this = self.sql(expression, "this") 4823 connection = self.sql(expression, "connection") 4824 connection = f"WITH CONNECTION {connection} " if connection else "" 4825 options = self.sql(expression, "options") 4826 return f"EXPORT DATA {connection}{options} AS {this}" 4827 4828 def declare_sql(self, expression: exp.Declare) -> str: 4829 return f"DECLARE {self.expressions(expression, flat=True)}" 4830 4831 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4832 variable = self.sql(expression, "this") 4833 default = self.sql(expression, "default") 4834 default = f" = {default}" if default else "" 4835 4836 kind = self.sql(expression, "kind") 4837 if isinstance(expression.args.get("kind"), exp.Schema): 4838 kind = f"TABLE {kind}" 4839 4840 return f"{variable} AS {kind}{default}" 4841 4842 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4843 kind = self.sql(expression, "kind") 4844 this = self.sql(expression, "this") 4845 set = self.sql(expression, "expression") 4846 using = self.sql(expression, "using") 4847 using = f" USING {using}" if using else "" 4848 4849 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4850 4851 return f"{kind_sql} {this} SET {set}{using}" 4852 4853 def parameterizedagg_sql(self, expression: exp.ParameterizedAgg) -> str: 4854 params = self.expressions(expression, key="params", flat=True) 4855 return self.func(expression.name, *expression.expressions) + f"({params})" 4856 4857 def anonymousaggfunc_sql(self, expression: exp.AnonymousAggFunc) -> str: 4858 return self.func(expression.name, *expression.expressions) 4859 4860 def combinedaggfunc_sql(self, expression: exp.CombinedAggFunc) -> str: 4861 return self.anonymousaggfunc_sql(expression) 4862 4863 def combinedparameterizedagg_sql(self, expression: exp.CombinedParameterizedAgg) -> str: 4864 return self.parameterizedagg_sql(expression) 4865 4866 def show_sql(self, expression: exp.Show) -> str: 4867 self.unsupported("Unsupported SHOW statement") 4868 return "" 4869 4870 def put_sql(self, expression: exp.Put) -> str: 4871 props = expression.args.get("properties") 4872 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4873 this = self.sql(expression, "this") 4874 target = self.sql(expression, "target") 4875 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)
679 def __init__( 680 self, 681 pretty: t.Optional[bool] = None, 682 identify: str | bool = False, 683 normalize: bool = False, 684 pad: int = 2, 685 indent: int = 2, 686 normalize_functions: t.Optional[str | bool] = None, 687 unsupported_level: ErrorLevel = ErrorLevel.WARN, 688 max_unsupported: int = 3, 689 leading_comma: bool = False, 690 max_text_width: int = 80, 691 comments: bool = True, 692 dialect: DialectType = None, 693 ): 694 import sqlglot 695 from sqlglot.dialects import Dialect 696 697 self.pretty = pretty if pretty is not None else sqlglot.pretty 698 self.identify = identify 699 self.normalize = normalize 700 self.pad = pad 701 self._indent = indent 702 self.unsupported_level = unsupported_level 703 self.max_unsupported = max_unsupported 704 self.leading_comma = leading_comma 705 self.max_text_width = max_text_width 706 self.comments = comments 707 self.dialect = Dialect.get_or_raise(dialect) 708 709 # This is both a Dialect property and a Generator argument, so we prioritize the latter 710 self.normalize_functions = ( 711 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 712 ) 713 714 self.unsupported_messages: t.List[str] = [] 715 self._escaped_quote_end: str = ( 716 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 717 ) 718 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 719 720 self._next_name = name_sequence("_t") 721 722 self._identifier_start = self.dialect.IDENTIFIER_START 723 self._identifier_end = self.dialect.IDENTIFIER_END 724 725 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.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.JSONPathFilter'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>}
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.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.CHAR: 'CHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.NVARCHAR: 'NVARCHAR'>}
727 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 728 """ 729 Generates the SQL string corresponding to the given syntax tree. 730 731 Args: 732 expression: The syntax tree. 733 copy: Whether to copy the expression. The generator performs mutations so 734 it is safer to copy. 735 736 Returns: 737 The SQL string corresponding to `expression`. 738 """ 739 if copy: 740 expression = expression.copy() 741 742 expression = self.preprocess(expression) 743 744 self.unsupported_messages = [] 745 sql = self.sql(expression).strip() 746 747 if self.pretty: 748 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 749 750 if self.unsupported_level == ErrorLevel.IGNORE: 751 return sql 752 753 if self.unsupported_level == ErrorLevel.WARN: 754 for msg in self.unsupported_messages: 755 logger.warning(msg) 756 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 757 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 758 759 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:
761 def preprocess(self, expression: exp.Expression) -> exp.Expression: 762 """Apply generic preprocessing transformations to a given expression.""" 763 expression = self._move_ctes_to_top_level(expression) 764 765 if self.ENSURE_BOOLS: 766 from sqlglot.transforms import ensure_bools 767 768 expression = ensure_bools(expression) 769 770 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:
799 def maybe_comment( 800 self, 801 sql: str, 802 expression: t.Optional[exp.Expression] = None, 803 comments: t.Optional[t.List[str]] = None, 804 separated: bool = False, 805 ) -> str: 806 comments = ( 807 ((expression and expression.comments) if comments is None else comments) # type: ignore 808 if self.comments 809 else None 810 ) 811 812 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 813 return sql 814 815 comments_sql = " ".join( 816 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 817 ) 818 819 if not comments_sql: 820 return sql 821 822 comments_sql = self._replace_line_breaks(comments_sql) 823 824 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 825 return ( 826 f"{self.sep()}{comments_sql}{sql}" 827 if not sql or sql[0].isspace() 828 else f"{comments_sql}{self.sep()}{sql}" 829 ) 830 831 return f"{sql} {comments_sql}"
833 def wrap(self, expression: exp.Expression | str) -> str: 834 this_sql = ( 835 self.sql(expression) 836 if isinstance(expression, exp.UNWRAPPED_QUERIES) 837 else self.sql(expression, "this") 838 ) 839 if not this_sql: 840 return "()" 841 842 this_sql = self.indent(this_sql, level=1, pad=0) 843 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:
859 def indent( 860 self, 861 sql: str, 862 level: int = 0, 863 pad: t.Optional[int] = None, 864 skip_first: bool = False, 865 skip_last: bool = False, 866 ) -> str: 867 if not self.pretty or not sql: 868 return sql 869 870 pad = self.pad if pad is None else pad 871 lines = sql.split("\n") 872 873 return "\n".join( 874 ( 875 line 876 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 877 else f"{' ' * (level * self._indent + pad)}{line}" 878 ) 879 for i, line in enumerate(lines) 880 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
882 def sql( 883 self, 884 expression: t.Optional[str | exp.Expression], 885 key: t.Optional[str] = None, 886 comment: bool = True, 887 ) -> str: 888 if not expression: 889 return "" 890 891 if isinstance(expression, str): 892 return expression 893 894 if key: 895 value = expression.args.get(key) 896 if value: 897 return self.sql(value) 898 return "" 899 900 transform = self.TRANSFORMS.get(expression.__class__) 901 902 if callable(transform): 903 sql = transform(self, expression) 904 elif isinstance(expression, exp.Expression): 905 exp_handler_name = f"{expression.key}_sql" 906 907 if hasattr(self, exp_handler_name): 908 sql = getattr(self, exp_handler_name)(expression) 909 elif isinstance(expression, exp.Func): 910 sql = self.function_fallback_sql(expression) 911 elif isinstance(expression, exp.Property): 912 sql = self.property_sql(expression) 913 else: 914 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 915 else: 916 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 917 918 return self.maybe_comment(sql, expression) if self.comments and comment else sql
925 def cache_sql(self, expression: exp.Cache) -> str: 926 lazy = " LAZY" if expression.args.get("lazy") else "" 927 table = self.sql(expression, "this") 928 options = expression.args.get("options") 929 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 930 sql = self.sql(expression, "expression") 931 sql = f" AS{self.sep()}{sql}" if sql else "" 932 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 933 return self.prepend_ctes(expression, sql)
935 def characterset_sql(self, expression: exp.CharacterSet) -> str: 936 if isinstance(expression.parent, exp.Cast): 937 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 938 default = "DEFAULT " if expression.args.get("default") else "" 939 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
953 def column_sql(self, expression: exp.Column) -> str: 954 join_mark = " (+)" if expression.args.get("join_mark") else "" 955 956 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 957 join_mark = "" 958 self.unsupported("Outer join syntax using the (+) operator is not supported.") 959 960 return f"{self.column_parts(expression)}{join_mark}"
968 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 969 column = self.sql(expression, "this") 970 kind = self.sql(expression, "kind") 971 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 972 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 973 kind = f"{sep}{kind}" if kind else "" 974 constraints = f" {constraints}" if constraints else "" 975 position = self.sql(expression, "position") 976 position = f" {position}" if position else "" 977 978 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 979 kind = "" 980 981 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
988 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 989 this = self.sql(expression, "this") 990 if expression.args.get("not_null"): 991 persisted = " PERSISTED NOT NULL" 992 elif expression.args.get("persisted"): 993 persisted = " PERSISTED" 994 else: 995 persisted = "" 996 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1009 def generatedasidentitycolumnconstraint_sql( 1010 self, expression: exp.GeneratedAsIdentityColumnConstraint 1011 ) -> str: 1012 this = "" 1013 if expression.this is not None: 1014 on_null = " ON NULL" if expression.args.get("on_null") else "" 1015 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1016 1017 start = expression.args.get("start") 1018 start = f"START WITH {start}" if start else "" 1019 increment = expression.args.get("increment") 1020 increment = f" INCREMENT BY {increment}" if increment else "" 1021 minvalue = expression.args.get("minvalue") 1022 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1023 maxvalue = expression.args.get("maxvalue") 1024 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1025 cycle = expression.args.get("cycle") 1026 cycle_sql = "" 1027 1028 if cycle is not None: 1029 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1030 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1031 1032 sequence_opts = "" 1033 if start or increment or cycle_sql: 1034 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1035 sequence_opts = f" ({sequence_opts.strip()})" 1036 1037 expr = self.sql(expression, "expression") 1038 expr = f"({expr})" if expr else "IDENTITY" 1039 1040 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1042 def generatedasrowcolumnconstraint_sql( 1043 self, expression: exp.GeneratedAsRowColumnConstraint 1044 ) -> str: 1045 start = "START" if expression.args.get("start") else "END" 1046 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1047 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:
1066 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1067 this = self.sql(expression, "this") 1068 this = f" {this}" if this else "" 1069 index_type = expression.args.get("index_type") 1070 index_type = f" USING {index_type}" if index_type else "" 1071 on_conflict = self.sql(expression, "on_conflict") 1072 on_conflict = f" {on_conflict}" if on_conflict else "" 1073 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1074 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1079 def create_sql(self, expression: exp.Create) -> str: 1080 kind = self.sql(expression, "kind") 1081 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1082 properties = expression.args.get("properties") 1083 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1084 1085 this = self.createable_sql(expression, properties_locs) 1086 1087 properties_sql = "" 1088 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1089 exp.Properties.Location.POST_WITH 1090 ): 1091 properties_sql = self.sql( 1092 exp.Properties( 1093 expressions=[ 1094 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1095 *properties_locs[exp.Properties.Location.POST_WITH], 1096 ] 1097 ) 1098 ) 1099 1100 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1101 properties_sql = self.sep() + properties_sql 1102 elif not self.pretty: 1103 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1104 properties_sql = f" {properties_sql}" 1105 1106 begin = " BEGIN" if expression.args.get("begin") else "" 1107 end = " END" if expression.args.get("end") else "" 1108 1109 expression_sql = self.sql(expression, "expression") 1110 if expression_sql: 1111 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1112 1113 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1114 postalias_props_sql = "" 1115 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1116 postalias_props_sql = self.properties( 1117 exp.Properties( 1118 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1119 ), 1120 wrapped=False, 1121 ) 1122 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1123 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1124 1125 postindex_props_sql = "" 1126 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1127 postindex_props_sql = self.properties( 1128 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1129 wrapped=False, 1130 prefix=" ", 1131 ) 1132 1133 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1134 indexes = f" {indexes}" if indexes else "" 1135 index_sql = indexes + postindex_props_sql 1136 1137 replace = " OR REPLACE" if expression.args.get("replace") else "" 1138 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1139 unique = " UNIQUE" if expression.args.get("unique") else "" 1140 1141 clustered = expression.args.get("clustered") 1142 if clustered is None: 1143 clustered_sql = "" 1144 elif clustered: 1145 clustered_sql = " CLUSTERED COLUMNSTORE" 1146 else: 1147 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1148 1149 postcreate_props_sql = "" 1150 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1151 postcreate_props_sql = self.properties( 1152 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1153 sep=" ", 1154 prefix=" ", 1155 wrapped=False, 1156 ) 1157 1158 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1159 1160 postexpression_props_sql = "" 1161 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1162 postexpression_props_sql = self.properties( 1163 exp.Properties( 1164 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1165 ), 1166 sep=" ", 1167 prefix=" ", 1168 wrapped=False, 1169 ) 1170 1171 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1172 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1173 no_schema_binding = ( 1174 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1175 ) 1176 1177 clone = self.sql(expression, "clone") 1178 clone = f" {clone}" if clone else "" 1179 1180 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1181 properties_expression = f"{expression_sql}{properties_sql}" 1182 else: 1183 properties_expression = f"{properties_sql}{expression_sql}" 1184 1185 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1186 return self.prepend_ctes(expression, expression_sql)
1188 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1189 start = self.sql(expression, "start") 1190 start = f"START WITH {start}" if start else "" 1191 increment = self.sql(expression, "increment") 1192 increment = f" INCREMENT BY {increment}" if increment else "" 1193 minvalue = self.sql(expression, "minvalue") 1194 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1195 maxvalue = self.sql(expression, "maxvalue") 1196 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1197 owned = self.sql(expression, "owned") 1198 owned = f" OWNED BY {owned}" if owned else "" 1199 1200 cache = expression.args.get("cache") 1201 if cache is None: 1202 cache_str = "" 1203 elif cache is True: 1204 cache_str = " CACHE" 1205 else: 1206 cache_str = f" CACHE {cache}" 1207 1208 options = self.expressions(expression, key="options", flat=True, sep=" ") 1209 options = f" {options}" if options else "" 1210 1211 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1213 def clone_sql(self, expression: exp.Clone) -> str: 1214 this = self.sql(expression, "this") 1215 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1216 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1217 return f"{shallow}{keyword} {this}"
1219 def describe_sql(self, expression: exp.Describe) -> str: 1220 style = expression.args.get("style") 1221 style = f" {style}" if style else "" 1222 partition = self.sql(expression, "partition") 1223 partition = f" {partition}" if partition else "" 1224 format = self.sql(expression, "format") 1225 format = f" {format}" if format else "" 1226 1227 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1239 def with_sql(self, expression: exp.With) -> str: 1240 sql = self.expressions(expression, flat=True) 1241 recursive = ( 1242 "RECURSIVE " 1243 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1244 else "" 1245 ) 1246 search = self.sql(expression, "search") 1247 search = f" {search}" if search else "" 1248 1249 return f"WITH {recursive}{sql}{search}"
1251 def cte_sql(self, expression: exp.CTE) -> str: 1252 alias = expression.args.get("alias") 1253 if alias: 1254 alias.add_comments(expression.pop_comments()) 1255 1256 alias_sql = self.sql(expression, "alias") 1257 1258 materialized = expression.args.get("materialized") 1259 if materialized is False: 1260 materialized = "NOT MATERIALIZED " 1261 elif materialized: 1262 materialized = "MATERIALIZED " 1263 1264 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1266 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1267 alias = self.sql(expression, "this") 1268 columns = self.expressions(expression, key="columns", flat=True) 1269 columns = f"({columns})" if columns else "" 1270 1271 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1272 columns = "" 1273 self.unsupported("Named columns are not supported in table alias.") 1274 1275 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1276 alias = self._next_name() 1277 1278 return f"{alias}{columns}"
def
hexstring_sql( self, expression: sqlglot.expressions.HexString, binary_function_repr: Optional[str] = None) -> str:
1286 def hexstring_sql( 1287 self, expression: exp.HexString, binary_function_repr: t.Optional[str] = None 1288 ) -> str: 1289 this = self.sql(expression, "this") 1290 is_integer_type = expression.args.get("is_integer") 1291 1292 if (is_integer_type and not self.dialect.HEX_STRING_IS_INTEGER_TYPE) or ( 1293 not self.dialect.HEX_START and not binary_function_repr 1294 ): 1295 # Integer representation will be returned if: 1296 # - The read dialect treats the hex value as integer literal but not the write 1297 # - The transpilation is not supported (write dialect hasn't set HEX_START or the param flag) 1298 return f"{int(this, 16)}" 1299 1300 if not is_integer_type: 1301 # Read dialect treats the hex value as BINARY/BLOB 1302 if binary_function_repr: 1303 # The write dialect supports the transpilation to its equivalent BINARY/BLOB 1304 return self.func(binary_function_repr, exp.Literal.string(this)) 1305 if self.dialect.HEX_STRING_IS_INTEGER_TYPE: 1306 # The write dialect does not support the transpilation, it'll treat the hex value as INTEGER 1307 self.unsupported("Unsupported transpilation from BINARY/BLOB hex string") 1308 1309 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}"
1317 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1318 this = self.sql(expression, "this") 1319 escape = expression.args.get("escape") 1320 1321 if self.dialect.UNICODE_START: 1322 escape_substitute = r"\\\1" 1323 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1324 else: 1325 escape_substitute = r"\\u\1" 1326 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1327 1328 if escape: 1329 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1330 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1331 else: 1332 escape_pattern = ESCAPED_UNICODE_RE 1333 escape_sql = "" 1334 1335 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1336 this = escape_pattern.sub(escape_substitute, this) 1337 1338 return f"{left_quote}{this}{right_quote}{escape_sql}"
1350 def datatype_sql(self, expression: exp.DataType) -> str: 1351 nested = "" 1352 values = "" 1353 interior = self.expressions(expression, flat=True) 1354 1355 type_value = expression.this 1356 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1357 type_sql = self.sql(expression, "kind") 1358 else: 1359 type_sql = ( 1360 self.TYPE_MAPPING.get(type_value, type_value.value) 1361 if isinstance(type_value, exp.DataType.Type) 1362 else type_value 1363 ) 1364 1365 if interior: 1366 if expression.args.get("nested"): 1367 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1368 if expression.args.get("values") is not None: 1369 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1370 values = self.expressions(expression, key="values", flat=True) 1371 values = f"{delimiters[0]}{values}{delimiters[1]}" 1372 elif type_value == exp.DataType.Type.INTERVAL: 1373 nested = f" {interior}" 1374 else: 1375 nested = f"({interior})" 1376 1377 type_sql = f"{type_sql}{nested}{values}" 1378 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1379 exp.DataType.Type.TIMETZ, 1380 exp.DataType.Type.TIMESTAMPTZ, 1381 ): 1382 type_sql = f"{type_sql} WITH TIME ZONE" 1383 1384 return type_sql
1386 def directory_sql(self, expression: exp.Directory) -> str: 1387 local = "LOCAL " if expression.args.get("local") else "" 1388 row_format = self.sql(expression, "row_format") 1389 row_format = f" {row_format}" if row_format else "" 1390 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1392 def delete_sql(self, expression: exp.Delete) -> str: 1393 this = self.sql(expression, "this") 1394 this = f" FROM {this}" if this else "" 1395 using = self.sql(expression, "using") 1396 using = f" USING {using}" if using else "" 1397 cluster = self.sql(expression, "cluster") 1398 cluster = f" {cluster}" if cluster else "" 1399 where = self.sql(expression, "where") 1400 returning = self.sql(expression, "returning") 1401 limit = self.sql(expression, "limit") 1402 tables = self.expressions(expression, key="tables") 1403 tables = f" {tables}" if tables else "" 1404 if self.RETURNING_END: 1405 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1406 else: 1407 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1408 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1410 def drop_sql(self, expression: exp.Drop) -> str: 1411 this = self.sql(expression, "this") 1412 expressions = self.expressions(expression, flat=True) 1413 expressions = f" ({expressions})" if expressions else "" 1414 kind = expression.args["kind"] 1415 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1416 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1417 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1418 on_cluster = self.sql(expression, "cluster") 1419 on_cluster = f" {on_cluster}" if on_cluster else "" 1420 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1421 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1422 cascade = " CASCADE" if expression.args.get("cascade") else "" 1423 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1424 purge = " PURGE" if expression.args.get("purge") else "" 1425 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1427 def set_operation(self, expression: exp.SetOperation) -> str: 1428 op_type = type(expression) 1429 op_name = op_type.key.upper() 1430 1431 distinct = expression.args.get("distinct") 1432 if ( 1433 distinct is False 1434 and op_type in (exp.Except, exp.Intersect) 1435 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1436 ): 1437 self.unsupported(f"{op_name} ALL is not supported") 1438 1439 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1440 1441 if distinct is None: 1442 distinct = default_distinct 1443 if distinct is None: 1444 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1445 1446 if distinct is default_distinct: 1447 kind = "" 1448 else: 1449 kind = " DISTINCT" if distinct else " ALL" 1450 1451 by_name = " BY NAME" if expression.args.get("by_name") else "" 1452 return f"{op_name}{kind}{by_name}"
1454 def set_operations(self, expression: exp.SetOperation) -> str: 1455 if not self.SET_OP_MODIFIERS: 1456 limit = expression.args.get("limit") 1457 order = expression.args.get("order") 1458 1459 if limit or order: 1460 select = self._move_ctes_to_top_level( 1461 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1462 ) 1463 1464 if limit: 1465 select = select.limit(limit.pop(), copy=False) 1466 if order: 1467 select = select.order_by(order.pop(), copy=False) 1468 return self.sql(select) 1469 1470 sqls: t.List[str] = [] 1471 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1472 1473 while stack: 1474 node = stack.pop() 1475 1476 if isinstance(node, exp.SetOperation): 1477 stack.append(node.expression) 1478 stack.append( 1479 self.maybe_comment( 1480 self.set_operation(node), comments=node.comments, separated=True 1481 ) 1482 ) 1483 stack.append(node.this) 1484 else: 1485 sqls.append(self.sql(node)) 1486 1487 this = self.sep().join(sqls) 1488 this = self.query_modifiers(expression, this) 1489 return self.prepend_ctes(expression, this)
1491 def fetch_sql(self, expression: exp.Fetch) -> str: 1492 direction = expression.args.get("direction") 1493 direction = f" {direction}" if direction else "" 1494 count = self.sql(expression, "count") 1495 count = f" {count}" if count else "" 1496 limit_options = self.sql(expression, "limit_options") 1497 limit_options = f"{limit_options}" if limit_options else " ROWS ONLY" 1498 return f"{self.seg('FETCH')}{direction}{count}{limit_options}"
1500 def limitoptions_sql(self, expression: exp.LimitOptions) -> str: 1501 percent = " PERCENT" if expression.args.get("percent") else "" 1502 rows = " ROWS" if expression.args.get("rows") else "" 1503 with_ties = " WITH TIES" if expression.args.get("with_ties") else "" 1504 if not with_ties and rows: 1505 with_ties = " ONLY" 1506 return f"{percent}{rows}{with_ties}"
1508 def filter_sql(self, expression: exp.Filter) -> str: 1509 if self.AGGREGATE_FILTER_SUPPORTED: 1510 this = self.sql(expression, "this") 1511 where = self.sql(expression, "expression").strip() 1512 return f"{this} FILTER({where})" 1513 1514 agg = expression.this 1515 agg_arg = agg.this 1516 cond = expression.expression.this 1517 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1518 return self.sql(agg)
1527 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1528 using = self.sql(expression, "using") 1529 using = f" USING {using}" if using else "" 1530 columns = self.expressions(expression, key="columns", flat=True) 1531 columns = f"({columns})" if columns else "" 1532 partition_by = self.expressions(expression, key="partition_by", flat=True) 1533 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1534 where = self.sql(expression, "where") 1535 include = self.expressions(expression, key="include", flat=True) 1536 if include: 1537 include = f" INCLUDE ({include})" 1538 with_storage = self.expressions(expression, key="with_storage", flat=True) 1539 with_storage = f" WITH ({with_storage})" if with_storage else "" 1540 tablespace = self.sql(expression, "tablespace") 1541 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1542 on = self.sql(expression, "on") 1543 on = f" ON {on}" if on else "" 1544 1545 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1547 def index_sql(self, expression: exp.Index) -> str: 1548 unique = "UNIQUE " if expression.args.get("unique") else "" 1549 primary = "PRIMARY " if expression.args.get("primary") else "" 1550 amp = "AMP " if expression.args.get("amp") else "" 1551 name = self.sql(expression, "this") 1552 name = f"{name} " if name else "" 1553 table = self.sql(expression, "table") 1554 table = f"{self.INDEX_ON} {table}" if table else "" 1555 1556 index = "INDEX " if not table else "" 1557 1558 params = self.sql(expression, "params") 1559 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1561 def identifier_sql(self, expression: exp.Identifier) -> str: 1562 text = expression.name 1563 lower = text.lower() 1564 text = lower if self.normalize and not expression.quoted else text 1565 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1566 if ( 1567 expression.quoted 1568 or self.dialect.can_identify(text, self.identify) 1569 or lower in self.RESERVED_KEYWORDS 1570 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1571 ): 1572 text = f"{self._identifier_start}{text}{self._identifier_end}" 1573 return text
1588 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1589 input_format = self.sql(expression, "input_format") 1590 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1591 output_format = self.sql(expression, "output_format") 1592 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1593 return self.sep().join((input_format, output_format))
1603 def properties_sql(self, expression: exp.Properties) -> str: 1604 root_properties = [] 1605 with_properties = [] 1606 1607 for p in expression.expressions: 1608 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1609 if p_loc == exp.Properties.Location.POST_WITH: 1610 with_properties.append(p) 1611 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1612 root_properties.append(p) 1613 1614 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1615 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1616 1617 if root_props and with_props and not self.pretty: 1618 with_props = " " + with_props 1619 1620 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1627 def properties( 1628 self, 1629 properties: exp.Properties, 1630 prefix: str = "", 1631 sep: str = ", ", 1632 suffix: str = "", 1633 wrapped: bool = True, 1634 ) -> str: 1635 if properties.expressions: 1636 expressions = self.expressions(properties, sep=sep, indent=False) 1637 if expressions: 1638 expressions = self.wrap(expressions) if wrapped else expressions 1639 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1640 return ""
1645 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1646 properties_locs = defaultdict(list) 1647 for p in properties.expressions: 1648 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1649 if p_loc != exp.Properties.Location.UNSUPPORTED: 1650 properties_locs[p_loc].append(p) 1651 else: 1652 self.unsupported(f"Unsupported property {p.key}") 1653 1654 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1661 def property_sql(self, expression: exp.Property) -> str: 1662 property_cls = expression.__class__ 1663 if property_cls == exp.Property: 1664 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1665 1666 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1667 if not property_name: 1668 self.unsupported(f"Unsupported property {expression.key}") 1669 1670 return f"{property_name}={self.sql(expression, 'this')}"
1672 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1673 if self.SUPPORTS_CREATE_TABLE_LIKE: 1674 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1675 options = f" {options}" if options else "" 1676 1677 like = f"LIKE {self.sql(expression, 'this')}{options}" 1678 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1679 like = f"({like})" 1680 1681 return like 1682 1683 if expression.expressions: 1684 self.unsupported("Transpilation of LIKE property options is unsupported") 1685 1686 select = exp.select("*").from_(expression.this).limit(0) 1687 return f"AS {self.sql(select)}"
1694 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1695 no = "NO " if expression.args.get("no") else "" 1696 local = expression.args.get("local") 1697 local = f"{local} " if local else "" 1698 dual = "DUAL " if expression.args.get("dual") else "" 1699 before = "BEFORE " if expression.args.get("before") else "" 1700 after = "AFTER " if expression.args.get("after") else "" 1701 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1717 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1718 if expression.args.get("no"): 1719 return "NO MERGEBLOCKRATIO" 1720 if expression.args.get("default"): 1721 return "DEFAULT MERGEBLOCKRATIO" 1722 1723 percent = " PERCENT" if expression.args.get("percent") else "" 1724 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1726 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1727 default = expression.args.get("default") 1728 minimum = expression.args.get("minimum") 1729 maximum = expression.args.get("maximum") 1730 if default or minimum or maximum: 1731 if default: 1732 prop = "DEFAULT" 1733 elif minimum: 1734 prop = "MINIMUM" 1735 else: 1736 prop = "MAXIMUM" 1737 return f"{prop} DATABLOCKSIZE" 1738 units = expression.args.get("units") 1739 units = f" {units}" if units else "" 1740 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1742 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1743 autotemp = expression.args.get("autotemp") 1744 always = expression.args.get("always") 1745 default = expression.args.get("default") 1746 manual = expression.args.get("manual") 1747 never = expression.args.get("never") 1748 1749 if autotemp is not None: 1750 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1751 elif always: 1752 prop = "ALWAYS" 1753 elif default: 1754 prop = "DEFAULT" 1755 elif manual: 1756 prop = "MANUAL" 1757 elif never: 1758 prop = "NEVER" 1759 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1761 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1762 no = expression.args.get("no") 1763 no = " NO" if no else "" 1764 concurrent = expression.args.get("concurrent") 1765 concurrent = " CONCURRENT" if concurrent else "" 1766 target = self.sql(expression, "target") 1767 target = f" {target}" if target else "" 1768 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1770 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1771 if isinstance(expression.this, list): 1772 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1773 if expression.this: 1774 modulus = self.sql(expression, "this") 1775 remainder = self.sql(expression, "expression") 1776 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1777 1778 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1779 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1780 return f"FROM ({from_expressions}) TO ({to_expressions})"
1782 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1783 this = self.sql(expression, "this") 1784 1785 for_values_or_default = expression.expression 1786 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1787 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1788 else: 1789 for_values_or_default = " DEFAULT" 1790 1791 return f"PARTITION OF {this}{for_values_or_default}"
1793 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1794 kind = expression.args.get("kind") 1795 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1796 for_or_in = expression.args.get("for_or_in") 1797 for_or_in = f" {for_or_in}" if for_or_in else "" 1798 lock_type = expression.args.get("lock_type") 1799 override = " OVERRIDE" if expression.args.get("override") else "" 1800 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1802 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1803 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1804 statistics = expression.args.get("statistics") 1805 statistics_sql = "" 1806 if statistics is not None: 1807 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1808 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1810 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1811 this = self.sql(expression, "this") 1812 this = f"HISTORY_TABLE={this}" if this else "" 1813 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1814 data_consistency = ( 1815 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1816 ) 1817 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1818 retention_period = ( 1819 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1820 ) 1821 1822 if this: 1823 on_sql = self.func("ON", this, data_consistency, retention_period) 1824 else: 1825 on_sql = "ON" if expression.args.get("on") else "OFF" 1826 1827 sql = f"SYSTEM_VERSIONING={on_sql}" 1828 1829 return f"WITH({sql})" if expression.args.get("with") else sql
1831 def insert_sql(self, expression: exp.Insert) -> str: 1832 hint = self.sql(expression, "hint") 1833 overwrite = expression.args.get("overwrite") 1834 1835 if isinstance(expression.this, exp.Directory): 1836 this = " OVERWRITE" if overwrite else " INTO" 1837 else: 1838 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1839 1840 stored = self.sql(expression, "stored") 1841 stored = f" {stored}" if stored else "" 1842 alternative = expression.args.get("alternative") 1843 alternative = f" OR {alternative}" if alternative else "" 1844 ignore = " IGNORE" if expression.args.get("ignore") else "" 1845 is_function = expression.args.get("is_function") 1846 if is_function: 1847 this = f"{this} FUNCTION" 1848 this = f"{this} {self.sql(expression, 'this')}" 1849 1850 exists = " IF EXISTS" if expression.args.get("exists") else "" 1851 where = self.sql(expression, "where") 1852 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1853 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1854 on_conflict = self.sql(expression, "conflict") 1855 on_conflict = f" {on_conflict}" if on_conflict else "" 1856 by_name = " BY NAME" if expression.args.get("by_name") else "" 1857 returning = self.sql(expression, "returning") 1858 1859 if self.RETURNING_END: 1860 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1861 else: 1862 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1863 1864 partition_by = self.sql(expression, "partition") 1865 partition_by = f" {partition_by}" if partition_by else "" 1866 settings = self.sql(expression, "settings") 1867 settings = f" {settings}" if settings else "" 1868 1869 source = self.sql(expression, "source") 1870 source = f"TABLE {source}" if source else "" 1871 1872 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1873 return self.prepend_ctes(expression, sql)
1891 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1892 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1893 1894 constraint = self.sql(expression, "constraint") 1895 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1896 1897 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1898 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1899 action = self.sql(expression, "action") 1900 1901 expressions = self.expressions(expression, flat=True) 1902 if expressions: 1903 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1904 expressions = f" {set_keyword}{expressions}" 1905 1906 where = self.sql(expression, "where") 1907 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1912 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1913 fields = self.sql(expression, "fields") 1914 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1915 escaped = self.sql(expression, "escaped") 1916 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1917 items = self.sql(expression, "collection_items") 1918 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1919 keys = self.sql(expression, "map_keys") 1920 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1921 lines = self.sql(expression, "lines") 1922 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1923 null = self.sql(expression, "null") 1924 null = f" NULL DEFINED AS {null}" if null else "" 1925 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1953 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1954 table = self.table_parts(expression) 1955 only = "ONLY " if expression.args.get("only") else "" 1956 partition = self.sql(expression, "partition") 1957 partition = f" {partition}" if partition else "" 1958 version = self.sql(expression, "version") 1959 version = f" {version}" if version else "" 1960 alias = self.sql(expression, "alias") 1961 alias = f"{sep}{alias}" if alias else "" 1962 1963 sample = self.sql(expression, "sample") 1964 if self.dialect.ALIAS_POST_TABLESAMPLE: 1965 sample_pre_alias = sample 1966 sample_post_alias = "" 1967 else: 1968 sample_pre_alias = "" 1969 sample_post_alias = sample 1970 1971 hints = self.expressions(expression, key="hints", sep=" ") 1972 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1973 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1974 joins = self.indent( 1975 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1976 ) 1977 laterals = self.expressions(expression, key="laterals", sep="") 1978 1979 file_format = self.sql(expression, "format") 1980 if file_format: 1981 pattern = self.sql(expression, "pattern") 1982 pattern = f", PATTERN => {pattern}" if pattern else "" 1983 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1984 1985 ordinality = expression.args.get("ordinality") or "" 1986 if ordinality: 1987 ordinality = f" WITH ORDINALITY{alias}" 1988 alias = "" 1989 1990 when = self.sql(expression, "when") 1991 if when: 1992 table = f"{table} {when}" 1993 1994 changes = self.sql(expression, "changes") 1995 changes = f" {changes}" if changes else "" 1996 1997 rows_from = self.expressions(expression, key="rows_from") 1998 if rows_from: 1999 table = f"ROWS FROM {self.wrap(rows_from)}" 2000 2001 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
2003 def tablefromrows_sql(self, expression: exp.TableFromRows) -> str: 2004 table = self.func("TABLE", expression.this) 2005 alias = self.sql(expression, "alias") 2006 alias = f" AS {alias}" if alias else "" 2007 sample = self.sql(expression, "sample") 2008 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2009 joins = self.indent( 2010 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 2011 ) 2012 return f"{table}{alias}{pivots}{sample}{joins}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
2014 def tablesample_sql( 2015 self, 2016 expression: exp.TableSample, 2017 tablesample_keyword: t.Optional[str] = None, 2018 ) -> str: 2019 method = self.sql(expression, "method") 2020 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 2021 numerator = self.sql(expression, "bucket_numerator") 2022 denominator = self.sql(expression, "bucket_denominator") 2023 field = self.sql(expression, "bucket_field") 2024 field = f" ON {field}" if field else "" 2025 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 2026 seed = self.sql(expression, "seed") 2027 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 2028 2029 size = self.sql(expression, "size") 2030 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 2031 size = f"{size} ROWS" 2032 2033 percent = self.sql(expression, "percent") 2034 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 2035 percent = f"{percent} PERCENT" 2036 2037 expr = f"{bucket}{percent}{size}" 2038 if self.TABLESAMPLE_REQUIRES_PARENS: 2039 expr = f"({expr})" 2040 2041 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
2043 def pivot_sql(self, expression: exp.Pivot) -> str: 2044 expressions = self.expressions(expression, flat=True) 2045 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2046 2047 if expression.this: 2048 this = self.sql(expression, "this") 2049 if not expressions: 2050 return f"UNPIVOT {this}" 2051 2052 on = f"{self.seg('ON')} {expressions}" 2053 into = self.sql(expression, "into") 2054 into = f"{self.seg('INTO')} {into}" if into else "" 2055 using = self.expressions(expression, key="using", flat=True) 2056 using = f"{self.seg('USING')} {using}" if using else "" 2057 group = self.sql(expression, "group") 2058 return f"{direction} {this}{on}{into}{using}{group}" 2059 2060 alias = self.sql(expression, "alias") 2061 alias = f" AS {alias}" if alias else "" 2062 2063 field = self.sql(expression, "field") 2064 2065 include_nulls = expression.args.get("include_nulls") 2066 if include_nulls is not None: 2067 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2068 else: 2069 nulls = "" 2070 2071 default_on_null = self.sql(expression, "default_on_null") 2072 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2073 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
2084 def update_sql(self, expression: exp.Update) -> str: 2085 this = self.sql(expression, "this") 2086 set_sql = self.expressions(expression, flat=True) 2087 from_sql = self.sql(expression, "from") 2088 where_sql = self.sql(expression, "where") 2089 returning = self.sql(expression, "returning") 2090 order = self.sql(expression, "order") 2091 limit = self.sql(expression, "limit") 2092 if self.RETURNING_END: 2093 expression_sql = f"{from_sql}{where_sql}{returning}" 2094 else: 2095 expression_sql = f"{returning}{from_sql}{where_sql}" 2096 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2097 return self.prepend_ctes(expression, sql)
2099 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2100 values_as_table = values_as_table and self.VALUES_AS_TABLE 2101 2102 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2103 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2104 args = self.expressions(expression) 2105 alias = self.sql(expression, "alias") 2106 values = f"VALUES{self.seg('')}{args}" 2107 values = ( 2108 f"({values})" 2109 if self.WRAP_DERIVED_VALUES 2110 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2111 else values 2112 ) 2113 return f"{values} AS {alias}" if alias else values 2114 2115 # Converts `VALUES...` expression into a series of select unions. 2116 alias_node = expression.args.get("alias") 2117 column_names = alias_node and alias_node.columns 2118 2119 selects: t.List[exp.Query] = [] 2120 2121 for i, tup in enumerate(expression.expressions): 2122 row = tup.expressions 2123 2124 if i == 0 and column_names: 2125 row = [ 2126 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2127 ] 2128 2129 selects.append(exp.Select(expressions=row)) 2130 2131 if self.pretty: 2132 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2133 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2134 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2135 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2136 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2137 2138 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2139 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2140 return f"({unions}){alias}"
2145 @unsupported_args("expressions") 2146 def into_sql(self, expression: exp.Into) -> str: 2147 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2148 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2149 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2166 def group_sql(self, expression: exp.Group) -> str: 2167 group_by_all = expression.args.get("all") 2168 if group_by_all is True: 2169 modifier = " ALL" 2170 elif group_by_all is False: 2171 modifier = " DISTINCT" 2172 else: 2173 modifier = "" 2174 2175 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2176 2177 grouping_sets = self.expressions(expression, key="grouping_sets") 2178 cube = self.expressions(expression, key="cube") 2179 rollup = self.expressions(expression, key="rollup") 2180 2181 groupings = csv( 2182 self.seg(grouping_sets) if grouping_sets else "", 2183 self.seg(cube) if cube else "", 2184 self.seg(rollup) if rollup else "", 2185 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2186 sep=self.GROUPINGS_SEP, 2187 ) 2188 2189 if ( 2190 expression.expressions 2191 and groupings 2192 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2193 ): 2194 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2195 2196 return f"{group_by}{groupings}"
2202 def connect_sql(self, expression: exp.Connect) -> str: 2203 start = self.sql(expression, "start") 2204 start = self.seg(f"START WITH {start}") if start else "" 2205 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2206 connect = self.sql(expression, "connect") 2207 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2208 return start + connect
2213 def join_sql(self, expression: exp.Join) -> str: 2214 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2215 side = None 2216 else: 2217 side = expression.side 2218 2219 op_sql = " ".join( 2220 op 2221 for op in ( 2222 expression.method, 2223 "GLOBAL" if expression.args.get("global") else None, 2224 side, 2225 expression.kind, 2226 expression.hint if self.JOIN_HINTS else None, 2227 ) 2228 if op 2229 ) 2230 match_cond = self.sql(expression, "match_condition") 2231 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2232 on_sql = self.sql(expression, "on") 2233 using = expression.args.get("using") 2234 2235 if not on_sql and using: 2236 on_sql = csv(*(self.sql(column) for column in using)) 2237 2238 this = expression.this 2239 this_sql = self.sql(this) 2240 2241 exprs = self.expressions(expression) 2242 if exprs: 2243 this_sql = f"{this_sql},{self.seg(exprs)}" 2244 2245 if on_sql: 2246 on_sql = self.indent(on_sql, skip_first=True) 2247 space = self.seg(" " * self.pad) if self.pretty else " " 2248 if using: 2249 on_sql = f"{space}USING ({on_sql})" 2250 else: 2251 on_sql = f"{space}ON {on_sql}" 2252 elif not op_sql: 2253 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2254 return f" {this_sql}" 2255 2256 return f", {this_sql}" 2257 2258 if op_sql != "STRAIGHT_JOIN": 2259 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2260 2261 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2268 def lateral_op(self, expression: exp.Lateral) -> str: 2269 cross_apply = expression.args.get("cross_apply") 2270 2271 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2272 if cross_apply is True: 2273 op = "INNER JOIN " 2274 elif cross_apply is False: 2275 op = "LEFT JOIN " 2276 else: 2277 op = "" 2278 2279 return f"{op}LATERAL"
2281 def lateral_sql(self, expression: exp.Lateral) -> str: 2282 this = self.sql(expression, "this") 2283 2284 if expression.args.get("view"): 2285 alias = expression.args["alias"] 2286 columns = self.expressions(alias, key="columns", flat=True) 2287 table = f" {alias.name}" if alias.name else "" 2288 columns = f" AS {columns}" if columns else "" 2289 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2290 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2291 2292 alias = self.sql(expression, "alias") 2293 alias = f" AS {alias}" if alias else "" 2294 return f"{self.lateral_op(expression)} {this}{alias}"
2296 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2297 this = self.sql(expression, "this") 2298 2299 args = [ 2300 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2301 for e in (expression.args.get(k) for k in ("offset", "expression")) 2302 if e 2303 ] 2304 2305 args_sql = ", ".join(self.sql(e) for e in args) 2306 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2307 expressions = self.expressions(expression, flat=True) 2308 limit_options = self.sql(expression, "limit_options") 2309 expressions = f" BY {expressions}" if expressions else "" 2310 2311 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{limit_options}{expressions}"
2313 def offset_sql(self, expression: exp.Offset) -> str: 2314 this = self.sql(expression, "this") 2315 value = expression.expression 2316 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2317 expressions = self.expressions(expression, flat=True) 2318 expressions = f" BY {expressions}" if expressions else "" 2319 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2321 def setitem_sql(self, expression: exp.SetItem) -> str: 2322 kind = self.sql(expression, "kind") 2323 kind = f"{kind} " if kind else "" 2324 this = self.sql(expression, "this") 2325 expressions = self.expressions(expression) 2326 collate = self.sql(expression, "collate") 2327 collate = f" COLLATE {collate}" if collate else "" 2328 global_ = "GLOBAL " if expression.args.get("global") else "" 2329 return f"{global_}{kind}{this}{expressions}{collate}"
2339 def lock_sql(self, expression: exp.Lock) -> str: 2340 if not self.LOCKING_READS_SUPPORTED: 2341 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2342 return "" 2343 2344 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2345 expressions = self.expressions(expression, flat=True) 2346 expressions = f" OF {expressions}" if expressions else "" 2347 wait = expression.args.get("wait") 2348 2349 if wait is not None: 2350 if isinstance(wait, exp.Literal): 2351 wait = f" WAIT {self.sql(wait)}" 2352 else: 2353 wait = " NOWAIT" if wait else " SKIP LOCKED" 2354 2355 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2363 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2364 if self.dialect.ESCAPED_SEQUENCES: 2365 to_escaped = self.dialect.ESCAPED_SEQUENCES 2366 text = "".join( 2367 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2368 ) 2369 2370 return self._replace_line_breaks(text).replace( 2371 self.dialect.QUOTE_END, self._escaped_quote_end 2372 )
2374 def loaddata_sql(self, expression: exp.LoadData) -> str: 2375 local = " LOCAL" if expression.args.get("local") else "" 2376 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2377 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2378 this = f" INTO TABLE {self.sql(expression, 'this')}" 2379 partition = self.sql(expression, "partition") 2380 partition = f" {partition}" if partition else "" 2381 input_format = self.sql(expression, "input_format") 2382 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2383 serde = self.sql(expression, "serde") 2384 serde = f" SERDE {serde}" if serde else "" 2385 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2393 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2394 this = self.sql(expression, "this") 2395 this = f"{this} " if this else this 2396 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2397 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2399 def withfill_sql(self, expression: exp.WithFill) -> str: 2400 from_sql = self.sql(expression, "from") 2401 from_sql = f" FROM {from_sql}" if from_sql else "" 2402 to_sql = self.sql(expression, "to") 2403 to_sql = f" TO {to_sql}" if to_sql else "" 2404 step_sql = self.sql(expression, "step") 2405 step_sql = f" STEP {step_sql}" if step_sql else "" 2406 interpolated_values = [ 2407 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2408 if isinstance(e, exp.Alias) 2409 else self.sql(e, "this") 2410 for e in expression.args.get("interpolate") or [] 2411 ] 2412 interpolate = ( 2413 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2414 ) 2415 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2426 def ordered_sql(self, expression: exp.Ordered) -> str: 2427 desc = expression.args.get("desc") 2428 asc = not desc 2429 2430 nulls_first = expression.args.get("nulls_first") 2431 nulls_last = not nulls_first 2432 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2433 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2434 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2435 2436 this = self.sql(expression, "this") 2437 2438 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2439 nulls_sort_change = "" 2440 if nulls_first and ( 2441 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2442 ): 2443 nulls_sort_change = " NULLS FIRST" 2444 elif ( 2445 nulls_last 2446 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2447 and not nulls_are_last 2448 ): 2449 nulls_sort_change = " NULLS LAST" 2450 2451 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2452 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2453 window = expression.find_ancestor(exp.Window, exp.Select) 2454 if isinstance(window, exp.Window) and window.args.get("spec"): 2455 self.unsupported( 2456 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2457 ) 2458 nulls_sort_change = "" 2459 elif self.NULL_ORDERING_SUPPORTED is False and ( 2460 (asc and nulls_sort_change == " NULLS LAST") 2461 or (desc and nulls_sort_change == " NULLS FIRST") 2462 ): 2463 # BigQuery does not allow these ordering/nulls combinations when used under 2464 # an aggregation func or under a window containing one 2465 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2466 2467 if isinstance(ancestor, exp.Window): 2468 ancestor = ancestor.this 2469 if isinstance(ancestor, exp.AggFunc): 2470 self.unsupported( 2471 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2472 ) 2473 nulls_sort_change = "" 2474 elif self.NULL_ORDERING_SUPPORTED is None: 2475 if expression.this.is_int: 2476 self.unsupported( 2477 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2478 ) 2479 elif not isinstance(expression.this, exp.Rand): 2480 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2481 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2482 nulls_sort_change = "" 2483 2484 with_fill = self.sql(expression, "with_fill") 2485 with_fill = f" {with_fill}" if with_fill else "" 2486 2487 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2497 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2498 partition = self.partition_by_sql(expression) 2499 order = self.sql(expression, "order") 2500 measures = self.expressions(expression, key="measures") 2501 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2502 rows = self.sql(expression, "rows") 2503 rows = self.seg(rows) if rows else "" 2504 after = self.sql(expression, "after") 2505 after = self.seg(after) if after else "" 2506 pattern = self.sql(expression, "pattern") 2507 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2508 definition_sqls = [ 2509 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2510 for definition in expression.args.get("define", []) 2511 ] 2512 definitions = self.expressions(sqls=definition_sqls) 2513 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2514 body = "".join( 2515 ( 2516 partition, 2517 order, 2518 measures, 2519 rows, 2520 after, 2521 pattern, 2522 define, 2523 ) 2524 ) 2525 alias = self.sql(expression, "alias") 2526 alias = f" {alias}" if alias else "" 2527 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2529 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2530 limit = expression.args.get("limit") 2531 2532 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2533 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2534 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2535 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2536 2537 return csv( 2538 *sqls, 2539 *[self.sql(join) for join in expression.args.get("joins") or []], 2540 self.sql(expression, "match"), 2541 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2542 self.sql(expression, "prewhere"), 2543 self.sql(expression, "where"), 2544 self.sql(expression, "connect"), 2545 self.sql(expression, "group"), 2546 self.sql(expression, "having"), 2547 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2548 self.sql(expression, "order"), 2549 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2550 *self.after_limit_modifiers(expression), 2551 self.options_modifier(expression), 2552 sep="", 2553 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2562 def offset_limit_modifiers( 2563 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2564 ) -> t.List[str]: 2565 return [ 2566 self.sql(expression, "offset") if fetch else self.sql(limit), 2567 self.sql(limit) if fetch else self.sql(expression, "offset"), 2568 ]
2575 def select_sql(self, expression: exp.Select) -> str: 2576 into = expression.args.get("into") 2577 if not self.SUPPORTS_SELECT_INTO and into: 2578 into.pop() 2579 2580 hint = self.sql(expression, "hint") 2581 distinct = self.sql(expression, "distinct") 2582 distinct = f" {distinct}" if distinct else "" 2583 kind = self.sql(expression, "kind") 2584 2585 limit = expression.args.get("limit") 2586 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2587 top = self.limit_sql(limit, top=True) 2588 limit.pop() 2589 else: 2590 top = "" 2591 2592 expressions = self.expressions(expression) 2593 2594 if kind: 2595 if kind in self.SELECT_KINDS: 2596 kind = f" AS {kind}" 2597 else: 2598 if kind == "STRUCT": 2599 expressions = self.expressions( 2600 sqls=[ 2601 self.sql( 2602 exp.Struct( 2603 expressions=[ 2604 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2605 if isinstance(e, exp.Alias) 2606 else e 2607 for e in expression.expressions 2608 ] 2609 ) 2610 ) 2611 ] 2612 ) 2613 kind = "" 2614 2615 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2616 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2617 2618 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2619 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2620 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2621 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2622 sql = self.query_modifiers( 2623 expression, 2624 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2625 self.sql(expression, "into", comment=False), 2626 self.sql(expression, "from", comment=False), 2627 ) 2628 2629 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2630 if expression.args.get("with"): 2631 sql = self.maybe_comment(sql, expression) 2632 expression.pop_comments() 2633 2634 sql = self.prepend_ctes(expression, sql) 2635 2636 if not self.SUPPORTS_SELECT_INTO and into: 2637 if into.args.get("temporary"): 2638 table_kind = " TEMPORARY" 2639 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2640 table_kind = " UNLOGGED" 2641 else: 2642 table_kind = "" 2643 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2644 2645 return sql
2657 def star_sql(self, expression: exp.Star) -> str: 2658 except_ = self.expressions(expression, key="except", flat=True) 2659 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2660 replace = self.expressions(expression, key="replace", flat=True) 2661 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2662 rename = self.expressions(expression, key="rename", flat=True) 2663 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2664 return f"*{except_}{replace}{rename}"
2680 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2681 alias = self.sql(expression, "alias") 2682 alias = f"{sep}{alias}" if alias else "" 2683 sample = self.sql(expression, "sample") 2684 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2685 alias = f"{sample}{alias}" 2686 2687 # Set to None so it's not generated again by self.query_modifiers() 2688 expression.set("sample", None) 2689 2690 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2691 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2692 return self.prepend_ctes(expression, sql)
2698 def unnest_sql(self, expression: exp.Unnest) -> str: 2699 args = self.expressions(expression, flat=True) 2700 2701 alias = expression.args.get("alias") 2702 offset = expression.args.get("offset") 2703 2704 if self.UNNEST_WITH_ORDINALITY: 2705 if alias and isinstance(offset, exp.Expression): 2706 alias.append("columns", offset) 2707 2708 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2709 columns = alias.columns 2710 alias = self.sql(columns[0]) if columns else "" 2711 else: 2712 alias = self.sql(alias) 2713 2714 alias = f" AS {alias}" if alias else alias 2715 if self.UNNEST_WITH_ORDINALITY: 2716 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2717 else: 2718 if isinstance(offset, exp.Expression): 2719 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2720 elif offset: 2721 suffix = f"{alias} WITH OFFSET" 2722 else: 2723 suffix = alias 2724 2725 return f"UNNEST({args}){suffix}"
2734 def window_sql(self, expression: exp.Window) -> str: 2735 this = self.sql(expression, "this") 2736 partition = self.partition_by_sql(expression) 2737 order = expression.args.get("order") 2738 order = self.order_sql(order, flat=True) if order else "" 2739 spec = self.sql(expression, "spec") 2740 alias = self.sql(expression, "alias") 2741 over = self.sql(expression, "over") or "OVER" 2742 2743 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2744 2745 first = expression.args.get("first") 2746 if first is None: 2747 first = "" 2748 else: 2749 first = "FIRST" if first else "LAST" 2750 2751 if not partition and not order and not spec and alias: 2752 return f"{this} {alias}" 2753 2754 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2755 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2761 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2762 kind = self.sql(expression, "kind") 2763 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2764 end = ( 2765 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2766 or "CURRENT ROW" 2767 ) 2768 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]:
2781 def bracket_offset_expressions( 2782 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2783 ) -> t.List[exp.Expression]: 2784 return apply_index_offset( 2785 expression.this, 2786 expression.expressions, 2787 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2788 )
2798 def any_sql(self, expression: exp.Any) -> str: 2799 this = self.sql(expression, "this") 2800 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2801 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2802 this = self.wrap(this) 2803 return f"ANY{this}" 2804 return f"ANY {this}"
2809 def case_sql(self, expression: exp.Case) -> str: 2810 this = self.sql(expression, "this") 2811 statements = [f"CASE {this}" if this else "CASE"] 2812 2813 for e in expression.args["ifs"]: 2814 statements.append(f"WHEN {self.sql(e, 'this')}") 2815 statements.append(f"THEN {self.sql(e, 'true')}") 2816 2817 default = self.sql(expression, "default") 2818 2819 if default: 2820 statements.append(f"ELSE {default}") 2821 2822 statements.append("END") 2823 2824 if self.pretty and self.too_wide(statements): 2825 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2826 2827 return " ".join(statements)
2844 def trim_sql(self, expression: exp.Trim) -> str: 2845 trim_type = self.sql(expression, "position") 2846 2847 if trim_type == "LEADING": 2848 func_name = "LTRIM" 2849 elif trim_type == "TRAILING": 2850 func_name = "RTRIM" 2851 else: 2852 func_name = "TRIM" 2853 2854 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]:
2856 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2857 args = expression.expressions 2858 if isinstance(expression, exp.ConcatWs): 2859 args = args[1:] # Skip the delimiter 2860 2861 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2862 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2863 2864 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2865 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2866 2867 return args
2869 def concat_sql(self, expression: exp.Concat) -> str: 2870 expressions = self.convert_concat_args(expression) 2871 2872 # Some dialects don't allow a single-argument CONCAT call 2873 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2874 return self.sql(expressions[0]) 2875 2876 return self.func("CONCAT", *expressions)
2887 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2888 expressions = self.expressions(expression, flat=True) 2889 expressions = f" ({expressions})" if expressions else "" 2890 reference = self.sql(expression, "reference") 2891 reference = f" {reference}" if reference else "" 2892 delete = self.sql(expression, "delete") 2893 delete = f" ON DELETE {delete}" if delete else "" 2894 update = self.sql(expression, "update") 2895 update = f" ON UPDATE {update}" if update else "" 2896 return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
2898 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2899 expressions = self.expressions(expression, flat=True) 2900 options = self.expressions(expression, key="options", flat=True, sep=" ") 2901 options = f" {options}" if options else "" 2902 return f"PRIMARY KEY ({expressions}){options}"
2915 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2916 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2917 2918 if expression.args.get("escape"): 2919 path = self.escape_str(path) 2920 2921 if self.QUOTE_JSON_PATH: 2922 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2923 2924 return path
2926 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2927 if isinstance(expression, exp.JSONPathPart): 2928 transform = self.TRANSFORMS.get(expression.__class__) 2929 if not callable(transform): 2930 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2931 return "" 2932 2933 return transform(self, expression) 2934 2935 if isinstance(expression, int): 2936 return str(expression) 2937 2938 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2939 escaped = expression.replace("'", "\\'") 2940 escaped = f"\\'{expression}\\'" 2941 else: 2942 escaped = expression.replace('"', '\\"') 2943 escaped = f'"{escaped}"' 2944 2945 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2950 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2951 null_handling = expression.args.get("null_handling") 2952 null_handling = f" {null_handling}" if null_handling else "" 2953 2954 unique_keys = expression.args.get("unique_keys") 2955 if unique_keys is not None: 2956 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2957 else: 2958 unique_keys = "" 2959 2960 return_type = self.sql(expression, "return_type") 2961 return_type = f" RETURNING {return_type}" if return_type else "" 2962 encoding = self.sql(expression, "encoding") 2963 encoding = f" ENCODING {encoding}" if encoding else "" 2964 2965 return self.func( 2966 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2967 *expression.expressions, 2968 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2969 )
2974 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2975 null_handling = expression.args.get("null_handling") 2976 null_handling = f" {null_handling}" if null_handling else "" 2977 return_type = self.sql(expression, "return_type") 2978 return_type = f" RETURNING {return_type}" if return_type else "" 2979 strict = " STRICT" if expression.args.get("strict") else "" 2980 return self.func( 2981 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2982 )
2984 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2985 this = self.sql(expression, "this") 2986 order = self.sql(expression, "order") 2987 null_handling = expression.args.get("null_handling") 2988 null_handling = f" {null_handling}" if null_handling else "" 2989 return_type = self.sql(expression, "return_type") 2990 return_type = f" RETURNING {return_type}" if return_type else "" 2991 strict = " STRICT" if expression.args.get("strict") else "" 2992 return self.func( 2993 "JSON_ARRAYAGG", 2994 this, 2995 suffix=f"{order}{null_handling}{return_type}{strict})", 2996 )
2998 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2999 path = self.sql(expression, "path") 3000 path = f" PATH {path}" if path else "" 3001 nested_schema = self.sql(expression, "nested_schema") 3002 3003 if nested_schema: 3004 return f"NESTED{path} {nested_schema}" 3005 3006 this = self.sql(expression, "this") 3007 kind = self.sql(expression, "kind") 3008 kind = f" {kind}" if kind else "" 3009 return f"{this}{kind}{path}"
3014 def jsontable_sql(self, expression: exp.JSONTable) -> str: 3015 this = self.sql(expression, "this") 3016 path = self.sql(expression, "path") 3017 path = f", {path}" if path else "" 3018 error_handling = expression.args.get("error_handling") 3019 error_handling = f" {error_handling}" if error_handling else "" 3020 empty_handling = expression.args.get("empty_handling") 3021 empty_handling = f" {empty_handling}" if empty_handling else "" 3022 schema = self.sql(expression, "schema") 3023 return self.func( 3024 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 3025 )
3027 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 3028 this = self.sql(expression, "this") 3029 kind = self.sql(expression, "kind") 3030 path = self.sql(expression, "path") 3031 path = f" {path}" if path else "" 3032 as_json = " AS JSON" if expression.args.get("as_json") else "" 3033 return f"{this} {kind}{path}{as_json}"
3035 def openjson_sql(self, expression: exp.OpenJSON) -> str: 3036 this = self.sql(expression, "this") 3037 path = self.sql(expression, "path") 3038 path = f", {path}" if path else "" 3039 expressions = self.expressions(expression) 3040 with_ = ( 3041 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 3042 if expressions 3043 else "" 3044 ) 3045 return f"OPENJSON({this}{path}){with_}"
3047 def in_sql(self, expression: exp.In) -> str: 3048 query = expression.args.get("query") 3049 unnest = expression.args.get("unnest") 3050 field = expression.args.get("field") 3051 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3052 3053 if query: 3054 in_sql = self.sql(query) 3055 elif unnest: 3056 in_sql = self.in_unnest_op(unnest) 3057 elif field: 3058 in_sql = self.sql(field) 3059 else: 3060 in_sql = f"({self.expressions(expression, flat=True)})" 3061 3062 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3067 def interval_sql(self, expression: exp.Interval) -> str: 3068 unit = self.sql(expression, "unit") 3069 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3070 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3071 unit = f" {unit}" if unit else "" 3072 3073 if self.SINGLE_STRING_INTERVAL: 3074 this = expression.this.name if expression.this else "" 3075 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3076 3077 this = self.sql(expression, "this") 3078 if this: 3079 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3080 this = f" {this}" if unwrapped else f" ({this})" 3081 3082 return f"INTERVAL{this}{unit}"
3087 def reference_sql(self, expression: exp.Reference) -> str: 3088 this = self.sql(expression, "this") 3089 expressions = self.expressions(expression, flat=True) 3090 expressions = f"({expressions})" if expressions else "" 3091 options = self.expressions(expression, key="options", flat=True, sep=" ") 3092 options = f" {options}" if options else "" 3093 return f"REFERENCES {this}{expressions}{options}"
3095 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3096 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3097 parent = expression.parent 3098 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3099 return self.func( 3100 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3101 )
3121 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3122 alias = expression.args["alias"] 3123 3124 parent = expression.parent 3125 pivot = parent and parent.parent 3126 3127 if isinstance(pivot, exp.Pivot) and pivot.unpivot: 3128 identifier_alias = isinstance(alias, exp.Identifier) 3129 literal_alias = isinstance(alias, exp.Literal) 3130 3131 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3132 alias.replace(exp.Literal.string(alias.output_name)) 3133 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3134 alias.replace(exp.to_identifier(alias.output_name)) 3135 3136 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:
3174 def connector_sql( 3175 self, 3176 expression: exp.Connector, 3177 op: str, 3178 stack: t.Optional[t.List[str | exp.Expression]] = None, 3179 ) -> str: 3180 if stack is not None: 3181 if expression.expressions: 3182 stack.append(self.expressions(expression, sep=f" {op} ")) 3183 else: 3184 stack.append(expression.right) 3185 if expression.comments and self.comments: 3186 for comment in expression.comments: 3187 if comment: 3188 op += f" /*{self.pad_comment(comment)}*/" 3189 stack.extend((op, expression.left)) 3190 return op 3191 3192 stack = [expression] 3193 sqls: t.List[str] = [] 3194 ops = set() 3195 3196 while stack: 3197 node = stack.pop() 3198 if isinstance(node, exp.Connector): 3199 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3200 else: 3201 sql = self.sql(node) 3202 if sqls and sqls[-1] in ops: 3203 sqls[-1] += f" {sql}" 3204 else: 3205 sqls.append(sql) 3206 3207 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3208 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3228 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3229 format_sql = self.sql(expression, "format") 3230 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3231 to_sql = self.sql(expression, "to") 3232 to_sql = f" {to_sql}" if to_sql else "" 3233 action = self.sql(expression, "action") 3234 action = f" {action}" if action else "" 3235 default = self.sql(expression, "default") 3236 default = f" DEFAULT {default} ON CONVERSION ERROR" if default else "" 3237 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{default}{format_sql}{action})"
3251 def comment_sql(self, expression: exp.Comment) -> str: 3252 this = self.sql(expression, "this") 3253 kind = expression.args["kind"] 3254 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3255 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3256 expression_sql = self.sql(expression, "expression") 3257 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3259 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3260 this = self.sql(expression, "this") 3261 delete = " DELETE" if expression.args.get("delete") else "" 3262 recompress = self.sql(expression, "recompress") 3263 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3264 to_disk = self.sql(expression, "to_disk") 3265 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3266 to_volume = self.sql(expression, "to_volume") 3267 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3268 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3270 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3271 where = self.sql(expression, "where") 3272 group = self.sql(expression, "group") 3273 aggregates = self.expressions(expression, key="aggregates") 3274 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3275 3276 if not (where or group or aggregates) and len(expression.expressions) == 1: 3277 return f"TTL {self.expressions(expression, flat=True)}" 3278 3279 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3296 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3297 this = self.sql(expression, "this") 3298 3299 dtype = self.sql(expression, "dtype") 3300 if dtype: 3301 collate = self.sql(expression, "collate") 3302 collate = f" COLLATE {collate}" if collate else "" 3303 using = self.sql(expression, "using") 3304 using = f" USING {using}" if using else "" 3305 return f"ALTER COLUMN {this} {self.ALTER_SET_TYPE} {dtype}{collate}{using}" 3306 3307 default = self.sql(expression, "default") 3308 if default: 3309 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3310 3311 comment = self.sql(expression, "comment") 3312 if comment: 3313 return f"ALTER COLUMN {this} COMMENT {comment}" 3314 3315 visible = expression.args.get("visible") 3316 if visible: 3317 return f"ALTER COLUMN {this} SET {visible}" 3318 3319 allow_null = expression.args.get("allow_null") 3320 drop = expression.args.get("drop") 3321 3322 if not drop and not allow_null: 3323 self.unsupported("Unsupported ALTER COLUMN syntax") 3324 3325 if allow_null is not None: 3326 keyword = "DROP" if drop else "SET" 3327 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3328 3329 return f"ALTER COLUMN {this} DROP DEFAULT"
3345 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3346 compound = " COMPOUND" if expression.args.get("compound") else "" 3347 this = self.sql(expression, "this") 3348 expressions = self.expressions(expression, flat=True) 3349 expressions = f"({expressions})" if expressions else "" 3350 return f"ALTER{compound} SORTKEY {this or expressions}"
3352 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3353 if not self.RENAME_TABLE_WITH_DB: 3354 # Remove db from tables 3355 expression = expression.transform( 3356 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3357 ).assert_is(exp.AlterRename) 3358 this = self.sql(expression, "this") 3359 return f"RENAME TO {this}"
3371 def alter_sql(self, expression: exp.Alter) -> str: 3372 actions = expression.args["actions"] 3373 3374 if isinstance(actions[0], exp.ColumnDef): 3375 actions = self.add_column_sql(expression) 3376 elif isinstance(actions[0], exp.Schema): 3377 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3378 elif isinstance(actions[0], exp.Delete): 3379 actions = self.expressions(expression, key="actions", flat=True) 3380 elif isinstance(actions[0], exp.Query): 3381 actions = "AS " + self.expressions(expression, key="actions") 3382 else: 3383 actions = self.expressions(expression, key="actions", flat=True) 3384 3385 exists = " IF EXISTS" if expression.args.get("exists") else "" 3386 on_cluster = self.sql(expression, "cluster") 3387 on_cluster = f" {on_cluster}" if on_cluster else "" 3388 only = " ONLY" if expression.args.get("only") else "" 3389 options = self.expressions(expression, key="options") 3390 options = f", {options}" if options else "" 3391 kind = self.sql(expression, "kind") 3392 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3393 3394 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3396 def add_column_sql(self, expression: exp.Alter) -> str: 3397 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3398 return self.expressions( 3399 expression, 3400 key="actions", 3401 prefix="ADD COLUMN ", 3402 skip_first=True, 3403 ) 3404 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3414 def distinct_sql(self, expression: exp.Distinct) -> str: 3415 this = self.expressions(expression, flat=True) 3416 3417 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3418 case = exp.case() 3419 for arg in expression.expressions: 3420 case = case.when(arg.is_(exp.null()), exp.null()) 3421 this = self.sql(case.else_(f"({this})")) 3422 3423 this = f" {this}" if this else "" 3424 3425 on = self.sql(expression, "on") 3426 on = f" ON {on}" if on else "" 3427 return f"DISTINCT{this}{on}"
3456 def div_sql(self, expression: exp.Div) -> str: 3457 l, r = expression.left, expression.right 3458 3459 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3460 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3461 3462 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3463 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3464 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3465 3466 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3467 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3468 return self.sql( 3469 exp.cast( 3470 l / r, 3471 to=exp.DataType.Type.BIGINT, 3472 ) 3473 ) 3474 3475 return self.binary(expression, "/")
3571 def log_sql(self, expression: exp.Log) -> str: 3572 this = expression.this 3573 expr = expression.expression 3574 3575 if self.dialect.LOG_BASE_FIRST is False: 3576 this, expr = expr, this 3577 elif self.dialect.LOG_BASE_FIRST is None and expr: 3578 if this.name in ("2", "10"): 3579 return self.func(f"LOG{this.name}", expr) 3580 3581 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3582 3583 return self.func("LOG", this, expr)
3592 def binary(self, expression: exp.Binary, op: str) -> str: 3593 sqls: t.List[str] = [] 3594 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3595 binary_type = type(expression) 3596 3597 while stack: 3598 node = stack.pop() 3599 3600 if type(node) is binary_type: 3601 op_func = node.args.get("operator") 3602 if op_func: 3603 op = f"OPERATOR({self.sql(op_func)})" 3604 3605 stack.append(node.right) 3606 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3607 stack.append(node.left) 3608 else: 3609 sqls.append(self.sql(node)) 3610 3611 return "".join(sqls)
3620 def function_fallback_sql(self, expression: exp.Func) -> str: 3621 args = [] 3622 3623 for key in expression.arg_types: 3624 arg_value = expression.args.get(key) 3625 3626 if isinstance(arg_value, list): 3627 for value in arg_value: 3628 args.append(value) 3629 elif arg_value is not None: 3630 args.append(arg_value) 3631 3632 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3633 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3634 else: 3635 name = expression.sql_name() 3636 3637 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:
3639 def func( 3640 self, 3641 name: str, 3642 *args: t.Optional[exp.Expression | str], 3643 prefix: str = "(", 3644 suffix: str = ")", 3645 normalize: bool = True, 3646 ) -> str: 3647 name = self.normalize_func(name) if normalize else name 3648 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3650 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3651 arg_sqls = tuple( 3652 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3653 ) 3654 if self.pretty and self.too_wide(arg_sqls): 3655 return self.indent( 3656 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3657 ) 3658 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]:
3663 def format_time( 3664 self, 3665 expression: exp.Expression, 3666 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3667 inverse_time_trie: t.Optional[t.Dict] = None, 3668 ) -> t.Optional[str]: 3669 return format_time( 3670 self.sql(expression, "format"), 3671 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3672 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3673 )
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:
3675 def expressions( 3676 self, 3677 expression: t.Optional[exp.Expression] = None, 3678 key: t.Optional[str] = None, 3679 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3680 flat: bool = False, 3681 indent: bool = True, 3682 skip_first: bool = False, 3683 skip_last: bool = False, 3684 sep: str = ", ", 3685 prefix: str = "", 3686 dynamic: bool = False, 3687 new_line: bool = False, 3688 ) -> str: 3689 expressions = expression.args.get(key or "expressions") if expression else sqls 3690 3691 if not expressions: 3692 return "" 3693 3694 if flat: 3695 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3696 3697 num_sqls = len(expressions) 3698 result_sqls = [] 3699 3700 for i, e in enumerate(expressions): 3701 sql = self.sql(e, comment=False) 3702 if not sql: 3703 continue 3704 3705 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3706 3707 if self.pretty: 3708 if self.leading_comma: 3709 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3710 else: 3711 result_sqls.append( 3712 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3713 ) 3714 else: 3715 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3716 3717 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3718 if new_line: 3719 result_sqls.insert(0, "") 3720 result_sqls.append("") 3721 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3722 else: 3723 result_sql = "".join(result_sqls) 3724 3725 return ( 3726 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3727 if indent 3728 else result_sql 3729 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3731 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3732 flat = flat or isinstance(expression.parent, exp.Properties) 3733 expressions_sql = self.expressions(expression, flat=flat) 3734 if flat: 3735 return f"{op} {expressions_sql}" 3736 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3738 def naked_property(self, expression: exp.Property) -> str: 3739 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3740 if not property_name: 3741 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3742 return f"{property_name} {self.sql(expression, 'this')}"
3750 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3751 this = self.sql(expression, "this") 3752 expressions = self.no_identify(self.expressions, expression) 3753 expressions = ( 3754 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3755 ) 3756 return f"{this}{expressions}" if expressions.strip() != "" else this
3766 def when_sql(self, expression: exp.When) -> str: 3767 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3768 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3769 condition = self.sql(expression, "condition") 3770 condition = f" AND {condition}" if condition else "" 3771 3772 then_expression = expression.args.get("then") 3773 if isinstance(then_expression, exp.Insert): 3774 this = self.sql(then_expression, "this") 3775 this = f"INSERT {this}" if this else "INSERT" 3776 then = self.sql(then_expression, "expression") 3777 then = f"{this} VALUES {then}" if then else this 3778 elif isinstance(then_expression, exp.Update): 3779 if isinstance(then_expression.args.get("expressions"), exp.Star): 3780 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3781 else: 3782 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3783 else: 3784 then = self.sql(then_expression) 3785 return f"WHEN {matched}{source}{condition} THEN {then}"
3790 def merge_sql(self, expression: exp.Merge) -> str: 3791 table = expression.this 3792 table_alias = "" 3793 3794 hints = table.args.get("hints") 3795 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3796 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3797 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3798 3799 this = self.sql(table) 3800 using = f"USING {self.sql(expression, 'using')}" 3801 on = f"ON {self.sql(expression, 'on')}" 3802 whens = self.sql(expression, "whens") 3803 3804 returning = self.sql(expression, "returning") 3805 if returning: 3806 whens = f"{whens}{returning}" 3807 3808 sep = self.sep() 3809 3810 return self.prepend_ctes( 3811 expression, 3812 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3813 )
3819 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3820 if not self.SUPPORTS_TO_NUMBER: 3821 self.unsupported("Unsupported TO_NUMBER function") 3822 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3823 3824 fmt = expression.args.get("format") 3825 if not fmt: 3826 self.unsupported("Conversion format is required for TO_NUMBER") 3827 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3828 3829 return self.func("TO_NUMBER", expression.this, fmt)
3831 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3832 this = self.sql(expression, "this") 3833 kind = self.sql(expression, "kind") 3834 settings_sql = self.expressions(expression, key="settings", sep=" ") 3835 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3836 return f"{this}({kind}{args})"
3855 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3856 expressions = self.expressions(expression, flat=True) 3857 expressions = f" {self.wrap(expressions)}" if expressions else "" 3858 buckets = self.sql(expression, "buckets") 3859 kind = self.sql(expression, "kind") 3860 buckets = f" BUCKETS {buckets}" if buckets else "" 3861 order = self.sql(expression, "order") 3862 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3867 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3868 expressions = self.expressions(expression, key="expressions", flat=True) 3869 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3870 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3871 buckets = self.sql(expression, "buckets") 3872 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3874 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3875 this = self.sql(expression, "this") 3876 having = self.sql(expression, "having") 3877 3878 if having: 3879 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3880 3881 return self.func("ANY_VALUE", this)
3883 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3884 transform = self.func("TRANSFORM", *expression.expressions) 3885 row_format_before = self.sql(expression, "row_format_before") 3886 row_format_before = f" {row_format_before}" if row_format_before else "" 3887 record_writer = self.sql(expression, "record_writer") 3888 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3889 using = f" USING {self.sql(expression, 'command_script')}" 3890 schema = self.sql(expression, "schema") 3891 schema = f" AS {schema}" if schema else "" 3892 row_format_after = self.sql(expression, "row_format_after") 3893 row_format_after = f" {row_format_after}" if row_format_after else "" 3894 record_reader = self.sql(expression, "record_reader") 3895 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3896 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3898 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3899 key_block_size = self.sql(expression, "key_block_size") 3900 if key_block_size: 3901 return f"KEY_BLOCK_SIZE = {key_block_size}" 3902 3903 using = self.sql(expression, "using") 3904 if using: 3905 return f"USING {using}" 3906 3907 parser = self.sql(expression, "parser") 3908 if parser: 3909 return f"WITH PARSER {parser}" 3910 3911 comment = self.sql(expression, "comment") 3912 if comment: 3913 return f"COMMENT {comment}" 3914 3915 visible = expression.args.get("visible") 3916 if visible is not None: 3917 return "VISIBLE" if visible else "INVISIBLE" 3918 3919 engine_attr = self.sql(expression, "engine_attr") 3920 if engine_attr: 3921 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3922 3923 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3924 if secondary_engine_attr: 3925 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3926 3927 self.unsupported("Unsupported index constraint option.") 3928 return ""
3934 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3935 kind = self.sql(expression, "kind") 3936 kind = f"{kind} INDEX" if kind else "INDEX" 3937 this = self.sql(expression, "this") 3938 this = f" {this}" if this else "" 3939 index_type = self.sql(expression, "index_type") 3940 index_type = f" USING {index_type}" if index_type else "" 3941 expressions = self.expressions(expression, flat=True) 3942 expressions = f" ({expressions})" if expressions else "" 3943 options = self.expressions(expression, key="options", sep=" ") 3944 options = f" {options}" if options else "" 3945 return f"{kind}{this}{index_type}{expressions}{options}"
3947 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3948 if self.NVL2_SUPPORTED: 3949 return self.function_fallback_sql(expression) 3950 3951 case = exp.Case().when( 3952 expression.this.is_(exp.null()).not_(copy=False), 3953 expression.args["true"], 3954 copy=False, 3955 ) 3956 else_cond = expression.args.get("false") 3957 if else_cond: 3958 case.else_(else_cond, copy=False) 3959 3960 return self.sql(case)
3962 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3963 this = self.sql(expression, "this") 3964 expr = self.sql(expression, "expression") 3965 iterator = self.sql(expression, "iterator") 3966 condition = self.sql(expression, "condition") 3967 condition = f" IF {condition}" if condition else "" 3968 return f"{this} FOR {expr} IN {iterator}{condition}"
3976 def predict_sql(self, expression: exp.Predict) -> str: 3977 model = self.sql(expression, "this") 3978 model = f"MODEL {model}" 3979 table = self.sql(expression, "expression") 3980 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3981 parameters = self.sql(expression, "params_struct") 3982 return self.func("PREDICT", model, table, parameters or None)
3994 def toarray_sql(self, expression: exp.ToArray) -> str: 3995 arg = expression.this 3996 if not arg.type: 3997 from sqlglot.optimizer.annotate_types import annotate_types 3998 3999 arg = annotate_types(arg) 4000 4001 if arg.is_type(exp.DataType.Type.ARRAY): 4002 return self.sql(arg) 4003 4004 cond_for_null = arg.is_(exp.null()) 4005 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
4007 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 4008 this = expression.this 4009 time_format = self.format_time(expression) 4010 4011 if time_format: 4012 return self.sql( 4013 exp.cast( 4014 exp.StrToTime(this=this, format=expression.args["format"]), 4015 exp.DataType.Type.TIME, 4016 ) 4017 ) 4018 4019 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 4020 return self.sql(this) 4021 4022 return self.sql(exp.cast(this, exp.DataType.Type.TIME))
4024 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 4025 this = expression.this 4026 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 4027 return self.sql(this) 4028 4029 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
4031 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 4032 this = expression.this 4033 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 4034 return self.sql(this) 4035 4036 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
4038 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 4039 this = expression.this 4040 time_format = self.format_time(expression) 4041 4042 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 4043 return self.sql( 4044 exp.cast( 4045 exp.StrToTime(this=this, format=expression.args["format"]), 4046 exp.DataType.Type.DATE, 4047 ) 4048 ) 4049 4050 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 4051 return self.sql(this) 4052 4053 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
4065 def lastday_sql(self, expression: exp.LastDay) -> str: 4066 if self.LAST_DAY_SUPPORTS_DATE_PART: 4067 return self.function_fallback_sql(expression) 4068 4069 unit = expression.text("unit") 4070 if unit and unit != "MONTH": 4071 self.unsupported("Date parts are not supported in LAST_DAY.") 4072 4073 return self.func("LAST_DAY", expression.this)
4082 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4083 if self.CAN_IMPLEMENT_ARRAY_ANY: 4084 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4085 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4086 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4087 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4088 4089 from sqlglot.dialects import Dialect 4090 4091 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4092 if self.dialect.__class__ != Dialect: 4093 self.unsupported("ARRAY_ANY is unsupported") 4094 4095 return self.function_fallback_sql(expression)
4097 def struct_sql(self, expression: exp.Struct) -> str: 4098 expression.set( 4099 "expressions", 4100 [ 4101 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4102 if isinstance(e, exp.PropertyEQ) 4103 else e 4104 for e in expression.expressions 4105 ], 4106 ) 4107 4108 return self.function_fallback_sql(expression)
4116 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4117 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4118 tables = f" {self.expressions(expression)}" 4119 4120 exists = " IF EXISTS" if expression.args.get("exists") else "" 4121 4122 on_cluster = self.sql(expression, "cluster") 4123 on_cluster = f" {on_cluster}" if on_cluster else "" 4124 4125 identity = self.sql(expression, "identity") 4126 identity = f" {identity} IDENTITY" if identity else "" 4127 4128 option = self.sql(expression, "option") 4129 option = f" {option}" if option else "" 4130 4131 partition = self.sql(expression, "partition") 4132 partition = f" {partition}" if partition else "" 4133 4134 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4138 def convert_sql(self, expression: exp.Convert) -> str: 4139 to = expression.this 4140 value = expression.expression 4141 style = expression.args.get("style") 4142 safe = expression.args.get("safe") 4143 strict = expression.args.get("strict") 4144 4145 if not to or not value: 4146 return "" 4147 4148 # Retrieve length of datatype and override to default if not specified 4149 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4150 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4151 4152 transformed: t.Optional[exp.Expression] = None 4153 cast = exp.Cast if strict else exp.TryCast 4154 4155 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4156 if isinstance(style, exp.Literal) and style.is_int: 4157 from sqlglot.dialects.tsql import TSQL 4158 4159 style_value = style.name 4160 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4161 if not converted_style: 4162 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4163 4164 fmt = exp.Literal.string(converted_style) 4165 4166 if to.this == exp.DataType.Type.DATE: 4167 transformed = exp.StrToDate(this=value, format=fmt) 4168 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4169 transformed = exp.StrToTime(this=value, format=fmt) 4170 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4171 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4172 elif to.this == exp.DataType.Type.TEXT: 4173 transformed = exp.TimeToStr(this=value, format=fmt) 4174 4175 if not transformed: 4176 transformed = cast(this=value, to=to, safe=safe) 4177 4178 return self.sql(transformed)
4238 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4239 option = self.sql(expression, "this") 4240 4241 if expression.expressions: 4242 upper = option.upper() 4243 4244 # Snowflake FILE_FORMAT options are separated by whitespace 4245 sep = " " if upper == "FILE_FORMAT" else ", " 4246 4247 # Databricks copy/format options do not set their list of values with EQ 4248 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4249 values = self.expressions(expression, flat=True, sep=sep) 4250 return f"{option}{op}({values})" 4251 4252 value = self.sql(expression, "expression") 4253 4254 if not value: 4255 return option 4256 4257 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4258 4259 return f"{option}{op}{value}"
4261 def credentials_sql(self, expression: exp.Credentials) -> str: 4262 cred_expr = expression.args.get("credentials") 4263 if isinstance(cred_expr, exp.Literal): 4264 # Redshift case: CREDENTIALS <string> 4265 credentials = self.sql(expression, "credentials") 4266 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4267 else: 4268 # Snowflake case: CREDENTIALS = (...) 4269 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4270 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4271 4272 storage = self.sql(expression, "storage") 4273 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4274 4275 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4276 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4277 4278 iam_role = self.sql(expression, "iam_role") 4279 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4280 4281 region = self.sql(expression, "region") 4282 region = f" REGION {region}" if region else "" 4283 4284 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4286 def copy_sql(self, expression: exp.Copy) -> str: 4287 this = self.sql(expression, "this") 4288 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4289 4290 credentials = self.sql(expression, "credentials") 4291 credentials = self.seg(credentials) if credentials else "" 4292 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4293 files = self.expressions(expression, key="files", flat=True) 4294 4295 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4296 params = self.expressions( 4297 expression, 4298 key="params", 4299 sep=sep, 4300 new_line=True, 4301 skip_last=True, 4302 skip_first=True, 4303 indent=self.COPY_PARAMS_ARE_WRAPPED, 4304 ) 4305 4306 if params: 4307 if self.COPY_PARAMS_ARE_WRAPPED: 4308 params = f" WITH ({params})" 4309 elif not self.pretty: 4310 params = f" {params}" 4311 4312 return f"COPY{this}{kind} {files}{credentials}{params}"
4317 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4318 on_sql = "ON" if expression.args.get("on") else "OFF" 4319 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4320 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4321 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4322 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4323 4324 if filter_col or retention_period: 4325 on_sql = self.func("ON", filter_col, retention_period) 4326 4327 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4329 def maskingpolicycolumnconstraint_sql( 4330 self, expression: exp.MaskingPolicyColumnConstraint 4331 ) -> str: 4332 this = self.sql(expression, "this") 4333 expressions = self.expressions(expression, flat=True) 4334 expressions = f" USING ({expressions})" if expressions else "" 4335 return f"MASKING POLICY {this}{expressions}"
4345 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4346 this = self.sql(expression, "this") 4347 expr = expression.expression 4348 4349 if isinstance(expr, exp.Func): 4350 # T-SQL's CLR functions are case sensitive 4351 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4352 else: 4353 expr = self.sql(expression, "expression") 4354 4355 return self.scope_resolution(expr, this)
4363 def rand_sql(self, expression: exp.Rand) -> str: 4364 lower = self.sql(expression, "lower") 4365 upper = self.sql(expression, "upper") 4366 4367 if lower and upper: 4368 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4369 return self.func("RAND", expression.this)
4371 def changes_sql(self, expression: exp.Changes) -> str: 4372 information = self.sql(expression, "information") 4373 information = f"INFORMATION => {information}" 4374 at_before = self.sql(expression, "at_before") 4375 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4376 end = self.sql(expression, "end") 4377 end = f"{self.seg('')}{end}" if end else "" 4378 4379 return f"CHANGES ({information}){at_before}{end}"
4381 def pad_sql(self, expression: exp.Pad) -> str: 4382 prefix = "L" if expression.args.get("is_left") else "R" 4383 4384 fill_pattern = self.sql(expression, "fill_pattern") or None 4385 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4386 fill_pattern = "' '" 4387 4388 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4394 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4395 generate_series = exp.GenerateSeries(**expression.args) 4396 4397 parent = expression.parent 4398 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4399 parent = parent.parent 4400 4401 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4402 return self.sql(exp.Unnest(expressions=[generate_series])) 4403 4404 if isinstance(parent, exp.Select): 4405 self.unsupported("GenerateSeries projection unnesting is not supported.") 4406 4407 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4409 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4410 exprs = expression.expressions 4411 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4412 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4413 else: 4414 rhs = self.expressions(expression) 4415 4416 return self.func(name, expression.this, rhs or None)
4418 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4419 if self.SUPPORTS_CONVERT_TIMEZONE: 4420 return self.function_fallback_sql(expression) 4421 4422 source_tz = expression.args.get("source_tz") 4423 target_tz = expression.args.get("target_tz") 4424 timestamp = expression.args.get("timestamp") 4425 4426 if source_tz and timestamp: 4427 timestamp = exp.AtTimeZone( 4428 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4429 ) 4430 4431 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4432 4433 return self.sql(expr)
4435 def json_sql(self, expression: exp.JSON) -> str: 4436 this = self.sql(expression, "this") 4437 this = f" {this}" if this else "" 4438 4439 _with = expression.args.get("with") 4440 4441 if _with is None: 4442 with_sql = "" 4443 elif not _with: 4444 with_sql = " WITHOUT" 4445 else: 4446 with_sql = " WITH" 4447 4448 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4449 4450 return f"JSON{this}{with_sql}{unique_sql}"
4452 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4453 def _generate_on_options(arg: t.Any) -> str: 4454 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4455 4456 path = self.sql(expression, "path") 4457 returning = self.sql(expression, "returning") 4458 returning = f" RETURNING {returning}" if returning else "" 4459 4460 on_condition = self.sql(expression, "on_condition") 4461 on_condition = f" {on_condition}" if on_condition else "" 4462 4463 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4465 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4466 else_ = "ELSE " if expression.args.get("else_") else "" 4467 condition = self.sql(expression, "expression") 4468 condition = f"WHEN {condition} THEN " if condition else else_ 4469 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4470 return f"{condition}{insert}"
4478 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4479 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4480 empty = expression.args.get("empty") 4481 empty = ( 4482 f"DEFAULT {empty} ON EMPTY" 4483 if isinstance(empty, exp.Expression) 4484 else self.sql(expression, "empty") 4485 ) 4486 4487 error = expression.args.get("error") 4488 error = ( 4489 f"DEFAULT {error} ON ERROR" 4490 if isinstance(error, exp.Expression) 4491 else self.sql(expression, "error") 4492 ) 4493 4494 if error and empty: 4495 error = ( 4496 f"{empty} {error}" 4497 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4498 else f"{error} {empty}" 4499 ) 4500 empty = "" 4501 4502 null = self.sql(expression, "null") 4503 4504 return f"{empty}{error}{null}"
4510 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4511 this = self.sql(expression, "this") 4512 path = self.sql(expression, "path") 4513 4514 passing = self.expressions(expression, "passing") 4515 passing = f" PASSING {passing}" if passing else "" 4516 4517 on_condition = self.sql(expression, "on_condition") 4518 on_condition = f" {on_condition}" if on_condition else "" 4519 4520 path = f"{path}{passing}{on_condition}" 4521 4522 return self.func("JSON_EXISTS", this, path)
4524 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4525 array_agg = self.function_fallback_sql(expression) 4526 4527 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4528 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4529 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4530 parent = expression.parent 4531 if isinstance(parent, exp.Filter): 4532 parent_cond = parent.expression.this 4533 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4534 else: 4535 this = expression.this 4536 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4537 if this.find(exp.Column): 4538 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4539 this_sql = ( 4540 self.expressions(this) 4541 if isinstance(this, exp.Distinct) 4542 else self.sql(expression, "this") 4543 ) 4544 4545 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4546 4547 return array_agg
4555 def grant_sql(self, expression: exp.Grant) -> str: 4556 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4557 4558 kind = self.sql(expression, "kind") 4559 kind = f" {kind}" if kind else "" 4560 4561 securable = self.sql(expression, "securable") 4562 securable = f" {securable}" if securable else "" 4563 4564 principals = self.expressions(expression, key="principals", flat=True) 4565 4566 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4567 4568 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4592 def overlay_sql(self, expression: exp.Overlay): 4593 this = self.sql(expression, "this") 4594 expr = self.sql(expression, "expression") 4595 from_sql = self.sql(expression, "from") 4596 for_sql = self.sql(expression, "for") 4597 for_sql = f" FOR {for_sql}" if for_sql else "" 4598 4599 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4605 def string_sql(self, expression: exp.String) -> str: 4606 this = expression.this 4607 zone = expression.args.get("zone") 4608 4609 if zone: 4610 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4611 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4612 # set for source_tz to transpile the time conversion before the STRING cast 4613 this = exp.ConvertTimezone( 4614 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4615 ) 4616 4617 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4627 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4628 filler = self.sql(expression, "this") 4629 filler = f" {filler}" if filler else "" 4630 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4631 return f"TRUNCATE{filler} {with_count}"
4633 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4634 if self.SUPPORTS_UNIX_SECONDS: 4635 return self.function_fallback_sql(expression) 4636 4637 start_ts = exp.cast( 4638 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4639 ) 4640 4641 return self.sql( 4642 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4643 )
4645 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4646 dim = expression.expression 4647 4648 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4649 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4650 if not (dim.is_int and dim.name == "1"): 4651 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4652 dim = None 4653 4654 # If dimension is required but not specified, default initialize it 4655 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4656 dim = exp.Literal.number(1) 4657 4658 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4660 def attach_sql(self, expression: exp.Attach) -> str: 4661 this = self.sql(expression, "this") 4662 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4663 expressions = self.expressions(expression) 4664 expressions = f" ({expressions})" if expressions else "" 4665 4666 return f"ATTACH{exists_sql} {this}{expressions}"
4680 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4681 this_sql = self.sql(expression, "this") 4682 if isinstance(expression.this, exp.Table): 4683 this_sql = f"TABLE {this_sql}" 4684 4685 return self.func( 4686 "FEATURES_AT_TIME", 4687 this_sql, 4688 expression.args.get("time"), 4689 expression.args.get("num_rows"), 4690 expression.args.get("ignore_feature_nulls"), 4691 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4698 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4699 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4700 encode = f"{encode} {self.sql(expression, 'this')}" 4701 4702 properties = expression.args.get("properties") 4703 if properties: 4704 encode = f"{encode} {self.properties(properties)}" 4705 4706 return encode
4708 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4709 this = self.sql(expression, "this") 4710 include = f"INCLUDE {this}" 4711 4712 column_def = self.sql(expression, "column_def") 4713 if column_def: 4714 include = f"{include} {column_def}" 4715 4716 alias = self.sql(expression, "alias") 4717 if alias: 4718 include = f"{include} AS {alias}" 4719 4720 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4726 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4727 partitions = self.expressions(expression, "partition_expressions") 4728 create = self.expressions(expression, "create_expressions") 4729 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4731 def partitionbyrangepropertydynamic_sql( 4732 self, expression: exp.PartitionByRangePropertyDynamic 4733 ) -> str: 4734 start = self.sql(expression, "start") 4735 end = self.sql(expression, "end") 4736 4737 every = expression.args["every"] 4738 if isinstance(every, exp.Interval) and every.this.is_string: 4739 every.this.replace(exp.Literal.number(every.name)) 4740 4741 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4754 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4755 kind = self.sql(expression, "kind") 4756 option = self.sql(expression, "option") 4757 option = f" {option}" if option else "" 4758 this = self.sql(expression, "this") 4759 this = f" {this}" if this else "" 4760 columns = self.expressions(expression) 4761 columns = f" {columns}" if columns else "" 4762 return f"{kind}{option} STATISTICS{this}{columns}"
4764 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4765 this = self.sql(expression, "this") 4766 columns = self.expressions(expression) 4767 inner_expression = self.sql(expression, "expression") 4768 inner_expression = f" {inner_expression}" if inner_expression else "" 4769 update_options = self.sql(expression, "update_options") 4770 update_options = f" {update_options} UPDATE" if update_options else "" 4771 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4782 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4783 kind = self.sql(expression, "kind") 4784 this = self.sql(expression, "this") 4785 this = f" {this}" if this else "" 4786 inner_expression = self.sql(expression, "expression") 4787 return f"VALIDATE {kind}{this}{inner_expression}"
4789 def analyze_sql(self, expression: exp.Analyze) -> str: 4790 options = self.expressions(expression, key="options", sep=" ") 4791 options = f" {options}" if options else "" 4792 kind = self.sql(expression, "kind") 4793 kind = f" {kind}" if kind else "" 4794 this = self.sql(expression, "this") 4795 this = f" {this}" if this else "" 4796 mode = self.sql(expression, "mode") 4797 mode = f" {mode}" if mode else "" 4798 properties = self.sql(expression, "properties") 4799 properties = f" {properties}" if properties else "" 4800 partition = self.sql(expression, "partition") 4801 partition = f" {partition}" if partition else "" 4802 inner_expression = self.sql(expression, "expression") 4803 inner_expression = f" {inner_expression}" if inner_expression else "" 4804 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4806 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4807 this = self.sql(expression, "this") 4808 namespaces = self.expressions(expression, key="namespaces") 4809 namespaces = f"XMLNAMESPACES({namespaces}), " if namespaces else "" 4810 passing = self.expressions(expression, key="passing") 4811 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4812 columns = self.expressions(expression, key="columns") 4813 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4814 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4815 return f"XMLTABLE({self.sep('')}{self.indent(namespaces + this + passing + by_ref + columns)}{self.seg(')', sep='')}"
4821 def export_sql(self, expression: exp.Export) -> str: 4822 this = self.sql(expression, "this") 4823 connection = self.sql(expression, "connection") 4824 connection = f"WITH CONNECTION {connection} " if connection else "" 4825 options = self.sql(expression, "options") 4826 return f"EXPORT DATA {connection}{options} AS {this}"
4831 def declareitem_sql(self, expression: exp.DeclareItem) -> str: 4832 variable = self.sql(expression, "this") 4833 default = self.sql(expression, "default") 4834 default = f" = {default}" if default else "" 4835 4836 kind = self.sql(expression, "kind") 4837 if isinstance(expression.args.get("kind"), exp.Schema): 4838 kind = f"TABLE {kind}" 4839 4840 return f"{variable} AS {kind}{default}"
4842 def recursivewithsearch_sql(self, expression: exp.RecursiveWithSearch) -> str: 4843 kind = self.sql(expression, "kind") 4844 this = self.sql(expression, "this") 4845 set = self.sql(expression, "expression") 4846 using = self.sql(expression, "using") 4847 using = f" USING {using}" if using else "" 4848 4849 kind_sql = kind if kind == "CYCLE" else f"SEARCH {kind} FIRST BY" 4850 4851 return f"{kind_sql} {this} SET {set}{using}"
def
combinedparameterizedagg_sql(self, expression: sqlglot.expressions.CombinedParameterizedAgg) -> str:
4870 def put_sql(self, expression: exp.Put) -> str: 4871 props = expression.args.get("properties") 4872 props_sql = self.properties(props, prefix=" ", sep=" ", wrapped=False) if props else "" 4873 this = self.sql(expression, "this") 4874 target = self.sql(expression, "target") 4875 return f"PUT {this} {target}{props_sql}"