sqlglot.generator
1from __future__ import annotations 2 3import logging 4import re 5import typing as t 6from collections import defaultdict 7from functools import reduce, wraps 8 9from sqlglot import exp 10from sqlglot.errors import ErrorLevel, UnsupportedError, concat_messages 11from sqlglot.helper import apply_index_offset, csv, name_sequence, seq_get 12from sqlglot.jsonpath import ALL_JSON_PATH_PARTS, JSON_PATH_PART_TRANSFORMS 13from sqlglot.time import format_time 14from sqlglot.tokens import TokenType 15 16if t.TYPE_CHECKING: 17 from sqlglot._typing import E 18 from sqlglot.dialects.dialect import DialectType 19 20 G = t.TypeVar("G", bound="Generator") 21 GeneratorMethod = t.Callable[[G, E], str] 22 23logger = logging.getLogger("sqlglot") 24 25ESCAPED_UNICODE_RE = re.compile(r"\\(\d+)") 26UNSUPPORTED_TEMPLATE = "Argument '{}' is not supported for expression '{}' when targeting {}." 27 28 29def unsupported_args( 30 *args: t.Union[str, t.Tuple[str, str]], 31) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 32 """ 33 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 34 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 35 """ 36 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 37 for arg in args: 38 if isinstance(arg, str): 39 diagnostic_by_arg[arg] = None 40 else: 41 diagnostic_by_arg[arg[0]] = arg[1] 42 43 def decorator(func: GeneratorMethod) -> GeneratorMethod: 44 @wraps(func) 45 def _func(generator: G, expression: E) -> str: 46 expression_name = expression.__class__.__name__ 47 dialect_name = generator.dialect.__class__.__name__ 48 49 for arg_name, diagnostic in diagnostic_by_arg.items(): 50 if expression.args.get(arg_name): 51 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 52 arg_name, expression_name, dialect_name 53 ) 54 generator.unsupported(diagnostic) 55 56 return func(generator, expression) 57 58 return _func 59 60 return decorator 61 62 63class _Generator(type): 64 def __new__(cls, clsname, bases, attrs): 65 klass = super().__new__(cls, clsname, bases, attrs) 66 67 # Remove transforms that correspond to unsupported JSONPathPart expressions 68 for part in ALL_JSON_PATH_PARTS - klass.SUPPORTED_JSON_PATH_PARTS: 69 klass.TRANSFORMS.pop(part, None) 70 71 return klass 72 73 74class Generator(metaclass=_Generator): 75 """ 76 Generator converts a given syntax tree to the corresponding SQL string. 77 78 Args: 79 pretty: Whether to format the produced SQL string. 80 Default: False. 81 identify: Determines when an identifier should be quoted. Possible values are: 82 False (default): Never quote, except in cases where it's mandatory by the dialect. 83 True or 'always': Always quote. 84 'safe': Only quote identifiers that are case insensitive. 85 normalize: Whether to normalize identifiers to lowercase. 86 Default: False. 87 pad: The pad size in a formatted string. For example, this affects the indentation of 88 a projection in a query, relative to its nesting level. 89 Default: 2. 90 indent: The indentation size in a formatted string. For example, this affects the 91 indentation of subqueries and filters under a `WHERE` clause. 92 Default: 2. 93 normalize_functions: How to normalize function names. Possible values are: 94 "upper" or True (default): Convert names to uppercase. 95 "lower": Convert names to lowercase. 96 False: Disables function name normalization. 97 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 98 Default ErrorLevel.WARN. 99 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 100 This is only relevant if unsupported_level is ErrorLevel.RAISE. 101 Default: 3 102 leading_comma: Whether the comma is leading or trailing in select expressions. 103 This is only relevant when generating in pretty mode. 104 Default: False 105 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 106 The default is on the smaller end because the length only represents a segment and not the true 107 line length. 108 Default: 80 109 comments: Whether to preserve comments in the output SQL code. 110 Default: True 111 """ 112 113 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 114 **JSON_PATH_PART_TRANSFORMS, 115 exp.AllowedValuesProperty: lambda self, 116 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 117 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 118 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 119 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 120 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 121 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 122 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 123 exp.CaseSpecificColumnConstraint: lambda _, 124 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 125 exp.Ceil: lambda self, e: self.ceil_floor(e), 126 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 127 exp.CharacterSetProperty: lambda self, 128 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 129 exp.ClusteredColumnConstraint: lambda self, 130 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 131 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 132 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 133 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 134 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 135 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 136 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 137 exp.DynamicProperty: lambda *_: "DYNAMIC", 138 exp.EmptyProperty: lambda *_: "EMPTY", 139 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 140 exp.EphemeralColumnConstraint: lambda self, 141 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 142 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 143 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 144 exp.Except: lambda self, e: self.set_operations(e), 145 exp.ExternalProperty: lambda *_: "EXTERNAL", 146 exp.Floor: lambda self, e: self.ceil_floor(e), 147 exp.GlobalProperty: lambda *_: "GLOBAL", 148 exp.HeapProperty: lambda *_: "HEAP", 149 exp.IcebergProperty: lambda *_: "ICEBERG", 150 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 151 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 152 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 153 exp.Intersect: lambda self, e: self.set_operations(e), 154 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 155 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 156 exp.LanguageProperty: lambda self, e: self.naked_property(e), 157 exp.LocationProperty: lambda self, e: self.naked_property(e), 158 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 159 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 160 exp.NonClusteredColumnConstraint: lambda self, 161 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 162 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 163 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 164 exp.OnCommitProperty: lambda _, 165 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 166 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 167 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 168 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 169 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 170 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 171 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 172 exp.ProjectionPolicyColumnConstraint: lambda self, 173 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 174 exp.RemoteWithConnectionModelProperty: lambda self, 175 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 176 exp.ReturnsProperty: lambda self, e: ( 177 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 178 ), 179 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 180 exp.SecureProperty: lambda *_: "SECURE", 181 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 182 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 183 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 184 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 185 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 186 exp.SqlReadWriteProperty: lambda _, e: e.name, 187 exp.SqlSecurityProperty: lambda _, 188 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 189 exp.StabilityProperty: lambda _, e: e.name, 190 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 191 exp.StreamingTableProperty: lambda *_: "STREAMING", 192 exp.StrictProperty: lambda *_: "STRICT", 193 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 194 exp.TemporaryProperty: lambda *_: "TEMPORARY", 195 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 196 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 197 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 198 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 199 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 200 exp.TransientProperty: lambda *_: "TRANSIENT", 201 exp.Union: lambda self, e: self.set_operations(e), 202 exp.UnloggedProperty: lambda *_: "UNLOGGED", 203 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 204 exp.Uuid: lambda *_: "UUID()", 205 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 206 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 207 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 208 exp.VolatileProperty: lambda *_: "VOLATILE", 209 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 210 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 211 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 212 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 213 } 214 215 # Whether null ordering is supported in order by 216 # True: Full Support, None: No support, False: No support for certain cases 217 # such as window specifications, aggregate functions etc 218 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 219 220 # Whether ignore nulls is inside the agg or outside. 221 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 222 IGNORE_NULLS_IN_FUNC = False 223 224 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 225 LOCKING_READS_SUPPORTED = False 226 227 # Whether the EXCEPT and INTERSECT operations can return duplicates 228 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 229 230 # Wrap derived values in parens, usually standard but spark doesn't support it 231 WRAP_DERIVED_VALUES = True 232 233 # Whether create function uses an AS before the RETURN 234 CREATE_FUNCTION_RETURN_AS = True 235 236 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 237 MATCHED_BY_SOURCE = True 238 239 # Whether the INTERVAL expression works only with values like '1 day' 240 SINGLE_STRING_INTERVAL = False 241 242 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 243 INTERVAL_ALLOWS_PLURAL_FORM = True 244 245 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 246 LIMIT_FETCH = "ALL" 247 248 # Whether limit and fetch allows expresions or just limits 249 LIMIT_ONLY_LITERALS = False 250 251 # Whether a table is allowed to be renamed with a db 252 RENAME_TABLE_WITH_DB = True 253 254 # The separator for grouping sets and rollups 255 GROUPINGS_SEP = "," 256 257 # The string used for creating an index on a table 258 INDEX_ON = "ON" 259 260 # Whether join hints should be generated 261 JOIN_HINTS = True 262 263 # Whether table hints should be generated 264 TABLE_HINTS = True 265 266 # Whether query hints should be generated 267 QUERY_HINTS = True 268 269 # What kind of separator to use for query hints 270 QUERY_HINT_SEP = ", " 271 272 # Whether comparing against booleans (e.g. x IS TRUE) is supported 273 IS_BOOL_ALLOWED = True 274 275 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 276 DUPLICATE_KEY_UPDATE_WITH_SET = True 277 278 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 279 LIMIT_IS_TOP = False 280 281 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 282 RETURNING_END = True 283 284 # Whether to generate an unquoted value for EXTRACT's date part argument 285 EXTRACT_ALLOWS_QUOTES = True 286 287 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 288 TZ_TO_WITH_TIME_ZONE = False 289 290 # Whether the NVL2 function is supported 291 NVL2_SUPPORTED = True 292 293 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 294 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 295 296 # Whether VALUES statements can be used as derived tables. 297 # MySQL 5 and Redshift do not allow this, so when False, it will convert 298 # SELECT * VALUES into SELECT UNION 299 VALUES_AS_TABLE = True 300 301 # Whether the word COLUMN is included when adding a column with ALTER TABLE 302 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 303 304 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 305 UNNEST_WITH_ORDINALITY = True 306 307 # Whether FILTER (WHERE cond) can be used for conditional aggregation 308 AGGREGATE_FILTER_SUPPORTED = True 309 310 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 311 SEMI_ANTI_JOIN_WITH_SIDE = True 312 313 # Whether to include the type of a computed column in the CREATE DDL 314 COMPUTED_COLUMN_WITH_TYPE = True 315 316 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 317 SUPPORTS_TABLE_COPY = True 318 319 # Whether parentheses are required around the table sample's expression 320 TABLESAMPLE_REQUIRES_PARENS = True 321 322 # Whether a table sample clause's size needs to be followed by the ROWS keyword 323 TABLESAMPLE_SIZE_IS_ROWS = True 324 325 # The keyword(s) to use when generating a sample clause 326 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 327 328 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 329 TABLESAMPLE_WITH_METHOD = True 330 331 # The keyword to use when specifying the seed of a sample clause 332 TABLESAMPLE_SEED_KEYWORD = "SEED" 333 334 # Whether COLLATE is a function instead of a binary operator 335 COLLATE_IS_FUNC = False 336 337 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 338 DATA_TYPE_SPECIFIERS_ALLOWED = False 339 340 # Whether conditions require booleans WHERE x = 0 vs WHERE x 341 ENSURE_BOOLS = False 342 343 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 344 CTE_RECURSIVE_KEYWORD_REQUIRED = True 345 346 # Whether CONCAT requires >1 arguments 347 SUPPORTS_SINGLE_ARG_CONCAT = True 348 349 # Whether LAST_DAY function supports a date part argument 350 LAST_DAY_SUPPORTS_DATE_PART = True 351 352 # Whether named columns are allowed in table aliases 353 SUPPORTS_TABLE_ALIAS_COLUMNS = True 354 355 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 356 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 357 358 # What delimiter to use for separating JSON key/value pairs 359 JSON_KEY_VALUE_PAIR_SEP = ":" 360 361 # INSERT OVERWRITE TABLE x override 362 INSERT_OVERWRITE = " OVERWRITE TABLE" 363 364 # Whether the SELECT .. INTO syntax is used instead of CTAS 365 SUPPORTS_SELECT_INTO = False 366 367 # Whether UNLOGGED tables can be created 368 SUPPORTS_UNLOGGED_TABLES = False 369 370 # Whether the CREATE TABLE LIKE statement is supported 371 SUPPORTS_CREATE_TABLE_LIKE = True 372 373 # Whether the LikeProperty needs to be specified inside of the schema clause 374 LIKE_PROPERTY_INSIDE_SCHEMA = False 375 376 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 377 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 378 MULTI_ARG_DISTINCT = True 379 380 # Whether the JSON extraction operators expect a value of type JSON 381 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 382 383 # Whether bracketed keys like ["foo"] are supported in JSON paths 384 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 385 386 # Whether to escape keys using single quotes in JSON paths 387 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 388 389 # The JSONPathPart expressions supported by this dialect 390 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 391 392 # Whether any(f(x) for x in array) can be implemented by this dialect 393 CAN_IMPLEMENT_ARRAY_ANY = False 394 395 # Whether the function TO_NUMBER is supported 396 SUPPORTS_TO_NUMBER = True 397 398 # Whether or not set op modifiers apply to the outer set op or select. 399 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 400 # True means limit 1 happens after the set op, False means it it happens on y. 401 SET_OP_MODIFIERS = True 402 403 # Whether parameters from COPY statement are wrapped in parentheses 404 COPY_PARAMS_ARE_WRAPPED = True 405 406 # Whether values of params are set with "=" token or empty space 407 COPY_PARAMS_EQ_REQUIRED = False 408 409 # Whether COPY statement has INTO keyword 410 COPY_HAS_INTO_KEYWORD = True 411 412 # Whether the conditional TRY(expression) function is supported 413 TRY_SUPPORTED = True 414 415 # Whether the UESCAPE syntax in unicode strings is supported 416 SUPPORTS_UESCAPE = True 417 418 # The keyword to use when generating a star projection with excluded columns 419 STAR_EXCEPT = "EXCEPT" 420 421 # The HEX function name 422 HEX_FUNC = "HEX" 423 424 # The keywords to use when prefixing & separating WITH based properties 425 WITH_PROPERTIES_PREFIX = "WITH" 426 427 # Whether to quote the generated expression of exp.JsonPath 428 QUOTE_JSON_PATH = True 429 430 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 431 PAD_FILL_PATTERN_IS_REQUIRED = False 432 433 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 434 SUPPORTS_EXPLODING_PROJECTIONS = True 435 436 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 437 ARRAY_CONCAT_IS_VAR_LEN = True 438 439 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 440 SUPPORTS_CONVERT_TIMEZONE = False 441 442 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 443 SUPPORTS_MEDIAN = True 444 445 # Whether UNIX_SECONDS(timestamp) is supported 446 SUPPORTS_UNIX_SECONDS = False 447 448 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 449 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 450 451 # The function name of the exp.ArraySize expression 452 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 453 454 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 455 # None -> Doesn't support it at all 456 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 457 # True (Postgres) -> Explicitly requires it 458 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 459 460 TYPE_MAPPING = { 461 exp.DataType.Type.DATETIME2: "TIMESTAMP", 462 exp.DataType.Type.NCHAR: "CHAR", 463 exp.DataType.Type.NVARCHAR: "VARCHAR", 464 exp.DataType.Type.MEDIUMTEXT: "TEXT", 465 exp.DataType.Type.LONGTEXT: "TEXT", 466 exp.DataType.Type.TINYTEXT: "TEXT", 467 exp.DataType.Type.MEDIUMBLOB: "BLOB", 468 exp.DataType.Type.LONGBLOB: "BLOB", 469 exp.DataType.Type.TINYBLOB: "BLOB", 470 exp.DataType.Type.INET: "INET", 471 exp.DataType.Type.ROWVERSION: "VARBINARY", 472 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 473 } 474 475 TIME_PART_SINGULARS = { 476 "MICROSECONDS": "MICROSECOND", 477 "SECONDS": "SECOND", 478 "MINUTES": "MINUTE", 479 "HOURS": "HOUR", 480 "DAYS": "DAY", 481 "WEEKS": "WEEK", 482 "MONTHS": "MONTH", 483 "QUARTERS": "QUARTER", 484 "YEARS": "YEAR", 485 } 486 487 AFTER_HAVING_MODIFIER_TRANSFORMS = { 488 "cluster": lambda self, e: self.sql(e, "cluster"), 489 "distribute": lambda self, e: self.sql(e, "distribute"), 490 "sort": lambda self, e: self.sql(e, "sort"), 491 "windows": lambda self, e: ( 492 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 493 if e.args.get("windows") 494 else "" 495 ), 496 "qualify": lambda self, e: self.sql(e, "qualify"), 497 } 498 499 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 500 501 STRUCT_DELIMITER = ("<", ">") 502 503 PARAMETER_TOKEN = "@" 504 NAMED_PLACEHOLDER_TOKEN = ":" 505 506 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 507 508 PROPERTIES_LOCATION = { 509 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 510 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 511 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 512 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 513 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 514 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 515 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 516 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 517 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 518 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 520 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 521 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 524 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 525 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 526 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 527 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 528 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 529 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 530 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 532 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 533 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 534 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 536 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 537 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 538 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 539 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 540 exp.HeapProperty: exp.Properties.Location.POST_WITH, 541 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 542 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 543 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 544 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 546 exp.JournalProperty: exp.Properties.Location.POST_NAME, 547 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 548 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 552 exp.LogProperty: exp.Properties.Location.POST_NAME, 553 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 554 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 555 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 556 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 557 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 558 exp.Order: exp.Properties.Location.POST_SCHEMA, 559 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 560 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 561 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 562 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 563 exp.Property: exp.Properties.Location.POST_WITH, 564 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 565 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 572 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 573 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 574 exp.Set: exp.Properties.Location.POST_SCHEMA, 575 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 576 exp.SetProperty: exp.Properties.Location.POST_CREATE, 577 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 578 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 579 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 580 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 581 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 582 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 583 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 584 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 585 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 586 exp.Tags: exp.Properties.Location.POST_WITH, 587 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 588 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 589 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 590 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 591 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 592 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 593 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 594 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 595 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 596 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 597 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 598 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 599 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 600 } 601 602 # Keywords that can't be used as unquoted identifier names 603 RESERVED_KEYWORDS: t.Set[str] = set() 604 605 # Expressions whose comments are separated from them for better formatting 606 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 607 exp.Command, 608 exp.Create, 609 exp.Describe, 610 exp.Delete, 611 exp.Drop, 612 exp.From, 613 exp.Insert, 614 exp.Join, 615 exp.MultitableInserts, 616 exp.Select, 617 exp.SetOperation, 618 exp.Update, 619 exp.Where, 620 exp.With, 621 ) 622 623 # Expressions that should not have their comments generated in maybe_comment 624 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 625 exp.Binary, 626 exp.SetOperation, 627 ) 628 629 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 630 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 631 exp.Column, 632 exp.Literal, 633 exp.Neg, 634 exp.Paren, 635 ) 636 637 PARAMETERIZABLE_TEXT_TYPES = { 638 exp.DataType.Type.NVARCHAR, 639 exp.DataType.Type.VARCHAR, 640 exp.DataType.Type.CHAR, 641 exp.DataType.Type.NCHAR, 642 } 643 644 # Expressions that need to have all CTEs under them bubbled up to them 645 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 646 647 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 648 649 __slots__ = ( 650 "pretty", 651 "identify", 652 "normalize", 653 "pad", 654 "_indent", 655 "normalize_functions", 656 "unsupported_level", 657 "max_unsupported", 658 "leading_comma", 659 "max_text_width", 660 "comments", 661 "dialect", 662 "unsupported_messages", 663 "_escaped_quote_end", 664 "_escaped_identifier_end", 665 "_next_name", 666 "_identifier_start", 667 "_identifier_end", 668 "_quote_json_path_key_using_brackets", 669 ) 670 671 def __init__( 672 self, 673 pretty: t.Optional[bool] = None, 674 identify: str | bool = False, 675 normalize: bool = False, 676 pad: int = 2, 677 indent: int = 2, 678 normalize_functions: t.Optional[str | bool] = None, 679 unsupported_level: ErrorLevel = ErrorLevel.WARN, 680 max_unsupported: int = 3, 681 leading_comma: bool = False, 682 max_text_width: int = 80, 683 comments: bool = True, 684 dialect: DialectType = None, 685 ): 686 import sqlglot 687 from sqlglot.dialects import Dialect 688 689 self.pretty = pretty if pretty is not None else sqlglot.pretty 690 self.identify = identify 691 self.normalize = normalize 692 self.pad = pad 693 self._indent = indent 694 self.unsupported_level = unsupported_level 695 self.max_unsupported = max_unsupported 696 self.leading_comma = leading_comma 697 self.max_text_width = max_text_width 698 self.comments = comments 699 self.dialect = Dialect.get_or_raise(dialect) 700 701 # This is both a Dialect property and a Generator argument, so we prioritize the latter 702 self.normalize_functions = ( 703 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 704 ) 705 706 self.unsupported_messages: t.List[str] = [] 707 self._escaped_quote_end: str = ( 708 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 709 ) 710 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 711 712 self._next_name = name_sequence("_t") 713 714 self._identifier_start = self.dialect.IDENTIFIER_START 715 self._identifier_end = self.dialect.IDENTIFIER_END 716 717 self._quote_json_path_key_using_brackets = True 718 719 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 720 """ 721 Generates the SQL string corresponding to the given syntax tree. 722 723 Args: 724 expression: The syntax tree. 725 copy: Whether to copy the expression. The generator performs mutations so 726 it is safer to copy. 727 728 Returns: 729 The SQL string corresponding to `expression`. 730 """ 731 if copy: 732 expression = expression.copy() 733 734 expression = self.preprocess(expression) 735 736 self.unsupported_messages = [] 737 sql = self.sql(expression).strip() 738 739 if self.pretty: 740 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 741 742 if self.unsupported_level == ErrorLevel.IGNORE: 743 return sql 744 745 if self.unsupported_level == ErrorLevel.WARN: 746 for msg in self.unsupported_messages: 747 logger.warning(msg) 748 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 749 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 750 751 return sql 752 753 def preprocess(self, expression: exp.Expression) -> exp.Expression: 754 """Apply generic preprocessing transformations to a given expression.""" 755 expression = self._move_ctes_to_top_level(expression) 756 757 if self.ENSURE_BOOLS: 758 from sqlglot.transforms import ensure_bools 759 760 expression = ensure_bools(expression) 761 762 return expression 763 764 def _move_ctes_to_top_level(self, expression: E) -> E: 765 if ( 766 not expression.parent 767 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 768 and any(node.parent is not expression for node in expression.find_all(exp.With)) 769 ): 770 from sqlglot.transforms import move_ctes_to_top_level 771 772 expression = move_ctes_to_top_level(expression) 773 return expression 774 775 def unsupported(self, message: str) -> None: 776 if self.unsupported_level == ErrorLevel.IMMEDIATE: 777 raise UnsupportedError(message) 778 self.unsupported_messages.append(message) 779 780 def sep(self, sep: str = " ") -> str: 781 return f"{sep.strip()}\n" if self.pretty else sep 782 783 def seg(self, sql: str, sep: str = " ") -> str: 784 return f"{self.sep(sep)}{sql}" 785 786 def pad_comment(self, comment: str) -> str: 787 comment = " " + comment if comment[0].strip() else comment 788 comment = comment + " " if comment[-1].strip() else comment 789 return comment 790 791 def maybe_comment( 792 self, 793 sql: str, 794 expression: t.Optional[exp.Expression] = None, 795 comments: t.Optional[t.List[str]] = None, 796 separated: bool = False, 797 ) -> str: 798 comments = ( 799 ((expression and expression.comments) if comments is None else comments) # type: ignore 800 if self.comments 801 else None 802 ) 803 804 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 805 return sql 806 807 comments_sql = " ".join( 808 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 809 ) 810 811 if not comments_sql: 812 return sql 813 814 comments_sql = self._replace_line_breaks(comments_sql) 815 816 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 817 return ( 818 f"{self.sep()}{comments_sql}{sql}" 819 if not sql or sql[0].isspace() 820 else f"{comments_sql}{self.sep()}{sql}" 821 ) 822 823 return f"{sql} {comments_sql}" 824 825 def wrap(self, expression: exp.Expression | str) -> str: 826 this_sql = ( 827 self.sql(expression) 828 if isinstance(expression, exp.UNWRAPPED_QUERIES) 829 else self.sql(expression, "this") 830 ) 831 if not this_sql: 832 return "()" 833 834 this_sql = self.indent(this_sql, level=1, pad=0) 835 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 836 837 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 838 original = self.identify 839 self.identify = False 840 result = func(*args, **kwargs) 841 self.identify = original 842 return result 843 844 def normalize_func(self, name: str) -> str: 845 if self.normalize_functions == "upper" or self.normalize_functions is True: 846 return name.upper() 847 if self.normalize_functions == "lower": 848 return name.lower() 849 return name 850 851 def indent( 852 self, 853 sql: str, 854 level: int = 0, 855 pad: t.Optional[int] = None, 856 skip_first: bool = False, 857 skip_last: bool = False, 858 ) -> str: 859 if not self.pretty or not sql: 860 return sql 861 862 pad = self.pad if pad is None else pad 863 lines = sql.split("\n") 864 865 return "\n".join( 866 ( 867 line 868 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 869 else f"{' ' * (level * self._indent + pad)}{line}" 870 ) 871 for i, line in enumerate(lines) 872 ) 873 874 def sql( 875 self, 876 expression: t.Optional[str | exp.Expression], 877 key: t.Optional[str] = None, 878 comment: bool = True, 879 ) -> str: 880 if not expression: 881 return "" 882 883 if isinstance(expression, str): 884 return expression 885 886 if key: 887 value = expression.args.get(key) 888 if value: 889 return self.sql(value) 890 return "" 891 892 transform = self.TRANSFORMS.get(expression.__class__) 893 894 if callable(transform): 895 sql = transform(self, expression) 896 elif isinstance(expression, exp.Expression): 897 exp_handler_name = f"{expression.key}_sql" 898 899 if hasattr(self, exp_handler_name): 900 sql = getattr(self, exp_handler_name)(expression) 901 elif isinstance(expression, exp.Func): 902 sql = self.function_fallback_sql(expression) 903 elif isinstance(expression, exp.Property): 904 sql = self.property_sql(expression) 905 else: 906 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 907 else: 908 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 909 910 return self.maybe_comment(sql, expression) if self.comments and comment else sql 911 912 def uncache_sql(self, expression: exp.Uncache) -> str: 913 table = self.sql(expression, "this") 914 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 915 return f"UNCACHE TABLE{exists_sql} {table}" 916 917 def cache_sql(self, expression: exp.Cache) -> str: 918 lazy = " LAZY" if expression.args.get("lazy") else "" 919 table = self.sql(expression, "this") 920 options = expression.args.get("options") 921 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 922 sql = self.sql(expression, "expression") 923 sql = f" AS{self.sep()}{sql}" if sql else "" 924 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 925 return self.prepend_ctes(expression, sql) 926 927 def characterset_sql(self, expression: exp.CharacterSet) -> str: 928 if isinstance(expression.parent, exp.Cast): 929 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 930 default = "DEFAULT " if expression.args.get("default") else "" 931 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 932 933 def column_parts(self, expression: exp.Column) -> str: 934 return ".".join( 935 self.sql(part) 936 for part in ( 937 expression.args.get("catalog"), 938 expression.args.get("db"), 939 expression.args.get("table"), 940 expression.args.get("this"), 941 ) 942 if part 943 ) 944 945 def column_sql(self, expression: exp.Column) -> str: 946 join_mark = " (+)" if expression.args.get("join_mark") else "" 947 948 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 949 join_mark = "" 950 self.unsupported("Outer join syntax using the (+) operator is not supported.") 951 952 return f"{self.column_parts(expression)}{join_mark}" 953 954 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 955 this = self.sql(expression, "this") 956 this = f" {this}" if this else "" 957 position = self.sql(expression, "position") 958 return f"{position}{this}" 959 960 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 961 column = self.sql(expression, "this") 962 kind = self.sql(expression, "kind") 963 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 964 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 965 kind = f"{sep}{kind}" if kind else "" 966 constraints = f" {constraints}" if constraints else "" 967 position = self.sql(expression, "position") 968 position = f" {position}" if position else "" 969 970 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 971 kind = "" 972 973 return f"{exists}{column}{kind}{constraints}{position}" 974 975 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 976 this = self.sql(expression, "this") 977 kind_sql = self.sql(expression, "kind").strip() 978 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 979 980 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 981 this = self.sql(expression, "this") 982 if expression.args.get("not_null"): 983 persisted = " PERSISTED NOT NULL" 984 elif expression.args.get("persisted"): 985 persisted = " PERSISTED" 986 else: 987 persisted = "" 988 return f"AS {this}{persisted}" 989 990 def autoincrementcolumnconstraint_sql(self, _) -> str: 991 return self.token_sql(TokenType.AUTO_INCREMENT) 992 993 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 994 if isinstance(expression.this, list): 995 this = self.wrap(self.expressions(expression, key="this", flat=True)) 996 else: 997 this = self.sql(expression, "this") 998 999 return f"COMPRESS {this}" 1000 1001 def generatedasidentitycolumnconstraint_sql( 1002 self, expression: exp.GeneratedAsIdentityColumnConstraint 1003 ) -> str: 1004 this = "" 1005 if expression.this is not None: 1006 on_null = " ON NULL" if expression.args.get("on_null") else "" 1007 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1008 1009 start = expression.args.get("start") 1010 start = f"START WITH {start}" if start else "" 1011 increment = expression.args.get("increment") 1012 increment = f" INCREMENT BY {increment}" if increment else "" 1013 minvalue = expression.args.get("minvalue") 1014 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1015 maxvalue = expression.args.get("maxvalue") 1016 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1017 cycle = expression.args.get("cycle") 1018 cycle_sql = "" 1019 1020 if cycle is not None: 1021 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1022 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1023 1024 sequence_opts = "" 1025 if start or increment or cycle_sql: 1026 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1027 sequence_opts = f" ({sequence_opts.strip()})" 1028 1029 expr = self.sql(expression, "expression") 1030 expr = f"({expr})" if expr else "IDENTITY" 1031 1032 return f"GENERATED{this} AS {expr}{sequence_opts}" 1033 1034 def generatedasrowcolumnconstraint_sql( 1035 self, expression: exp.GeneratedAsRowColumnConstraint 1036 ) -> str: 1037 start = "START" if expression.args.get("start") else "END" 1038 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1039 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1040 1041 def periodforsystemtimeconstraint_sql( 1042 self, expression: exp.PeriodForSystemTimeConstraint 1043 ) -> str: 1044 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1045 1046 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1047 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1048 1049 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1050 return f"AS {self.sql(expression, 'this')}" 1051 1052 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1053 desc = expression.args.get("desc") 1054 if desc is not None: 1055 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1056 return "PRIMARY KEY" 1057 1058 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1059 this = self.sql(expression, "this") 1060 this = f" {this}" if this else "" 1061 index_type = expression.args.get("index_type") 1062 index_type = f" USING {index_type}" if index_type else "" 1063 on_conflict = self.sql(expression, "on_conflict") 1064 on_conflict = f" {on_conflict}" if on_conflict else "" 1065 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1066 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1067 1068 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1069 return self.sql(expression, "this") 1070 1071 def create_sql(self, expression: exp.Create) -> str: 1072 kind = self.sql(expression, "kind") 1073 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1074 properties = expression.args.get("properties") 1075 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1076 1077 this = self.createable_sql(expression, properties_locs) 1078 1079 properties_sql = "" 1080 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1081 exp.Properties.Location.POST_WITH 1082 ): 1083 properties_sql = self.sql( 1084 exp.Properties( 1085 expressions=[ 1086 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1087 *properties_locs[exp.Properties.Location.POST_WITH], 1088 ] 1089 ) 1090 ) 1091 1092 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1093 properties_sql = self.sep() + properties_sql 1094 elif not self.pretty: 1095 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1096 properties_sql = f" {properties_sql}" 1097 1098 begin = " BEGIN" if expression.args.get("begin") else "" 1099 end = " END" if expression.args.get("end") else "" 1100 1101 expression_sql = self.sql(expression, "expression") 1102 if expression_sql: 1103 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1104 1105 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1106 postalias_props_sql = "" 1107 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1108 postalias_props_sql = self.properties( 1109 exp.Properties( 1110 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1111 ), 1112 wrapped=False, 1113 ) 1114 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1115 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1116 1117 postindex_props_sql = "" 1118 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1119 postindex_props_sql = self.properties( 1120 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1121 wrapped=False, 1122 prefix=" ", 1123 ) 1124 1125 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1126 indexes = f" {indexes}" if indexes else "" 1127 index_sql = indexes + postindex_props_sql 1128 1129 replace = " OR REPLACE" if expression.args.get("replace") else "" 1130 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1131 unique = " UNIQUE" if expression.args.get("unique") else "" 1132 1133 clustered = expression.args.get("clustered") 1134 if clustered is None: 1135 clustered_sql = "" 1136 elif clustered: 1137 clustered_sql = " CLUSTERED COLUMNSTORE" 1138 else: 1139 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1140 1141 postcreate_props_sql = "" 1142 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1143 postcreate_props_sql = self.properties( 1144 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1145 sep=" ", 1146 prefix=" ", 1147 wrapped=False, 1148 ) 1149 1150 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1151 1152 postexpression_props_sql = "" 1153 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1154 postexpression_props_sql = self.properties( 1155 exp.Properties( 1156 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1157 ), 1158 sep=" ", 1159 prefix=" ", 1160 wrapped=False, 1161 ) 1162 1163 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1164 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1165 no_schema_binding = ( 1166 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1167 ) 1168 1169 clone = self.sql(expression, "clone") 1170 clone = f" {clone}" if clone else "" 1171 1172 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1173 properties_expression = f"{expression_sql}{properties_sql}" 1174 else: 1175 properties_expression = f"{properties_sql}{expression_sql}" 1176 1177 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1178 return self.prepend_ctes(expression, expression_sql) 1179 1180 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1181 start = self.sql(expression, "start") 1182 start = f"START WITH {start}" if start else "" 1183 increment = self.sql(expression, "increment") 1184 increment = f" INCREMENT BY {increment}" if increment else "" 1185 minvalue = self.sql(expression, "minvalue") 1186 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1187 maxvalue = self.sql(expression, "maxvalue") 1188 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1189 owned = self.sql(expression, "owned") 1190 owned = f" OWNED BY {owned}" if owned else "" 1191 1192 cache = expression.args.get("cache") 1193 if cache is None: 1194 cache_str = "" 1195 elif cache is True: 1196 cache_str = " CACHE" 1197 else: 1198 cache_str = f" CACHE {cache}" 1199 1200 options = self.expressions(expression, key="options", flat=True, sep=" ") 1201 options = f" {options}" if options else "" 1202 1203 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1204 1205 def clone_sql(self, expression: exp.Clone) -> str: 1206 this = self.sql(expression, "this") 1207 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1208 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1209 return f"{shallow}{keyword} {this}" 1210 1211 def describe_sql(self, expression: exp.Describe) -> str: 1212 style = expression.args.get("style") 1213 style = f" {style}" if style else "" 1214 partition = self.sql(expression, "partition") 1215 partition = f" {partition}" if partition else "" 1216 format = self.sql(expression, "format") 1217 format = f" {format}" if format else "" 1218 1219 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1220 1221 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1222 tag = self.sql(expression, "tag") 1223 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1224 1225 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1226 with_ = self.sql(expression, "with") 1227 if with_: 1228 sql = f"{with_}{self.sep()}{sql}" 1229 return sql 1230 1231 def with_sql(self, expression: exp.With) -> str: 1232 sql = self.expressions(expression, flat=True) 1233 recursive = ( 1234 "RECURSIVE " 1235 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1236 else "" 1237 ) 1238 1239 return f"WITH {recursive}{sql}" 1240 1241 def cte_sql(self, expression: exp.CTE) -> str: 1242 alias = expression.args.get("alias") 1243 if alias: 1244 alias.add_comments(expression.pop_comments()) 1245 1246 alias_sql = self.sql(expression, "alias") 1247 1248 materialized = expression.args.get("materialized") 1249 if materialized is False: 1250 materialized = "NOT MATERIALIZED " 1251 elif materialized: 1252 materialized = "MATERIALIZED " 1253 1254 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1255 1256 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1257 alias = self.sql(expression, "this") 1258 columns = self.expressions(expression, key="columns", flat=True) 1259 columns = f"({columns})" if columns else "" 1260 1261 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1262 columns = "" 1263 self.unsupported("Named columns are not supported in table alias.") 1264 1265 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1266 alias = self._next_name() 1267 1268 return f"{alias}{columns}" 1269 1270 def bitstring_sql(self, expression: exp.BitString) -> str: 1271 this = self.sql(expression, "this") 1272 if self.dialect.BIT_START: 1273 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1274 return f"{int(this, 2)}" 1275 1276 def hexstring_sql(self, expression: exp.HexString) -> str: 1277 this = self.sql(expression, "this") 1278 if self.dialect.HEX_START: 1279 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1280 return f"{int(this, 16)}" 1281 1282 def bytestring_sql(self, expression: exp.ByteString) -> str: 1283 this = self.sql(expression, "this") 1284 if self.dialect.BYTE_START: 1285 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1286 return this 1287 1288 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1289 this = self.sql(expression, "this") 1290 escape = expression.args.get("escape") 1291 1292 if self.dialect.UNICODE_START: 1293 escape_substitute = r"\\\1" 1294 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1295 else: 1296 escape_substitute = r"\\u\1" 1297 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1298 1299 if escape: 1300 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1301 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1302 else: 1303 escape_pattern = ESCAPED_UNICODE_RE 1304 escape_sql = "" 1305 1306 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1307 this = escape_pattern.sub(escape_substitute, this) 1308 1309 return f"{left_quote}{this}{right_quote}{escape_sql}" 1310 1311 def rawstring_sql(self, expression: exp.RawString) -> str: 1312 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1313 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1314 1315 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1316 this = self.sql(expression, "this") 1317 specifier = self.sql(expression, "expression") 1318 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1319 return f"{this}{specifier}" 1320 1321 def datatype_sql(self, expression: exp.DataType) -> str: 1322 nested = "" 1323 values = "" 1324 interior = self.expressions(expression, flat=True) 1325 1326 type_value = expression.this 1327 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1328 type_sql = self.sql(expression, "kind") 1329 else: 1330 type_sql = ( 1331 self.TYPE_MAPPING.get(type_value, type_value.value) 1332 if isinstance(type_value, exp.DataType.Type) 1333 else type_value 1334 ) 1335 1336 if interior: 1337 if expression.args.get("nested"): 1338 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1339 if expression.args.get("values") is not None: 1340 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1341 values = self.expressions(expression, key="values", flat=True) 1342 values = f"{delimiters[0]}{values}{delimiters[1]}" 1343 elif type_value == exp.DataType.Type.INTERVAL: 1344 nested = f" {interior}" 1345 else: 1346 nested = f"({interior})" 1347 1348 type_sql = f"{type_sql}{nested}{values}" 1349 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1350 exp.DataType.Type.TIMETZ, 1351 exp.DataType.Type.TIMESTAMPTZ, 1352 ): 1353 type_sql = f"{type_sql} WITH TIME ZONE" 1354 1355 return type_sql 1356 1357 def directory_sql(self, expression: exp.Directory) -> str: 1358 local = "LOCAL " if expression.args.get("local") else "" 1359 row_format = self.sql(expression, "row_format") 1360 row_format = f" {row_format}" if row_format else "" 1361 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1362 1363 def delete_sql(self, expression: exp.Delete) -> str: 1364 this = self.sql(expression, "this") 1365 this = f" FROM {this}" if this else "" 1366 using = self.sql(expression, "using") 1367 using = f" USING {using}" if using else "" 1368 cluster = self.sql(expression, "cluster") 1369 cluster = f" {cluster}" if cluster else "" 1370 where = self.sql(expression, "where") 1371 returning = self.sql(expression, "returning") 1372 limit = self.sql(expression, "limit") 1373 tables = self.expressions(expression, key="tables") 1374 tables = f" {tables}" if tables else "" 1375 if self.RETURNING_END: 1376 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1377 else: 1378 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1379 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1380 1381 def drop_sql(self, expression: exp.Drop) -> str: 1382 this = self.sql(expression, "this") 1383 expressions = self.expressions(expression, flat=True) 1384 expressions = f" ({expressions})" if expressions else "" 1385 kind = expression.args["kind"] 1386 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1387 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1388 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1389 on_cluster = self.sql(expression, "cluster") 1390 on_cluster = f" {on_cluster}" if on_cluster else "" 1391 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1392 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1393 cascade = " CASCADE" if expression.args.get("cascade") else "" 1394 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1395 purge = " PURGE" if expression.args.get("purge") else "" 1396 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1397 1398 def set_operation(self, expression: exp.SetOperation) -> str: 1399 op_type = type(expression) 1400 op_name = op_type.key.upper() 1401 1402 distinct = expression.args.get("distinct") 1403 if ( 1404 distinct is False 1405 and op_type in (exp.Except, exp.Intersect) 1406 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1407 ): 1408 self.unsupported(f"{op_name} ALL is not supported") 1409 1410 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1411 1412 if distinct is None: 1413 distinct = default_distinct 1414 if distinct is None: 1415 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1416 1417 if distinct is default_distinct: 1418 kind = "" 1419 else: 1420 kind = " DISTINCT" if distinct else " ALL" 1421 1422 by_name = " BY NAME" if expression.args.get("by_name") else "" 1423 return f"{op_name}{kind}{by_name}" 1424 1425 def set_operations(self, expression: exp.SetOperation) -> str: 1426 if not self.SET_OP_MODIFIERS: 1427 limit = expression.args.get("limit") 1428 order = expression.args.get("order") 1429 1430 if limit or order: 1431 select = self._move_ctes_to_top_level( 1432 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1433 ) 1434 1435 if limit: 1436 select = select.limit(limit.pop(), copy=False) 1437 if order: 1438 select = select.order_by(order.pop(), copy=False) 1439 return self.sql(select) 1440 1441 sqls: t.List[str] = [] 1442 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1443 1444 while stack: 1445 node = stack.pop() 1446 1447 if isinstance(node, exp.SetOperation): 1448 stack.append(node.expression) 1449 stack.append( 1450 self.maybe_comment( 1451 self.set_operation(node), comments=node.comments, separated=True 1452 ) 1453 ) 1454 stack.append(node.this) 1455 else: 1456 sqls.append(self.sql(node)) 1457 1458 this = self.sep().join(sqls) 1459 this = self.query_modifiers(expression, this) 1460 return self.prepend_ctes(expression, this) 1461 1462 def fetch_sql(self, expression: exp.Fetch) -> str: 1463 direction = expression.args.get("direction") 1464 direction = f" {direction}" if direction else "" 1465 count = self.sql(expression, "count") 1466 count = f" {count}" if count else "" 1467 if expression.args.get("percent"): 1468 count = f"{count} PERCENT" 1469 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1470 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}" 1471 1472 def filter_sql(self, expression: exp.Filter) -> str: 1473 if self.AGGREGATE_FILTER_SUPPORTED: 1474 this = self.sql(expression, "this") 1475 where = self.sql(expression, "expression").strip() 1476 return f"{this} FILTER({where})" 1477 1478 agg = expression.this 1479 agg_arg = agg.this 1480 cond = expression.expression.this 1481 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1482 return self.sql(agg) 1483 1484 def hint_sql(self, expression: exp.Hint) -> str: 1485 if not self.QUERY_HINTS: 1486 self.unsupported("Hints are not supported") 1487 return "" 1488 1489 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1490 1491 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1492 using = self.sql(expression, "using") 1493 using = f" USING {using}" if using else "" 1494 columns = self.expressions(expression, key="columns", flat=True) 1495 columns = f"({columns})" if columns else "" 1496 partition_by = self.expressions(expression, key="partition_by", flat=True) 1497 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1498 where = self.sql(expression, "where") 1499 include = self.expressions(expression, key="include", flat=True) 1500 if include: 1501 include = f" INCLUDE ({include})" 1502 with_storage = self.expressions(expression, key="with_storage", flat=True) 1503 with_storage = f" WITH ({with_storage})" if with_storage else "" 1504 tablespace = self.sql(expression, "tablespace") 1505 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1506 on = self.sql(expression, "on") 1507 on = f" ON {on}" if on else "" 1508 1509 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1510 1511 def index_sql(self, expression: exp.Index) -> str: 1512 unique = "UNIQUE " if expression.args.get("unique") else "" 1513 primary = "PRIMARY " if expression.args.get("primary") else "" 1514 amp = "AMP " if expression.args.get("amp") else "" 1515 name = self.sql(expression, "this") 1516 name = f"{name} " if name else "" 1517 table = self.sql(expression, "table") 1518 table = f"{self.INDEX_ON} {table}" if table else "" 1519 1520 index = "INDEX " if not table else "" 1521 1522 params = self.sql(expression, "params") 1523 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1524 1525 def identifier_sql(self, expression: exp.Identifier) -> str: 1526 text = expression.name 1527 lower = text.lower() 1528 text = lower if self.normalize and not expression.quoted else text 1529 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1530 if ( 1531 expression.quoted 1532 or self.dialect.can_identify(text, self.identify) 1533 or lower in self.RESERVED_KEYWORDS 1534 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1535 ): 1536 text = f"{self._identifier_start}{text}{self._identifier_end}" 1537 return text 1538 1539 def hex_sql(self, expression: exp.Hex) -> str: 1540 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1541 if self.dialect.HEX_LOWERCASE: 1542 text = self.func("LOWER", text) 1543 1544 return text 1545 1546 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1547 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1548 if not self.dialect.HEX_LOWERCASE: 1549 text = self.func("LOWER", text) 1550 return text 1551 1552 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1553 input_format = self.sql(expression, "input_format") 1554 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1555 output_format = self.sql(expression, "output_format") 1556 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1557 return self.sep().join((input_format, output_format)) 1558 1559 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1560 string = self.sql(exp.Literal.string(expression.name)) 1561 return f"{prefix}{string}" 1562 1563 def partition_sql(self, expression: exp.Partition) -> str: 1564 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1565 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1566 1567 def properties_sql(self, expression: exp.Properties) -> str: 1568 root_properties = [] 1569 with_properties = [] 1570 1571 for p in expression.expressions: 1572 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1573 if p_loc == exp.Properties.Location.POST_WITH: 1574 with_properties.append(p) 1575 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1576 root_properties.append(p) 1577 1578 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1579 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1580 1581 if root_props and with_props and not self.pretty: 1582 with_props = " " + with_props 1583 1584 return root_props + with_props 1585 1586 def root_properties(self, properties: exp.Properties) -> str: 1587 if properties.expressions: 1588 return self.expressions(properties, indent=False, sep=" ") 1589 return "" 1590 1591 def properties( 1592 self, 1593 properties: exp.Properties, 1594 prefix: str = "", 1595 sep: str = ", ", 1596 suffix: str = "", 1597 wrapped: bool = True, 1598 ) -> str: 1599 if properties.expressions: 1600 expressions = self.expressions(properties, sep=sep, indent=False) 1601 if expressions: 1602 expressions = self.wrap(expressions) if wrapped else expressions 1603 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1604 return "" 1605 1606 def with_properties(self, properties: exp.Properties) -> str: 1607 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1608 1609 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1610 properties_locs = defaultdict(list) 1611 for p in properties.expressions: 1612 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1613 if p_loc != exp.Properties.Location.UNSUPPORTED: 1614 properties_locs[p_loc].append(p) 1615 else: 1616 self.unsupported(f"Unsupported property {p.key}") 1617 1618 return properties_locs 1619 1620 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1621 if isinstance(expression.this, exp.Dot): 1622 return self.sql(expression, "this") 1623 return f"'{expression.name}'" if string_key else expression.name 1624 1625 def property_sql(self, expression: exp.Property) -> str: 1626 property_cls = expression.__class__ 1627 if property_cls == exp.Property: 1628 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1629 1630 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1631 if not property_name: 1632 self.unsupported(f"Unsupported property {expression.key}") 1633 1634 return f"{property_name}={self.sql(expression, 'this')}" 1635 1636 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1637 if self.SUPPORTS_CREATE_TABLE_LIKE: 1638 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1639 options = f" {options}" if options else "" 1640 1641 like = f"LIKE {self.sql(expression, 'this')}{options}" 1642 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1643 like = f"({like})" 1644 1645 return like 1646 1647 if expression.expressions: 1648 self.unsupported("Transpilation of LIKE property options is unsupported") 1649 1650 select = exp.select("*").from_(expression.this).limit(0) 1651 return f"AS {self.sql(select)}" 1652 1653 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1654 no = "NO " if expression.args.get("no") else "" 1655 protection = " PROTECTION" if expression.args.get("protection") else "" 1656 return f"{no}FALLBACK{protection}" 1657 1658 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1659 no = "NO " if expression.args.get("no") else "" 1660 local = expression.args.get("local") 1661 local = f"{local} " if local else "" 1662 dual = "DUAL " if expression.args.get("dual") else "" 1663 before = "BEFORE " if expression.args.get("before") else "" 1664 after = "AFTER " if expression.args.get("after") else "" 1665 return f"{no}{local}{dual}{before}{after}JOURNAL" 1666 1667 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1668 freespace = self.sql(expression, "this") 1669 percent = " PERCENT" if expression.args.get("percent") else "" 1670 return f"FREESPACE={freespace}{percent}" 1671 1672 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1673 if expression.args.get("default"): 1674 property = "DEFAULT" 1675 elif expression.args.get("on"): 1676 property = "ON" 1677 else: 1678 property = "OFF" 1679 return f"CHECKSUM={property}" 1680 1681 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1682 if expression.args.get("no"): 1683 return "NO MERGEBLOCKRATIO" 1684 if expression.args.get("default"): 1685 return "DEFAULT MERGEBLOCKRATIO" 1686 1687 percent = " PERCENT" if expression.args.get("percent") else "" 1688 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1689 1690 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1691 default = expression.args.get("default") 1692 minimum = expression.args.get("minimum") 1693 maximum = expression.args.get("maximum") 1694 if default or minimum or maximum: 1695 if default: 1696 prop = "DEFAULT" 1697 elif minimum: 1698 prop = "MINIMUM" 1699 else: 1700 prop = "MAXIMUM" 1701 return f"{prop} DATABLOCKSIZE" 1702 units = expression.args.get("units") 1703 units = f" {units}" if units else "" 1704 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1705 1706 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1707 autotemp = expression.args.get("autotemp") 1708 always = expression.args.get("always") 1709 default = expression.args.get("default") 1710 manual = expression.args.get("manual") 1711 never = expression.args.get("never") 1712 1713 if autotemp is not None: 1714 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1715 elif always: 1716 prop = "ALWAYS" 1717 elif default: 1718 prop = "DEFAULT" 1719 elif manual: 1720 prop = "MANUAL" 1721 elif never: 1722 prop = "NEVER" 1723 return f"BLOCKCOMPRESSION={prop}" 1724 1725 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1726 no = expression.args.get("no") 1727 no = " NO" if no else "" 1728 concurrent = expression.args.get("concurrent") 1729 concurrent = " CONCURRENT" if concurrent else "" 1730 target = self.sql(expression, "target") 1731 target = f" {target}" if target else "" 1732 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1733 1734 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1735 if isinstance(expression.this, list): 1736 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1737 if expression.this: 1738 modulus = self.sql(expression, "this") 1739 remainder = self.sql(expression, "expression") 1740 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1741 1742 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1743 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1744 return f"FROM ({from_expressions}) TO ({to_expressions})" 1745 1746 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1747 this = self.sql(expression, "this") 1748 1749 for_values_or_default = expression.expression 1750 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1751 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1752 else: 1753 for_values_or_default = " DEFAULT" 1754 1755 return f"PARTITION OF {this}{for_values_or_default}" 1756 1757 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1758 kind = expression.args.get("kind") 1759 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1760 for_or_in = expression.args.get("for_or_in") 1761 for_or_in = f" {for_or_in}" if for_or_in else "" 1762 lock_type = expression.args.get("lock_type") 1763 override = " OVERRIDE" if expression.args.get("override") else "" 1764 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1765 1766 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1767 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1768 statistics = expression.args.get("statistics") 1769 statistics_sql = "" 1770 if statistics is not None: 1771 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1772 return f"{data_sql}{statistics_sql}" 1773 1774 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1775 this = self.sql(expression, "this") 1776 this = f"HISTORY_TABLE={this}" if this else "" 1777 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1778 data_consistency = ( 1779 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1780 ) 1781 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1782 retention_period = ( 1783 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1784 ) 1785 1786 if this: 1787 on_sql = self.func("ON", this, data_consistency, retention_period) 1788 else: 1789 on_sql = "ON" if expression.args.get("on") else "OFF" 1790 1791 sql = f"SYSTEM_VERSIONING={on_sql}" 1792 1793 return f"WITH({sql})" if expression.args.get("with") else sql 1794 1795 def insert_sql(self, expression: exp.Insert) -> str: 1796 hint = self.sql(expression, "hint") 1797 overwrite = expression.args.get("overwrite") 1798 1799 if isinstance(expression.this, exp.Directory): 1800 this = " OVERWRITE" if overwrite else " INTO" 1801 else: 1802 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1803 1804 stored = self.sql(expression, "stored") 1805 stored = f" {stored}" if stored else "" 1806 alternative = expression.args.get("alternative") 1807 alternative = f" OR {alternative}" if alternative else "" 1808 ignore = " IGNORE" if expression.args.get("ignore") else "" 1809 is_function = expression.args.get("is_function") 1810 if is_function: 1811 this = f"{this} FUNCTION" 1812 this = f"{this} {self.sql(expression, 'this')}" 1813 1814 exists = " IF EXISTS" if expression.args.get("exists") else "" 1815 where = self.sql(expression, "where") 1816 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1817 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1818 on_conflict = self.sql(expression, "conflict") 1819 on_conflict = f" {on_conflict}" if on_conflict else "" 1820 by_name = " BY NAME" if expression.args.get("by_name") else "" 1821 returning = self.sql(expression, "returning") 1822 1823 if self.RETURNING_END: 1824 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1825 else: 1826 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1827 1828 partition_by = self.sql(expression, "partition") 1829 partition_by = f" {partition_by}" if partition_by else "" 1830 settings = self.sql(expression, "settings") 1831 settings = f" {settings}" if settings else "" 1832 1833 source = self.sql(expression, "source") 1834 source = f"TABLE {source}" if source else "" 1835 1836 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1837 return self.prepend_ctes(expression, sql) 1838 1839 def introducer_sql(self, expression: exp.Introducer) -> str: 1840 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1841 1842 def kill_sql(self, expression: exp.Kill) -> str: 1843 kind = self.sql(expression, "kind") 1844 kind = f" {kind}" if kind else "" 1845 this = self.sql(expression, "this") 1846 this = f" {this}" if this else "" 1847 return f"KILL{kind}{this}" 1848 1849 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1850 return expression.name 1851 1852 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1853 return expression.name 1854 1855 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1856 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1857 1858 constraint = self.sql(expression, "constraint") 1859 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1860 1861 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1862 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1863 action = self.sql(expression, "action") 1864 1865 expressions = self.expressions(expression, flat=True) 1866 if expressions: 1867 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1868 expressions = f" {set_keyword}{expressions}" 1869 1870 where = self.sql(expression, "where") 1871 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1872 1873 def returning_sql(self, expression: exp.Returning) -> str: 1874 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1875 1876 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1877 fields = self.sql(expression, "fields") 1878 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1879 escaped = self.sql(expression, "escaped") 1880 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1881 items = self.sql(expression, "collection_items") 1882 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1883 keys = self.sql(expression, "map_keys") 1884 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1885 lines = self.sql(expression, "lines") 1886 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1887 null = self.sql(expression, "null") 1888 null = f" NULL DEFINED AS {null}" if null else "" 1889 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1890 1891 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1892 return f"WITH ({self.expressions(expression, flat=True)})" 1893 1894 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1895 this = f"{self.sql(expression, 'this')} INDEX" 1896 target = self.sql(expression, "target") 1897 target = f" FOR {target}" if target else "" 1898 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1899 1900 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1901 this = self.sql(expression, "this") 1902 kind = self.sql(expression, "kind") 1903 expr = self.sql(expression, "expression") 1904 return f"{this} ({kind} => {expr})" 1905 1906 def table_parts(self, expression: exp.Table) -> str: 1907 return ".".join( 1908 self.sql(part) 1909 for part in ( 1910 expression.args.get("catalog"), 1911 expression.args.get("db"), 1912 expression.args.get("this"), 1913 ) 1914 if part is not None 1915 ) 1916 1917 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1918 table = self.table_parts(expression) 1919 only = "ONLY " if expression.args.get("only") else "" 1920 partition = self.sql(expression, "partition") 1921 partition = f" {partition}" if partition else "" 1922 version = self.sql(expression, "version") 1923 version = f" {version}" if version else "" 1924 alias = self.sql(expression, "alias") 1925 alias = f"{sep}{alias}" if alias else "" 1926 1927 sample = self.sql(expression, "sample") 1928 if self.dialect.ALIAS_POST_TABLESAMPLE: 1929 sample_pre_alias = sample 1930 sample_post_alias = "" 1931 else: 1932 sample_pre_alias = "" 1933 sample_post_alias = sample 1934 1935 hints = self.expressions(expression, key="hints", sep=" ") 1936 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1937 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1938 joins = self.indent( 1939 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1940 ) 1941 laterals = self.expressions(expression, key="laterals", sep="") 1942 1943 file_format = self.sql(expression, "format") 1944 if file_format: 1945 pattern = self.sql(expression, "pattern") 1946 pattern = f", PATTERN => {pattern}" if pattern else "" 1947 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1948 1949 ordinality = expression.args.get("ordinality") or "" 1950 if ordinality: 1951 ordinality = f" WITH ORDINALITY{alias}" 1952 alias = "" 1953 1954 when = self.sql(expression, "when") 1955 if when: 1956 table = f"{table} {when}" 1957 1958 changes = self.sql(expression, "changes") 1959 changes = f" {changes}" if changes else "" 1960 1961 rows_from = self.expressions(expression, key="rows_from") 1962 if rows_from: 1963 table = f"ROWS FROM {self.wrap(rows_from)}" 1964 1965 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1966 1967 def tablesample_sql( 1968 self, 1969 expression: exp.TableSample, 1970 tablesample_keyword: t.Optional[str] = None, 1971 ) -> str: 1972 method = self.sql(expression, "method") 1973 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1974 numerator = self.sql(expression, "bucket_numerator") 1975 denominator = self.sql(expression, "bucket_denominator") 1976 field = self.sql(expression, "bucket_field") 1977 field = f" ON {field}" if field else "" 1978 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1979 seed = self.sql(expression, "seed") 1980 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1981 1982 size = self.sql(expression, "size") 1983 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1984 size = f"{size} ROWS" 1985 1986 percent = self.sql(expression, "percent") 1987 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1988 percent = f"{percent} PERCENT" 1989 1990 expr = f"{bucket}{percent}{size}" 1991 if self.TABLESAMPLE_REQUIRES_PARENS: 1992 expr = f"({expr})" 1993 1994 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 1995 1996 def pivot_sql(self, expression: exp.Pivot) -> str: 1997 expressions = self.expressions(expression, flat=True) 1998 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 1999 2000 if expression.this: 2001 this = self.sql(expression, "this") 2002 if not expressions: 2003 return f"UNPIVOT {this}" 2004 2005 on = f"{self.seg('ON')} {expressions}" 2006 into = self.sql(expression, "into") 2007 into = f"{self.seg('INTO')} {into}" if into else "" 2008 using = self.expressions(expression, key="using", flat=True) 2009 using = f"{self.seg('USING')} {using}" if using else "" 2010 group = self.sql(expression, "group") 2011 return f"{direction} {this}{on}{into}{using}{group}" 2012 2013 alias = self.sql(expression, "alias") 2014 alias = f" AS {alias}" if alias else "" 2015 2016 field = self.sql(expression, "field") 2017 2018 include_nulls = expression.args.get("include_nulls") 2019 if include_nulls is not None: 2020 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2021 else: 2022 nulls = "" 2023 2024 default_on_null = self.sql(expression, "default_on_null") 2025 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2026 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2027 2028 def version_sql(self, expression: exp.Version) -> str: 2029 this = f"FOR {expression.name}" 2030 kind = expression.text("kind") 2031 expr = self.sql(expression, "expression") 2032 return f"{this} {kind} {expr}" 2033 2034 def tuple_sql(self, expression: exp.Tuple) -> str: 2035 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2036 2037 def update_sql(self, expression: exp.Update) -> str: 2038 this = self.sql(expression, "this") 2039 set_sql = self.expressions(expression, flat=True) 2040 from_sql = self.sql(expression, "from") 2041 where_sql = self.sql(expression, "where") 2042 returning = self.sql(expression, "returning") 2043 order = self.sql(expression, "order") 2044 limit = self.sql(expression, "limit") 2045 if self.RETURNING_END: 2046 expression_sql = f"{from_sql}{where_sql}{returning}" 2047 else: 2048 expression_sql = f"{returning}{from_sql}{where_sql}" 2049 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2050 return self.prepend_ctes(expression, sql) 2051 2052 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2053 values_as_table = values_as_table and self.VALUES_AS_TABLE 2054 2055 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2056 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2057 args = self.expressions(expression) 2058 alias = self.sql(expression, "alias") 2059 values = f"VALUES{self.seg('')}{args}" 2060 values = ( 2061 f"({values})" 2062 if self.WRAP_DERIVED_VALUES 2063 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2064 else values 2065 ) 2066 return f"{values} AS {alias}" if alias else values 2067 2068 # Converts `VALUES...` expression into a series of select unions. 2069 alias_node = expression.args.get("alias") 2070 column_names = alias_node and alias_node.columns 2071 2072 selects: t.List[exp.Query] = [] 2073 2074 for i, tup in enumerate(expression.expressions): 2075 row = tup.expressions 2076 2077 if i == 0 and column_names: 2078 row = [ 2079 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2080 ] 2081 2082 selects.append(exp.Select(expressions=row)) 2083 2084 if self.pretty: 2085 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2086 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2087 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2088 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2089 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2090 2091 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2092 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2093 return f"({unions}){alias}" 2094 2095 def var_sql(self, expression: exp.Var) -> str: 2096 return self.sql(expression, "this") 2097 2098 @unsupported_args("expressions") 2099 def into_sql(self, expression: exp.Into) -> str: 2100 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2101 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2102 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2103 2104 def from_sql(self, expression: exp.From) -> str: 2105 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2106 2107 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2108 grouping_sets = self.expressions(expression, indent=False) 2109 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2110 2111 def rollup_sql(self, expression: exp.Rollup) -> str: 2112 expressions = self.expressions(expression, indent=False) 2113 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2114 2115 def cube_sql(self, expression: exp.Cube) -> str: 2116 expressions = self.expressions(expression, indent=False) 2117 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2118 2119 def group_sql(self, expression: exp.Group) -> str: 2120 group_by_all = expression.args.get("all") 2121 if group_by_all is True: 2122 modifier = " ALL" 2123 elif group_by_all is False: 2124 modifier = " DISTINCT" 2125 else: 2126 modifier = "" 2127 2128 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2129 2130 grouping_sets = self.expressions(expression, key="grouping_sets") 2131 cube = self.expressions(expression, key="cube") 2132 rollup = self.expressions(expression, key="rollup") 2133 2134 groupings = csv( 2135 self.seg(grouping_sets) if grouping_sets else "", 2136 self.seg(cube) if cube else "", 2137 self.seg(rollup) if rollup else "", 2138 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2139 sep=self.GROUPINGS_SEP, 2140 ) 2141 2142 if ( 2143 expression.expressions 2144 and groupings 2145 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2146 ): 2147 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2148 2149 return f"{group_by}{groupings}" 2150 2151 def having_sql(self, expression: exp.Having) -> str: 2152 this = self.indent(self.sql(expression, "this")) 2153 return f"{self.seg('HAVING')}{self.sep()}{this}" 2154 2155 def connect_sql(self, expression: exp.Connect) -> str: 2156 start = self.sql(expression, "start") 2157 start = self.seg(f"START WITH {start}") if start else "" 2158 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2159 connect = self.sql(expression, "connect") 2160 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2161 return start + connect 2162 2163 def prior_sql(self, expression: exp.Prior) -> str: 2164 return f"PRIOR {self.sql(expression, 'this')}" 2165 2166 def join_sql(self, expression: exp.Join) -> str: 2167 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2168 side = None 2169 else: 2170 side = expression.side 2171 2172 op_sql = " ".join( 2173 op 2174 for op in ( 2175 expression.method, 2176 "GLOBAL" if expression.args.get("global") else None, 2177 side, 2178 expression.kind, 2179 expression.hint if self.JOIN_HINTS else None, 2180 ) 2181 if op 2182 ) 2183 match_cond = self.sql(expression, "match_condition") 2184 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2185 on_sql = self.sql(expression, "on") 2186 using = expression.args.get("using") 2187 2188 if not on_sql and using: 2189 on_sql = csv(*(self.sql(column) for column in using)) 2190 2191 this = expression.this 2192 this_sql = self.sql(this) 2193 2194 exprs = self.expressions(expression) 2195 if exprs: 2196 this_sql = f"{this_sql},{self.seg(exprs)}" 2197 2198 if on_sql: 2199 on_sql = self.indent(on_sql, skip_first=True) 2200 space = self.seg(" " * self.pad) if self.pretty else " " 2201 if using: 2202 on_sql = f"{space}USING ({on_sql})" 2203 else: 2204 on_sql = f"{space}ON {on_sql}" 2205 elif not op_sql: 2206 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2207 return f" {this_sql}" 2208 2209 return f", {this_sql}" 2210 2211 if op_sql != "STRAIGHT_JOIN": 2212 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2213 2214 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2215 2216 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2217 args = self.expressions(expression, flat=True) 2218 args = f"({args})" if len(args.split(",")) > 1 else args 2219 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2220 2221 def lateral_op(self, expression: exp.Lateral) -> str: 2222 cross_apply = expression.args.get("cross_apply") 2223 2224 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2225 if cross_apply is True: 2226 op = "INNER JOIN " 2227 elif cross_apply is False: 2228 op = "LEFT JOIN " 2229 else: 2230 op = "" 2231 2232 return f"{op}LATERAL" 2233 2234 def lateral_sql(self, expression: exp.Lateral) -> str: 2235 this = self.sql(expression, "this") 2236 2237 if expression.args.get("view"): 2238 alias = expression.args["alias"] 2239 columns = self.expressions(alias, key="columns", flat=True) 2240 table = f" {alias.name}" if alias.name else "" 2241 columns = f" AS {columns}" if columns else "" 2242 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2243 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2244 2245 alias = self.sql(expression, "alias") 2246 alias = f" AS {alias}" if alias else "" 2247 return f"{self.lateral_op(expression)} {this}{alias}" 2248 2249 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2250 this = self.sql(expression, "this") 2251 2252 args = [ 2253 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2254 for e in (expression.args.get(k) for k in ("offset", "expression")) 2255 if e 2256 ] 2257 2258 args_sql = ", ".join(self.sql(e) for e in args) 2259 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2260 expressions = self.expressions(expression, flat=True) 2261 expressions = f" BY {expressions}" if expressions else "" 2262 2263 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}" 2264 2265 def offset_sql(self, expression: exp.Offset) -> str: 2266 this = self.sql(expression, "this") 2267 value = expression.expression 2268 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2269 expressions = self.expressions(expression, flat=True) 2270 expressions = f" BY {expressions}" if expressions else "" 2271 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2272 2273 def setitem_sql(self, expression: exp.SetItem) -> str: 2274 kind = self.sql(expression, "kind") 2275 kind = f"{kind} " if kind else "" 2276 this = self.sql(expression, "this") 2277 expressions = self.expressions(expression) 2278 collate = self.sql(expression, "collate") 2279 collate = f" COLLATE {collate}" if collate else "" 2280 global_ = "GLOBAL " if expression.args.get("global") else "" 2281 return f"{global_}{kind}{this}{expressions}{collate}" 2282 2283 def set_sql(self, expression: exp.Set) -> str: 2284 expressions = ( 2285 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2286 ) 2287 tag = " TAG" if expression.args.get("tag") else "" 2288 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2289 2290 def pragma_sql(self, expression: exp.Pragma) -> str: 2291 return f"PRAGMA {self.sql(expression, 'this')}" 2292 2293 def lock_sql(self, expression: exp.Lock) -> str: 2294 if not self.LOCKING_READS_SUPPORTED: 2295 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2296 return "" 2297 2298 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2299 expressions = self.expressions(expression, flat=True) 2300 expressions = f" OF {expressions}" if expressions else "" 2301 wait = expression.args.get("wait") 2302 2303 if wait is not None: 2304 if isinstance(wait, exp.Literal): 2305 wait = f" WAIT {self.sql(wait)}" 2306 else: 2307 wait = " NOWAIT" if wait else " SKIP LOCKED" 2308 2309 return f"{lock_type}{expressions}{wait or ''}" 2310 2311 def literal_sql(self, expression: exp.Literal) -> str: 2312 text = expression.this or "" 2313 if expression.is_string: 2314 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2315 return text 2316 2317 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2318 if self.dialect.ESCAPED_SEQUENCES: 2319 to_escaped = self.dialect.ESCAPED_SEQUENCES 2320 text = "".join( 2321 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2322 ) 2323 2324 return self._replace_line_breaks(text).replace( 2325 self.dialect.QUOTE_END, self._escaped_quote_end 2326 ) 2327 2328 def loaddata_sql(self, expression: exp.LoadData) -> str: 2329 local = " LOCAL" if expression.args.get("local") else "" 2330 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2331 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2332 this = f" INTO TABLE {self.sql(expression, 'this')}" 2333 partition = self.sql(expression, "partition") 2334 partition = f" {partition}" if partition else "" 2335 input_format = self.sql(expression, "input_format") 2336 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2337 serde = self.sql(expression, "serde") 2338 serde = f" SERDE {serde}" if serde else "" 2339 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2340 2341 def null_sql(self, *_) -> str: 2342 return "NULL" 2343 2344 def boolean_sql(self, expression: exp.Boolean) -> str: 2345 return "TRUE" if expression.this else "FALSE" 2346 2347 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2348 this = self.sql(expression, "this") 2349 this = f"{this} " if this else this 2350 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2351 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2352 2353 def withfill_sql(self, expression: exp.WithFill) -> str: 2354 from_sql = self.sql(expression, "from") 2355 from_sql = f" FROM {from_sql}" if from_sql else "" 2356 to_sql = self.sql(expression, "to") 2357 to_sql = f" TO {to_sql}" if to_sql else "" 2358 step_sql = self.sql(expression, "step") 2359 step_sql = f" STEP {step_sql}" if step_sql else "" 2360 interpolated_values = [ 2361 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2362 if isinstance(e, exp.Alias) 2363 else self.sql(e, "this") 2364 for e in expression.args.get("interpolate") or [] 2365 ] 2366 interpolate = ( 2367 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2368 ) 2369 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2370 2371 def cluster_sql(self, expression: exp.Cluster) -> str: 2372 return self.op_expressions("CLUSTER BY", expression) 2373 2374 def distribute_sql(self, expression: exp.Distribute) -> str: 2375 return self.op_expressions("DISTRIBUTE BY", expression) 2376 2377 def sort_sql(self, expression: exp.Sort) -> str: 2378 return self.op_expressions("SORT BY", expression) 2379 2380 def ordered_sql(self, expression: exp.Ordered) -> str: 2381 desc = expression.args.get("desc") 2382 asc = not desc 2383 2384 nulls_first = expression.args.get("nulls_first") 2385 nulls_last = not nulls_first 2386 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2387 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2388 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2389 2390 this = self.sql(expression, "this") 2391 2392 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2393 nulls_sort_change = "" 2394 if nulls_first and ( 2395 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2396 ): 2397 nulls_sort_change = " NULLS FIRST" 2398 elif ( 2399 nulls_last 2400 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2401 and not nulls_are_last 2402 ): 2403 nulls_sort_change = " NULLS LAST" 2404 2405 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2406 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2407 window = expression.find_ancestor(exp.Window, exp.Select) 2408 if isinstance(window, exp.Window) and window.args.get("spec"): 2409 self.unsupported( 2410 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2411 ) 2412 nulls_sort_change = "" 2413 elif self.NULL_ORDERING_SUPPORTED is False and ( 2414 (asc and nulls_sort_change == " NULLS LAST") 2415 or (desc and nulls_sort_change == " NULLS FIRST") 2416 ): 2417 # BigQuery does not allow these ordering/nulls combinations when used under 2418 # an aggregation func or under a window containing one 2419 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2420 2421 if isinstance(ancestor, exp.Window): 2422 ancestor = ancestor.this 2423 if isinstance(ancestor, exp.AggFunc): 2424 self.unsupported( 2425 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2426 ) 2427 nulls_sort_change = "" 2428 elif self.NULL_ORDERING_SUPPORTED is None: 2429 if expression.this.is_int: 2430 self.unsupported( 2431 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2432 ) 2433 elif not isinstance(expression.this, exp.Rand): 2434 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2435 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2436 nulls_sort_change = "" 2437 2438 with_fill = self.sql(expression, "with_fill") 2439 with_fill = f" {with_fill}" if with_fill else "" 2440 2441 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2442 2443 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2444 window_frame = self.sql(expression, "window_frame") 2445 window_frame = f"{window_frame} " if window_frame else "" 2446 2447 this = self.sql(expression, "this") 2448 2449 return f"{window_frame}{this}" 2450 2451 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2452 partition = self.partition_by_sql(expression) 2453 order = self.sql(expression, "order") 2454 measures = self.expressions(expression, key="measures") 2455 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2456 rows = self.sql(expression, "rows") 2457 rows = self.seg(rows) if rows else "" 2458 after = self.sql(expression, "after") 2459 after = self.seg(after) if after else "" 2460 pattern = self.sql(expression, "pattern") 2461 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2462 definition_sqls = [ 2463 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2464 for definition in expression.args.get("define", []) 2465 ] 2466 definitions = self.expressions(sqls=definition_sqls) 2467 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2468 body = "".join( 2469 ( 2470 partition, 2471 order, 2472 measures, 2473 rows, 2474 after, 2475 pattern, 2476 define, 2477 ) 2478 ) 2479 alias = self.sql(expression, "alias") 2480 alias = f" {alias}" if alias else "" 2481 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2482 2483 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2484 limit = expression.args.get("limit") 2485 2486 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2487 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2488 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2489 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2490 2491 return csv( 2492 *sqls, 2493 *[self.sql(join) for join in expression.args.get("joins") or []], 2494 self.sql(expression, "connect"), 2495 self.sql(expression, "match"), 2496 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2497 self.sql(expression, "prewhere"), 2498 self.sql(expression, "where"), 2499 self.sql(expression, "group"), 2500 self.sql(expression, "having"), 2501 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2502 self.sql(expression, "order"), 2503 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2504 *self.after_limit_modifiers(expression), 2505 self.options_modifier(expression), 2506 sep="", 2507 ) 2508 2509 def options_modifier(self, expression: exp.Expression) -> str: 2510 options = self.expressions(expression, key="options") 2511 return f" {options}" if options else "" 2512 2513 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2514 return "" 2515 2516 def offset_limit_modifiers( 2517 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2518 ) -> t.List[str]: 2519 return [ 2520 self.sql(expression, "offset") if fetch else self.sql(limit), 2521 self.sql(limit) if fetch else self.sql(expression, "offset"), 2522 ] 2523 2524 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2525 locks = self.expressions(expression, key="locks", sep=" ") 2526 locks = f" {locks}" if locks else "" 2527 return [locks, self.sql(expression, "sample")] 2528 2529 def select_sql(self, expression: exp.Select) -> str: 2530 into = expression.args.get("into") 2531 if not self.SUPPORTS_SELECT_INTO and into: 2532 into.pop() 2533 2534 hint = self.sql(expression, "hint") 2535 distinct = self.sql(expression, "distinct") 2536 distinct = f" {distinct}" if distinct else "" 2537 kind = self.sql(expression, "kind") 2538 2539 limit = expression.args.get("limit") 2540 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2541 top = self.limit_sql(limit, top=True) 2542 limit.pop() 2543 else: 2544 top = "" 2545 2546 expressions = self.expressions(expression) 2547 2548 if kind: 2549 if kind in self.SELECT_KINDS: 2550 kind = f" AS {kind}" 2551 else: 2552 if kind == "STRUCT": 2553 expressions = self.expressions( 2554 sqls=[ 2555 self.sql( 2556 exp.Struct( 2557 expressions=[ 2558 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2559 if isinstance(e, exp.Alias) 2560 else e 2561 for e in expression.expressions 2562 ] 2563 ) 2564 ) 2565 ] 2566 ) 2567 kind = "" 2568 2569 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2570 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2571 2572 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2573 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2574 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2575 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2576 sql = self.query_modifiers( 2577 expression, 2578 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2579 self.sql(expression, "into", comment=False), 2580 self.sql(expression, "from", comment=False), 2581 ) 2582 2583 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2584 if expression.args.get("with"): 2585 sql = self.maybe_comment(sql, expression) 2586 expression.pop_comments() 2587 2588 sql = self.prepend_ctes(expression, sql) 2589 2590 if not self.SUPPORTS_SELECT_INTO and into: 2591 if into.args.get("temporary"): 2592 table_kind = " TEMPORARY" 2593 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2594 table_kind = " UNLOGGED" 2595 else: 2596 table_kind = "" 2597 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2598 2599 return sql 2600 2601 def schema_sql(self, expression: exp.Schema) -> str: 2602 this = self.sql(expression, "this") 2603 sql = self.schema_columns_sql(expression) 2604 return f"{this} {sql}" if this and sql else this or sql 2605 2606 def schema_columns_sql(self, expression: exp.Schema) -> str: 2607 if expression.expressions: 2608 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2609 return "" 2610 2611 def star_sql(self, expression: exp.Star) -> str: 2612 except_ = self.expressions(expression, key="except", flat=True) 2613 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2614 replace = self.expressions(expression, key="replace", flat=True) 2615 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2616 rename = self.expressions(expression, key="rename", flat=True) 2617 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2618 return f"*{except_}{replace}{rename}" 2619 2620 def parameter_sql(self, expression: exp.Parameter) -> str: 2621 this = self.sql(expression, "this") 2622 return f"{self.PARAMETER_TOKEN}{this}" 2623 2624 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2625 this = self.sql(expression, "this") 2626 kind = expression.text("kind") 2627 if kind: 2628 kind = f"{kind}." 2629 return f"@@{kind}{this}" 2630 2631 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2632 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2633 2634 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2635 alias = self.sql(expression, "alias") 2636 alias = f"{sep}{alias}" if alias else "" 2637 sample = self.sql(expression, "sample") 2638 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2639 alias = f"{sample}{alias}" 2640 2641 # Set to None so it's not generated again by self.query_modifiers() 2642 expression.set("sample", None) 2643 2644 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2645 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2646 return self.prepend_ctes(expression, sql) 2647 2648 def qualify_sql(self, expression: exp.Qualify) -> str: 2649 this = self.indent(self.sql(expression, "this")) 2650 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2651 2652 def unnest_sql(self, expression: exp.Unnest) -> str: 2653 args = self.expressions(expression, flat=True) 2654 2655 alias = expression.args.get("alias") 2656 offset = expression.args.get("offset") 2657 2658 if self.UNNEST_WITH_ORDINALITY: 2659 if alias and isinstance(offset, exp.Expression): 2660 alias.append("columns", offset) 2661 2662 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2663 columns = alias.columns 2664 alias = self.sql(columns[0]) if columns else "" 2665 else: 2666 alias = self.sql(alias) 2667 2668 alias = f" AS {alias}" if alias else alias 2669 if self.UNNEST_WITH_ORDINALITY: 2670 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2671 else: 2672 if isinstance(offset, exp.Expression): 2673 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2674 elif offset: 2675 suffix = f"{alias} WITH OFFSET" 2676 else: 2677 suffix = alias 2678 2679 return f"UNNEST({args}){suffix}" 2680 2681 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2682 return "" 2683 2684 def where_sql(self, expression: exp.Where) -> str: 2685 this = self.indent(self.sql(expression, "this")) 2686 return f"{self.seg('WHERE')}{self.sep()}{this}" 2687 2688 def window_sql(self, expression: exp.Window) -> str: 2689 this = self.sql(expression, "this") 2690 partition = self.partition_by_sql(expression) 2691 order = expression.args.get("order") 2692 order = self.order_sql(order, flat=True) if order else "" 2693 spec = self.sql(expression, "spec") 2694 alias = self.sql(expression, "alias") 2695 over = self.sql(expression, "over") or "OVER" 2696 2697 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2698 2699 first = expression.args.get("first") 2700 if first is None: 2701 first = "" 2702 else: 2703 first = "FIRST" if first else "LAST" 2704 2705 if not partition and not order and not spec and alias: 2706 return f"{this} {alias}" 2707 2708 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2709 return f"{this} ({args})" 2710 2711 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2712 partition = self.expressions(expression, key="partition_by", flat=True) 2713 return f"PARTITION BY {partition}" if partition else "" 2714 2715 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2716 kind = self.sql(expression, "kind") 2717 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2718 end = ( 2719 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2720 or "CURRENT ROW" 2721 ) 2722 return f"{kind} BETWEEN {start} AND {end}" 2723 2724 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2725 this = self.sql(expression, "this") 2726 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2727 return f"{this} WITHIN GROUP ({expression_sql})" 2728 2729 def between_sql(self, expression: exp.Between) -> str: 2730 this = self.sql(expression, "this") 2731 low = self.sql(expression, "low") 2732 high = self.sql(expression, "high") 2733 return f"{this} BETWEEN {low} AND {high}" 2734 2735 def bracket_offset_expressions( 2736 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2737 ) -> t.List[exp.Expression]: 2738 return apply_index_offset( 2739 expression.this, 2740 expression.expressions, 2741 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2742 ) 2743 2744 def bracket_sql(self, expression: exp.Bracket) -> str: 2745 expressions = self.bracket_offset_expressions(expression) 2746 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2747 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2748 2749 def all_sql(self, expression: exp.All) -> str: 2750 return f"ALL {self.wrap(expression)}" 2751 2752 def any_sql(self, expression: exp.Any) -> str: 2753 this = self.sql(expression, "this") 2754 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2755 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2756 this = self.wrap(this) 2757 return f"ANY{this}" 2758 return f"ANY {this}" 2759 2760 def exists_sql(self, expression: exp.Exists) -> str: 2761 return f"EXISTS{self.wrap(expression)}" 2762 2763 def case_sql(self, expression: exp.Case) -> str: 2764 this = self.sql(expression, "this") 2765 statements = [f"CASE {this}" if this else "CASE"] 2766 2767 for e in expression.args["ifs"]: 2768 statements.append(f"WHEN {self.sql(e, 'this')}") 2769 statements.append(f"THEN {self.sql(e, 'true')}") 2770 2771 default = self.sql(expression, "default") 2772 2773 if default: 2774 statements.append(f"ELSE {default}") 2775 2776 statements.append("END") 2777 2778 if self.pretty and self.too_wide(statements): 2779 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2780 2781 return " ".join(statements) 2782 2783 def constraint_sql(self, expression: exp.Constraint) -> str: 2784 this = self.sql(expression, "this") 2785 expressions = self.expressions(expression, flat=True) 2786 return f"CONSTRAINT {this} {expressions}" 2787 2788 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2789 order = expression.args.get("order") 2790 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2791 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2792 2793 def extract_sql(self, expression: exp.Extract) -> str: 2794 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2795 expression_sql = self.sql(expression, "expression") 2796 return f"EXTRACT({this} FROM {expression_sql})" 2797 2798 def trim_sql(self, expression: exp.Trim) -> str: 2799 trim_type = self.sql(expression, "position") 2800 2801 if trim_type == "LEADING": 2802 func_name = "LTRIM" 2803 elif trim_type == "TRAILING": 2804 func_name = "RTRIM" 2805 else: 2806 func_name = "TRIM" 2807 2808 return self.func(func_name, expression.this, expression.expression) 2809 2810 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2811 args = expression.expressions 2812 if isinstance(expression, exp.ConcatWs): 2813 args = args[1:] # Skip the delimiter 2814 2815 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2816 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2817 2818 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2819 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2820 2821 return args 2822 2823 def concat_sql(self, expression: exp.Concat) -> str: 2824 expressions = self.convert_concat_args(expression) 2825 2826 # Some dialects don't allow a single-argument CONCAT call 2827 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2828 return self.sql(expressions[0]) 2829 2830 return self.func("CONCAT", *expressions) 2831 2832 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2833 return self.func( 2834 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2835 ) 2836 2837 def check_sql(self, expression: exp.Check) -> str: 2838 this = self.sql(expression, key="this") 2839 return f"CHECK ({this})" 2840 2841 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2842 expressions = self.expressions(expression, flat=True) 2843 expressions = f" ({expressions})" if expressions else "" 2844 reference = self.sql(expression, "reference") 2845 reference = f" {reference}" if reference else "" 2846 delete = self.sql(expression, "delete") 2847 delete = f" ON DELETE {delete}" if delete else "" 2848 update = self.sql(expression, "update") 2849 update = f" ON UPDATE {update}" if update else "" 2850 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2851 2852 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2853 expressions = self.expressions(expression, flat=True) 2854 options = self.expressions(expression, key="options", flat=True, sep=" ") 2855 options = f" {options}" if options else "" 2856 return f"PRIMARY KEY ({expressions}){options}" 2857 2858 def if_sql(self, expression: exp.If) -> str: 2859 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2860 2861 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2862 modifier = expression.args.get("modifier") 2863 modifier = f" {modifier}" if modifier else "" 2864 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2865 2866 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2867 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2868 2869 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2870 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2871 2872 if expression.args.get("escape"): 2873 path = self.escape_str(path) 2874 2875 if self.QUOTE_JSON_PATH: 2876 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2877 2878 return path 2879 2880 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2881 if isinstance(expression, exp.JSONPathPart): 2882 transform = self.TRANSFORMS.get(expression.__class__) 2883 if not callable(transform): 2884 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2885 return "" 2886 2887 return transform(self, expression) 2888 2889 if isinstance(expression, int): 2890 return str(expression) 2891 2892 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2893 escaped = expression.replace("'", "\\'") 2894 escaped = f"\\'{expression}\\'" 2895 else: 2896 escaped = expression.replace('"', '\\"') 2897 escaped = f'"{escaped}"' 2898 2899 return escaped 2900 2901 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2902 return f"{self.sql(expression, 'this')} FORMAT JSON" 2903 2904 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2905 null_handling = expression.args.get("null_handling") 2906 null_handling = f" {null_handling}" if null_handling else "" 2907 2908 unique_keys = expression.args.get("unique_keys") 2909 if unique_keys is not None: 2910 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2911 else: 2912 unique_keys = "" 2913 2914 return_type = self.sql(expression, "return_type") 2915 return_type = f" RETURNING {return_type}" if return_type else "" 2916 encoding = self.sql(expression, "encoding") 2917 encoding = f" ENCODING {encoding}" if encoding else "" 2918 2919 return self.func( 2920 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2921 *expression.expressions, 2922 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2923 ) 2924 2925 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2926 return self.jsonobject_sql(expression) 2927 2928 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2929 null_handling = expression.args.get("null_handling") 2930 null_handling = f" {null_handling}" if null_handling else "" 2931 return_type = self.sql(expression, "return_type") 2932 return_type = f" RETURNING {return_type}" if return_type else "" 2933 strict = " STRICT" if expression.args.get("strict") else "" 2934 return self.func( 2935 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2936 ) 2937 2938 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2939 this = self.sql(expression, "this") 2940 order = self.sql(expression, "order") 2941 null_handling = expression.args.get("null_handling") 2942 null_handling = f" {null_handling}" if null_handling else "" 2943 return_type = self.sql(expression, "return_type") 2944 return_type = f" RETURNING {return_type}" if return_type else "" 2945 strict = " STRICT" if expression.args.get("strict") else "" 2946 return self.func( 2947 "JSON_ARRAYAGG", 2948 this, 2949 suffix=f"{order}{null_handling}{return_type}{strict})", 2950 ) 2951 2952 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2953 path = self.sql(expression, "path") 2954 path = f" PATH {path}" if path else "" 2955 nested_schema = self.sql(expression, "nested_schema") 2956 2957 if nested_schema: 2958 return f"NESTED{path} {nested_schema}" 2959 2960 this = self.sql(expression, "this") 2961 kind = self.sql(expression, "kind") 2962 kind = f" {kind}" if kind else "" 2963 return f"{this}{kind}{path}" 2964 2965 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2966 return self.func("COLUMNS", *expression.expressions) 2967 2968 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2969 this = self.sql(expression, "this") 2970 path = self.sql(expression, "path") 2971 path = f", {path}" if path else "" 2972 error_handling = expression.args.get("error_handling") 2973 error_handling = f" {error_handling}" if error_handling else "" 2974 empty_handling = expression.args.get("empty_handling") 2975 empty_handling = f" {empty_handling}" if empty_handling else "" 2976 schema = self.sql(expression, "schema") 2977 return self.func( 2978 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2979 ) 2980 2981 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2982 this = self.sql(expression, "this") 2983 kind = self.sql(expression, "kind") 2984 path = self.sql(expression, "path") 2985 path = f" {path}" if path else "" 2986 as_json = " AS JSON" if expression.args.get("as_json") else "" 2987 return f"{this} {kind}{path}{as_json}" 2988 2989 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2990 this = self.sql(expression, "this") 2991 path = self.sql(expression, "path") 2992 path = f", {path}" if path else "" 2993 expressions = self.expressions(expression) 2994 with_ = ( 2995 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2996 if expressions 2997 else "" 2998 ) 2999 return f"OPENJSON({this}{path}){with_}" 3000 3001 def in_sql(self, expression: exp.In) -> str: 3002 query = expression.args.get("query") 3003 unnest = expression.args.get("unnest") 3004 field = expression.args.get("field") 3005 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3006 3007 if query: 3008 in_sql = self.sql(query) 3009 elif unnest: 3010 in_sql = self.in_unnest_op(unnest) 3011 elif field: 3012 in_sql = self.sql(field) 3013 else: 3014 in_sql = f"({self.expressions(expression, flat=True)})" 3015 3016 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3017 3018 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3019 return f"(SELECT {self.sql(unnest)})" 3020 3021 def interval_sql(self, expression: exp.Interval) -> str: 3022 unit = self.sql(expression, "unit") 3023 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3024 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3025 unit = f" {unit}" if unit else "" 3026 3027 if self.SINGLE_STRING_INTERVAL: 3028 this = expression.this.name if expression.this else "" 3029 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3030 3031 this = self.sql(expression, "this") 3032 if this: 3033 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3034 this = f" {this}" if unwrapped else f" ({this})" 3035 3036 return f"INTERVAL{this}{unit}" 3037 3038 def return_sql(self, expression: exp.Return) -> str: 3039 return f"RETURN {self.sql(expression, 'this')}" 3040 3041 def reference_sql(self, expression: exp.Reference) -> str: 3042 this = self.sql(expression, "this") 3043 expressions = self.expressions(expression, flat=True) 3044 expressions = f"({expressions})" if expressions else "" 3045 options = self.expressions(expression, key="options", flat=True, sep=" ") 3046 options = f" {options}" if options else "" 3047 return f"REFERENCES {this}{expressions}{options}" 3048 3049 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3050 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3051 parent = expression.parent 3052 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3053 return self.func( 3054 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3055 ) 3056 3057 def paren_sql(self, expression: exp.Paren) -> str: 3058 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3059 return f"({sql}{self.seg(')', sep='')}" 3060 3061 def neg_sql(self, expression: exp.Neg) -> str: 3062 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3063 this_sql = self.sql(expression, "this") 3064 sep = " " if this_sql[0] == "-" else "" 3065 return f"-{sep}{this_sql}" 3066 3067 def not_sql(self, expression: exp.Not) -> str: 3068 return f"NOT {self.sql(expression, 'this')}" 3069 3070 def alias_sql(self, expression: exp.Alias) -> str: 3071 alias = self.sql(expression, "alias") 3072 alias = f" AS {alias}" if alias else "" 3073 return f"{self.sql(expression, 'this')}{alias}" 3074 3075 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3076 alias = expression.args["alias"] 3077 3078 identifier_alias = isinstance(alias, exp.Identifier) 3079 literal_alias = isinstance(alias, exp.Literal) 3080 3081 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3082 alias.replace(exp.Literal.string(alias.output_name)) 3083 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3084 alias.replace(exp.to_identifier(alias.output_name)) 3085 3086 return self.alias_sql(expression) 3087 3088 def aliases_sql(self, expression: exp.Aliases) -> str: 3089 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3090 3091 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3092 this = self.sql(expression, "this") 3093 index = self.sql(expression, "expression") 3094 return f"{this} AT {index}" 3095 3096 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3097 this = self.sql(expression, "this") 3098 zone = self.sql(expression, "zone") 3099 return f"{this} AT TIME ZONE {zone}" 3100 3101 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3102 this = self.sql(expression, "this") 3103 zone = self.sql(expression, "zone") 3104 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3105 3106 def add_sql(self, expression: exp.Add) -> str: 3107 return self.binary(expression, "+") 3108 3109 def and_sql( 3110 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3111 ) -> str: 3112 return self.connector_sql(expression, "AND", stack) 3113 3114 def or_sql( 3115 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3116 ) -> str: 3117 return self.connector_sql(expression, "OR", stack) 3118 3119 def xor_sql( 3120 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3121 ) -> str: 3122 return self.connector_sql(expression, "XOR", stack) 3123 3124 def connector_sql( 3125 self, 3126 expression: exp.Connector, 3127 op: str, 3128 stack: t.Optional[t.List[str | exp.Expression]] = None, 3129 ) -> str: 3130 if stack is not None: 3131 if expression.expressions: 3132 stack.append(self.expressions(expression, sep=f" {op} ")) 3133 else: 3134 stack.append(expression.right) 3135 if expression.comments and self.comments: 3136 for comment in expression.comments: 3137 if comment: 3138 op += f" /*{self.pad_comment(comment)}*/" 3139 stack.extend((op, expression.left)) 3140 return op 3141 3142 stack = [expression] 3143 sqls: t.List[str] = [] 3144 ops = set() 3145 3146 while stack: 3147 node = stack.pop() 3148 if isinstance(node, exp.Connector): 3149 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3150 else: 3151 sql = self.sql(node) 3152 if sqls and sqls[-1] in ops: 3153 sqls[-1] += f" {sql}" 3154 else: 3155 sqls.append(sql) 3156 3157 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3158 return sep.join(sqls) 3159 3160 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3161 return self.binary(expression, "&") 3162 3163 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3164 return self.binary(expression, "<<") 3165 3166 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3167 return f"~{self.sql(expression, 'this')}" 3168 3169 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3170 return self.binary(expression, "|") 3171 3172 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3173 return self.binary(expression, ">>") 3174 3175 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3176 return self.binary(expression, "^") 3177 3178 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3179 format_sql = self.sql(expression, "format") 3180 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3181 to_sql = self.sql(expression, "to") 3182 to_sql = f" {to_sql}" if to_sql else "" 3183 action = self.sql(expression, "action") 3184 action = f" {action}" if action else "" 3185 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})" 3186 3187 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3188 zone = self.sql(expression, "this") 3189 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3190 3191 def collate_sql(self, expression: exp.Collate) -> str: 3192 if self.COLLATE_IS_FUNC: 3193 return self.function_fallback_sql(expression) 3194 return self.binary(expression, "COLLATE") 3195 3196 def command_sql(self, expression: exp.Command) -> str: 3197 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3198 3199 def comment_sql(self, expression: exp.Comment) -> str: 3200 this = self.sql(expression, "this") 3201 kind = expression.args["kind"] 3202 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3203 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3204 expression_sql = self.sql(expression, "expression") 3205 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3206 3207 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3208 this = self.sql(expression, "this") 3209 delete = " DELETE" if expression.args.get("delete") else "" 3210 recompress = self.sql(expression, "recompress") 3211 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3212 to_disk = self.sql(expression, "to_disk") 3213 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3214 to_volume = self.sql(expression, "to_volume") 3215 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3216 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3217 3218 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3219 where = self.sql(expression, "where") 3220 group = self.sql(expression, "group") 3221 aggregates = self.expressions(expression, key="aggregates") 3222 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3223 3224 if not (where or group or aggregates) and len(expression.expressions) == 1: 3225 return f"TTL {self.expressions(expression, flat=True)}" 3226 3227 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3228 3229 def transaction_sql(self, expression: exp.Transaction) -> str: 3230 return "BEGIN" 3231 3232 def commit_sql(self, expression: exp.Commit) -> str: 3233 chain = expression.args.get("chain") 3234 if chain is not None: 3235 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3236 3237 return f"COMMIT{chain or ''}" 3238 3239 def rollback_sql(self, expression: exp.Rollback) -> str: 3240 savepoint = expression.args.get("savepoint") 3241 savepoint = f" TO {savepoint}" if savepoint else "" 3242 return f"ROLLBACK{savepoint}" 3243 3244 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3245 this = self.sql(expression, "this") 3246 3247 dtype = self.sql(expression, "dtype") 3248 if dtype: 3249 collate = self.sql(expression, "collate") 3250 collate = f" COLLATE {collate}" if collate else "" 3251 using = self.sql(expression, "using") 3252 using = f" USING {using}" if using else "" 3253 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3254 3255 default = self.sql(expression, "default") 3256 if default: 3257 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3258 3259 comment = self.sql(expression, "comment") 3260 if comment: 3261 return f"ALTER COLUMN {this} COMMENT {comment}" 3262 3263 allow_null = expression.args.get("allow_null") 3264 drop = expression.args.get("drop") 3265 3266 if not drop and not allow_null: 3267 self.unsupported("Unsupported ALTER COLUMN syntax") 3268 3269 if allow_null is not None: 3270 keyword = "DROP" if drop else "SET" 3271 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3272 3273 return f"ALTER COLUMN {this} DROP DEFAULT" 3274 3275 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3276 this = self.sql(expression, "this") 3277 if not isinstance(expression.this, exp.Var): 3278 this = f"KEY DISTKEY {this}" 3279 return f"ALTER DISTSTYLE {this}" 3280 3281 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3282 compound = " COMPOUND" if expression.args.get("compound") else "" 3283 this = self.sql(expression, "this") 3284 expressions = self.expressions(expression, flat=True) 3285 expressions = f"({expressions})" if expressions else "" 3286 return f"ALTER{compound} SORTKEY {this or expressions}" 3287 3288 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3289 if not self.RENAME_TABLE_WITH_DB: 3290 # Remove db from tables 3291 expression = expression.transform( 3292 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3293 ).assert_is(exp.AlterRename) 3294 this = self.sql(expression, "this") 3295 return f"RENAME TO {this}" 3296 3297 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3298 exists = " IF EXISTS" if expression.args.get("exists") else "" 3299 old_column = self.sql(expression, "this") 3300 new_column = self.sql(expression, "to") 3301 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3302 3303 def alterset_sql(self, expression: exp.AlterSet) -> str: 3304 exprs = self.expressions(expression, flat=True) 3305 return f"SET {exprs}" 3306 3307 def alter_sql(self, expression: exp.Alter) -> str: 3308 actions = expression.args["actions"] 3309 3310 if isinstance(actions[0], exp.ColumnDef): 3311 actions = self.add_column_sql(expression) 3312 elif isinstance(actions[0], exp.Schema): 3313 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3314 elif isinstance(actions[0], exp.Delete): 3315 actions = self.expressions(expression, key="actions", flat=True) 3316 elif isinstance(actions[0], exp.Query): 3317 actions = "AS " + self.expressions(expression, key="actions") 3318 else: 3319 actions = self.expressions(expression, key="actions", flat=True) 3320 3321 exists = " IF EXISTS" if expression.args.get("exists") else "" 3322 on_cluster = self.sql(expression, "cluster") 3323 on_cluster = f" {on_cluster}" if on_cluster else "" 3324 only = " ONLY" if expression.args.get("only") else "" 3325 options = self.expressions(expression, key="options") 3326 options = f", {options}" if options else "" 3327 kind = self.sql(expression, "kind") 3328 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3329 3330 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3331 3332 def add_column_sql(self, expression: exp.Alter) -> str: 3333 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3334 return self.expressions( 3335 expression, 3336 key="actions", 3337 prefix="ADD COLUMN ", 3338 skip_first=True, 3339 ) 3340 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3341 3342 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3343 expressions = self.expressions(expression) 3344 exists = " IF EXISTS " if expression.args.get("exists") else " " 3345 return f"DROP{exists}{expressions}" 3346 3347 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3348 return f"ADD {self.expressions(expression)}" 3349 3350 def distinct_sql(self, expression: exp.Distinct) -> str: 3351 this = self.expressions(expression, flat=True) 3352 3353 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3354 case = exp.case() 3355 for arg in expression.expressions: 3356 case = case.when(arg.is_(exp.null()), exp.null()) 3357 this = self.sql(case.else_(f"({this})")) 3358 3359 this = f" {this}" if this else "" 3360 3361 on = self.sql(expression, "on") 3362 on = f" ON {on}" if on else "" 3363 return f"DISTINCT{this}{on}" 3364 3365 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3366 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3367 3368 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3369 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3370 3371 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3372 this_sql = self.sql(expression, "this") 3373 expression_sql = self.sql(expression, "expression") 3374 kind = "MAX" if expression.args.get("max") else "MIN" 3375 return f"{this_sql} HAVING {kind} {expression_sql}" 3376 3377 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3378 return self.sql( 3379 exp.Cast( 3380 this=exp.Div(this=expression.this, expression=expression.expression), 3381 to=exp.DataType(this=exp.DataType.Type.INT), 3382 ) 3383 ) 3384 3385 def dpipe_sql(self, expression: exp.DPipe) -> str: 3386 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3387 return self.func( 3388 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3389 ) 3390 return self.binary(expression, "||") 3391 3392 def div_sql(self, expression: exp.Div) -> str: 3393 l, r = expression.left, expression.right 3394 3395 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3396 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3397 3398 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3399 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3400 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3401 3402 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3403 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3404 return self.sql( 3405 exp.cast( 3406 l / r, 3407 to=exp.DataType.Type.BIGINT, 3408 ) 3409 ) 3410 3411 return self.binary(expression, "/") 3412 3413 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3414 return self.binary(expression, "OVERLAPS") 3415 3416 def distance_sql(self, expression: exp.Distance) -> str: 3417 return self.binary(expression, "<->") 3418 3419 def dot_sql(self, expression: exp.Dot) -> str: 3420 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3421 3422 def eq_sql(self, expression: exp.EQ) -> str: 3423 return self.binary(expression, "=") 3424 3425 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3426 return self.binary(expression, ":=") 3427 3428 def escape_sql(self, expression: exp.Escape) -> str: 3429 return self.binary(expression, "ESCAPE") 3430 3431 def glob_sql(self, expression: exp.Glob) -> str: 3432 return self.binary(expression, "GLOB") 3433 3434 def gt_sql(self, expression: exp.GT) -> str: 3435 return self.binary(expression, ">") 3436 3437 def gte_sql(self, expression: exp.GTE) -> str: 3438 return self.binary(expression, ">=") 3439 3440 def ilike_sql(self, expression: exp.ILike) -> str: 3441 return self.binary(expression, "ILIKE") 3442 3443 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3444 return self.binary(expression, "ILIKE ANY") 3445 3446 def is_sql(self, expression: exp.Is) -> str: 3447 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3448 return self.sql( 3449 expression.this if expression.expression.this else exp.not_(expression.this) 3450 ) 3451 return self.binary(expression, "IS") 3452 3453 def like_sql(self, expression: exp.Like) -> str: 3454 return self.binary(expression, "LIKE") 3455 3456 def likeany_sql(self, expression: exp.LikeAny) -> str: 3457 return self.binary(expression, "LIKE ANY") 3458 3459 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3460 return self.binary(expression, "SIMILAR TO") 3461 3462 def lt_sql(self, expression: exp.LT) -> str: 3463 return self.binary(expression, "<") 3464 3465 def lte_sql(self, expression: exp.LTE) -> str: 3466 return self.binary(expression, "<=") 3467 3468 def mod_sql(self, expression: exp.Mod) -> str: 3469 return self.binary(expression, "%") 3470 3471 def mul_sql(self, expression: exp.Mul) -> str: 3472 return self.binary(expression, "*") 3473 3474 def neq_sql(self, expression: exp.NEQ) -> str: 3475 return self.binary(expression, "<>") 3476 3477 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3478 return self.binary(expression, "IS NOT DISTINCT FROM") 3479 3480 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3481 return self.binary(expression, "IS DISTINCT FROM") 3482 3483 def slice_sql(self, expression: exp.Slice) -> str: 3484 return self.binary(expression, ":") 3485 3486 def sub_sql(self, expression: exp.Sub) -> str: 3487 return self.binary(expression, "-") 3488 3489 def trycast_sql(self, expression: exp.TryCast) -> str: 3490 return self.cast_sql(expression, safe_prefix="TRY_") 3491 3492 def try_sql(self, expression: exp.Try) -> str: 3493 if not self.TRY_SUPPORTED: 3494 self.unsupported("Unsupported TRY function") 3495 return self.sql(expression, "this") 3496 3497 return self.func("TRY", expression.this) 3498 3499 def log_sql(self, expression: exp.Log) -> str: 3500 this = expression.this 3501 expr = expression.expression 3502 3503 if self.dialect.LOG_BASE_FIRST is False: 3504 this, expr = expr, this 3505 elif self.dialect.LOG_BASE_FIRST is None and expr: 3506 if this.name in ("2", "10"): 3507 return self.func(f"LOG{this.name}", expr) 3508 3509 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3510 3511 return self.func("LOG", this, expr) 3512 3513 def use_sql(self, expression: exp.Use) -> str: 3514 kind = self.sql(expression, "kind") 3515 kind = f" {kind}" if kind else "" 3516 this = self.sql(expression, "this") 3517 this = f" {this}" if this else "" 3518 return f"USE{kind}{this}" 3519 3520 def binary(self, expression: exp.Binary, op: str) -> str: 3521 sqls: t.List[str] = [] 3522 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3523 binary_type = type(expression) 3524 3525 while stack: 3526 node = stack.pop() 3527 3528 if type(node) is binary_type: 3529 op_func = node.args.get("operator") 3530 if op_func: 3531 op = f"OPERATOR({self.sql(op_func)})" 3532 3533 stack.append(node.right) 3534 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3535 stack.append(node.left) 3536 else: 3537 sqls.append(self.sql(node)) 3538 3539 return "".join(sqls) 3540 3541 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3542 to_clause = self.sql(expression, "to") 3543 if to_clause: 3544 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3545 3546 return self.function_fallback_sql(expression) 3547 3548 def function_fallback_sql(self, expression: exp.Func) -> str: 3549 args = [] 3550 3551 for key in expression.arg_types: 3552 arg_value = expression.args.get(key) 3553 3554 if isinstance(arg_value, list): 3555 for value in arg_value: 3556 args.append(value) 3557 elif arg_value is not None: 3558 args.append(arg_value) 3559 3560 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3561 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3562 else: 3563 name = expression.sql_name() 3564 3565 return self.func(name, *args) 3566 3567 def func( 3568 self, 3569 name: str, 3570 *args: t.Optional[exp.Expression | str], 3571 prefix: str = "(", 3572 suffix: str = ")", 3573 normalize: bool = True, 3574 ) -> str: 3575 name = self.normalize_func(name) if normalize else name 3576 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3577 3578 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3579 arg_sqls = tuple( 3580 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3581 ) 3582 if self.pretty and self.too_wide(arg_sqls): 3583 return self.indent( 3584 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3585 ) 3586 return sep.join(arg_sqls) 3587 3588 def too_wide(self, args: t.Iterable) -> bool: 3589 return sum(len(arg) for arg in args) > self.max_text_width 3590 3591 def format_time( 3592 self, 3593 expression: exp.Expression, 3594 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3595 inverse_time_trie: t.Optional[t.Dict] = None, 3596 ) -> t.Optional[str]: 3597 return format_time( 3598 self.sql(expression, "format"), 3599 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3600 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3601 ) 3602 3603 def expressions( 3604 self, 3605 expression: t.Optional[exp.Expression] = None, 3606 key: t.Optional[str] = None, 3607 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3608 flat: bool = False, 3609 indent: bool = True, 3610 skip_first: bool = False, 3611 skip_last: bool = False, 3612 sep: str = ", ", 3613 prefix: str = "", 3614 dynamic: bool = False, 3615 new_line: bool = False, 3616 ) -> str: 3617 expressions = expression.args.get(key or "expressions") if expression else sqls 3618 3619 if not expressions: 3620 return "" 3621 3622 if flat: 3623 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3624 3625 num_sqls = len(expressions) 3626 result_sqls = [] 3627 3628 for i, e in enumerate(expressions): 3629 sql = self.sql(e, comment=False) 3630 if not sql: 3631 continue 3632 3633 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3634 3635 if self.pretty: 3636 if self.leading_comma: 3637 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3638 else: 3639 result_sqls.append( 3640 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3641 ) 3642 else: 3643 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3644 3645 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3646 if new_line: 3647 result_sqls.insert(0, "") 3648 result_sqls.append("") 3649 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3650 else: 3651 result_sql = "".join(result_sqls) 3652 3653 return ( 3654 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3655 if indent 3656 else result_sql 3657 ) 3658 3659 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3660 flat = flat or isinstance(expression.parent, exp.Properties) 3661 expressions_sql = self.expressions(expression, flat=flat) 3662 if flat: 3663 return f"{op} {expressions_sql}" 3664 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3665 3666 def naked_property(self, expression: exp.Property) -> str: 3667 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3668 if not property_name: 3669 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3670 return f"{property_name} {self.sql(expression, 'this')}" 3671 3672 def tag_sql(self, expression: exp.Tag) -> str: 3673 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3674 3675 def token_sql(self, token_type: TokenType) -> str: 3676 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3677 3678 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3679 this = self.sql(expression, "this") 3680 expressions = self.no_identify(self.expressions, expression) 3681 expressions = ( 3682 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3683 ) 3684 return f"{this}{expressions}" if expressions.strip() != "" else this 3685 3686 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3687 this = self.sql(expression, "this") 3688 expressions = self.expressions(expression, flat=True) 3689 return f"{this}({expressions})" 3690 3691 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3692 return self.binary(expression, "=>") 3693 3694 def when_sql(self, expression: exp.When) -> str: 3695 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3696 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3697 condition = self.sql(expression, "condition") 3698 condition = f" AND {condition}" if condition else "" 3699 3700 then_expression = expression.args.get("then") 3701 if isinstance(then_expression, exp.Insert): 3702 this = self.sql(then_expression, "this") 3703 this = f"INSERT {this}" if this else "INSERT" 3704 then = self.sql(then_expression, "expression") 3705 then = f"{this} VALUES {then}" if then else this 3706 elif isinstance(then_expression, exp.Update): 3707 if isinstance(then_expression.args.get("expressions"), exp.Star): 3708 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3709 else: 3710 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3711 else: 3712 then = self.sql(then_expression) 3713 return f"WHEN {matched}{source}{condition} THEN {then}" 3714 3715 def whens_sql(self, expression: exp.Whens) -> str: 3716 return self.expressions(expression, sep=" ", indent=False) 3717 3718 def merge_sql(self, expression: exp.Merge) -> str: 3719 table = expression.this 3720 table_alias = "" 3721 3722 hints = table.args.get("hints") 3723 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3724 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3725 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3726 3727 this = self.sql(table) 3728 using = f"USING {self.sql(expression, 'using')}" 3729 on = f"ON {self.sql(expression, 'on')}" 3730 whens = self.sql(expression, "whens") 3731 3732 returning = self.sql(expression, "returning") 3733 if returning: 3734 whens = f"{whens}{returning}" 3735 3736 sep = self.sep() 3737 3738 return self.prepend_ctes( 3739 expression, 3740 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3741 ) 3742 3743 @unsupported_args("format") 3744 def tochar_sql(self, expression: exp.ToChar) -> str: 3745 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3746 3747 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3748 if not self.SUPPORTS_TO_NUMBER: 3749 self.unsupported("Unsupported TO_NUMBER function") 3750 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3751 3752 fmt = expression.args.get("format") 3753 if not fmt: 3754 self.unsupported("Conversion format is required for TO_NUMBER") 3755 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3756 3757 return self.func("TO_NUMBER", expression.this, fmt) 3758 3759 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3760 this = self.sql(expression, "this") 3761 kind = self.sql(expression, "kind") 3762 settings_sql = self.expressions(expression, key="settings", sep=" ") 3763 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3764 return f"{this}({kind}{args})" 3765 3766 def dictrange_sql(self, expression: exp.DictRange) -> str: 3767 this = self.sql(expression, "this") 3768 max = self.sql(expression, "max") 3769 min = self.sql(expression, "min") 3770 return f"{this}(MIN {min} MAX {max})" 3771 3772 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3773 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3774 3775 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3776 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3777 3778 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3779 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3780 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3781 3782 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3783 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3784 expressions = self.expressions(expression, flat=True) 3785 expressions = f" {self.wrap(expressions)}" if expressions else "" 3786 buckets = self.sql(expression, "buckets") 3787 kind = self.sql(expression, "kind") 3788 buckets = f" BUCKETS {buckets}" if buckets else "" 3789 order = self.sql(expression, "order") 3790 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3791 3792 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3793 return "" 3794 3795 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3796 expressions = self.expressions(expression, key="expressions", flat=True) 3797 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3798 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3799 buckets = self.sql(expression, "buckets") 3800 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3801 3802 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3803 this = self.sql(expression, "this") 3804 having = self.sql(expression, "having") 3805 3806 if having: 3807 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3808 3809 return self.func("ANY_VALUE", this) 3810 3811 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3812 transform = self.func("TRANSFORM", *expression.expressions) 3813 row_format_before = self.sql(expression, "row_format_before") 3814 row_format_before = f" {row_format_before}" if row_format_before else "" 3815 record_writer = self.sql(expression, "record_writer") 3816 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3817 using = f" USING {self.sql(expression, 'command_script')}" 3818 schema = self.sql(expression, "schema") 3819 schema = f" AS {schema}" if schema else "" 3820 row_format_after = self.sql(expression, "row_format_after") 3821 row_format_after = f" {row_format_after}" if row_format_after else "" 3822 record_reader = self.sql(expression, "record_reader") 3823 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3824 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3825 3826 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3827 key_block_size = self.sql(expression, "key_block_size") 3828 if key_block_size: 3829 return f"KEY_BLOCK_SIZE = {key_block_size}" 3830 3831 using = self.sql(expression, "using") 3832 if using: 3833 return f"USING {using}" 3834 3835 parser = self.sql(expression, "parser") 3836 if parser: 3837 return f"WITH PARSER {parser}" 3838 3839 comment = self.sql(expression, "comment") 3840 if comment: 3841 return f"COMMENT {comment}" 3842 3843 visible = expression.args.get("visible") 3844 if visible is not None: 3845 return "VISIBLE" if visible else "INVISIBLE" 3846 3847 engine_attr = self.sql(expression, "engine_attr") 3848 if engine_attr: 3849 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3850 3851 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3852 if secondary_engine_attr: 3853 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3854 3855 self.unsupported("Unsupported index constraint option.") 3856 return "" 3857 3858 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3859 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3860 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3861 3862 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3863 kind = self.sql(expression, "kind") 3864 kind = f"{kind} INDEX" if kind else "INDEX" 3865 this = self.sql(expression, "this") 3866 this = f" {this}" if this else "" 3867 index_type = self.sql(expression, "index_type") 3868 index_type = f" USING {index_type}" if index_type else "" 3869 expressions = self.expressions(expression, flat=True) 3870 expressions = f" ({expressions})" if expressions else "" 3871 options = self.expressions(expression, key="options", sep=" ") 3872 options = f" {options}" if options else "" 3873 return f"{kind}{this}{index_type}{expressions}{options}" 3874 3875 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3876 if self.NVL2_SUPPORTED: 3877 return self.function_fallback_sql(expression) 3878 3879 case = exp.Case().when( 3880 expression.this.is_(exp.null()).not_(copy=False), 3881 expression.args["true"], 3882 copy=False, 3883 ) 3884 else_cond = expression.args.get("false") 3885 if else_cond: 3886 case.else_(else_cond, copy=False) 3887 3888 return self.sql(case) 3889 3890 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3891 this = self.sql(expression, "this") 3892 expr = self.sql(expression, "expression") 3893 iterator = self.sql(expression, "iterator") 3894 condition = self.sql(expression, "condition") 3895 condition = f" IF {condition}" if condition else "" 3896 return f"{this} FOR {expr} IN {iterator}{condition}" 3897 3898 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3899 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3900 3901 def opclass_sql(self, expression: exp.Opclass) -> str: 3902 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3903 3904 def predict_sql(self, expression: exp.Predict) -> str: 3905 model = self.sql(expression, "this") 3906 model = f"MODEL {model}" 3907 table = self.sql(expression, "expression") 3908 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3909 parameters = self.sql(expression, "params_struct") 3910 return self.func("PREDICT", model, table, parameters or None) 3911 3912 def forin_sql(self, expression: exp.ForIn) -> str: 3913 this = self.sql(expression, "this") 3914 expression_sql = self.sql(expression, "expression") 3915 return f"FOR {this} DO {expression_sql}" 3916 3917 def refresh_sql(self, expression: exp.Refresh) -> str: 3918 this = self.sql(expression, "this") 3919 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3920 return f"REFRESH {table}{this}" 3921 3922 def toarray_sql(self, expression: exp.ToArray) -> str: 3923 arg = expression.this 3924 if not arg.type: 3925 from sqlglot.optimizer.annotate_types import annotate_types 3926 3927 arg = annotate_types(arg) 3928 3929 if arg.is_type(exp.DataType.Type.ARRAY): 3930 return self.sql(arg) 3931 3932 cond_for_null = arg.is_(exp.null()) 3933 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3934 3935 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3936 this = expression.this 3937 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3938 return self.sql(this) 3939 3940 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 3941 3942 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 3943 this = expression.this 3944 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 3945 return self.sql(this) 3946 3947 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 3948 3949 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 3950 this = expression.this 3951 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 3952 return self.sql(this) 3953 3954 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 3955 3956 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3957 this = expression.this 3958 time_format = self.format_time(expression) 3959 3960 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3961 return self.sql( 3962 exp.cast( 3963 exp.StrToTime(this=this, format=expression.args["format"]), 3964 exp.DataType.Type.DATE, 3965 ) 3966 ) 3967 3968 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3969 return self.sql(this) 3970 3971 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 3972 3973 def unixdate_sql(self, expression: exp.UnixDate) -> str: 3974 return self.sql( 3975 exp.func( 3976 "DATEDIFF", 3977 expression.this, 3978 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 3979 "day", 3980 ) 3981 ) 3982 3983 def lastday_sql(self, expression: exp.LastDay) -> str: 3984 if self.LAST_DAY_SUPPORTS_DATE_PART: 3985 return self.function_fallback_sql(expression) 3986 3987 unit = expression.text("unit") 3988 if unit and unit != "MONTH": 3989 self.unsupported("Date parts are not supported in LAST_DAY.") 3990 3991 return self.func("LAST_DAY", expression.this) 3992 3993 def dateadd_sql(self, expression: exp.DateAdd) -> str: 3994 from sqlglot.dialects.dialect import unit_to_str 3995 3996 return self.func( 3997 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 3998 ) 3999 4000 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4001 if self.CAN_IMPLEMENT_ARRAY_ANY: 4002 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4003 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4004 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4005 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4006 4007 from sqlglot.dialects import Dialect 4008 4009 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4010 if self.dialect.__class__ != Dialect: 4011 self.unsupported("ARRAY_ANY is unsupported") 4012 4013 return self.function_fallback_sql(expression) 4014 4015 def struct_sql(self, expression: exp.Struct) -> str: 4016 expression.set( 4017 "expressions", 4018 [ 4019 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4020 if isinstance(e, exp.PropertyEQ) 4021 else e 4022 for e in expression.expressions 4023 ], 4024 ) 4025 4026 return self.function_fallback_sql(expression) 4027 4028 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4029 low = self.sql(expression, "this") 4030 high = self.sql(expression, "expression") 4031 4032 return f"{low} TO {high}" 4033 4034 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4035 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4036 tables = f" {self.expressions(expression)}" 4037 4038 exists = " IF EXISTS" if expression.args.get("exists") else "" 4039 4040 on_cluster = self.sql(expression, "cluster") 4041 on_cluster = f" {on_cluster}" if on_cluster else "" 4042 4043 identity = self.sql(expression, "identity") 4044 identity = f" {identity} IDENTITY" if identity else "" 4045 4046 option = self.sql(expression, "option") 4047 option = f" {option}" if option else "" 4048 4049 partition = self.sql(expression, "partition") 4050 partition = f" {partition}" if partition else "" 4051 4052 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4053 4054 # This transpiles T-SQL's CONVERT function 4055 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4056 def convert_sql(self, expression: exp.Convert) -> str: 4057 to = expression.this 4058 value = expression.expression 4059 style = expression.args.get("style") 4060 safe = expression.args.get("safe") 4061 strict = expression.args.get("strict") 4062 4063 if not to or not value: 4064 return "" 4065 4066 # Retrieve length of datatype and override to default if not specified 4067 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4068 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4069 4070 transformed: t.Optional[exp.Expression] = None 4071 cast = exp.Cast if strict else exp.TryCast 4072 4073 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4074 if isinstance(style, exp.Literal) and style.is_int: 4075 from sqlglot.dialects.tsql import TSQL 4076 4077 style_value = style.name 4078 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4079 if not converted_style: 4080 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4081 4082 fmt = exp.Literal.string(converted_style) 4083 4084 if to.this == exp.DataType.Type.DATE: 4085 transformed = exp.StrToDate(this=value, format=fmt) 4086 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4087 transformed = exp.StrToTime(this=value, format=fmt) 4088 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4089 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4090 elif to.this == exp.DataType.Type.TEXT: 4091 transformed = exp.TimeToStr(this=value, format=fmt) 4092 4093 if not transformed: 4094 transformed = cast(this=value, to=to, safe=safe) 4095 4096 return self.sql(transformed) 4097 4098 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4099 this = expression.this 4100 if isinstance(this, exp.JSONPathWildcard): 4101 this = self.json_path_part(this) 4102 return f".{this}" if this else "" 4103 4104 if exp.SAFE_IDENTIFIER_RE.match(this): 4105 return f".{this}" 4106 4107 this = self.json_path_part(this) 4108 return ( 4109 f"[{this}]" 4110 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4111 else f".{this}" 4112 ) 4113 4114 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4115 this = self.json_path_part(expression.this) 4116 return f"[{this}]" if this else "" 4117 4118 def _simplify_unless_literal(self, expression: E) -> E: 4119 if not isinstance(expression, exp.Literal): 4120 from sqlglot.optimizer.simplify import simplify 4121 4122 expression = simplify(expression, dialect=self.dialect) 4123 4124 return expression 4125 4126 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4127 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4128 # The first modifier here will be the one closest to the AggFunc's arg 4129 mods = sorted( 4130 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4131 key=lambda x: 0 4132 if isinstance(x, exp.HavingMax) 4133 else (1 if isinstance(x, exp.Order) else 2), 4134 ) 4135 4136 if mods: 4137 mod = mods[0] 4138 this = expression.__class__(this=mod.this.copy()) 4139 this.meta["inline"] = True 4140 mod.this.replace(this) 4141 return self.sql(expression.this) 4142 4143 agg_func = expression.find(exp.AggFunc) 4144 4145 if agg_func: 4146 return self.sql(agg_func)[:-1] + f" {text})" 4147 4148 return f"{self.sql(expression, 'this')} {text}" 4149 4150 def _replace_line_breaks(self, string: str) -> str: 4151 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4152 if self.pretty: 4153 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4154 return string 4155 4156 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4157 option = self.sql(expression, "this") 4158 4159 if expression.expressions: 4160 upper = option.upper() 4161 4162 # Snowflake FILE_FORMAT options are separated by whitespace 4163 sep = " " if upper == "FILE_FORMAT" else ", " 4164 4165 # Databricks copy/format options do not set their list of values with EQ 4166 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4167 values = self.expressions(expression, flat=True, sep=sep) 4168 return f"{option}{op}({values})" 4169 4170 value = self.sql(expression, "expression") 4171 4172 if not value: 4173 return option 4174 4175 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4176 4177 return f"{option}{op}{value}" 4178 4179 def credentials_sql(self, expression: exp.Credentials) -> str: 4180 cred_expr = expression.args.get("credentials") 4181 if isinstance(cred_expr, exp.Literal): 4182 # Redshift case: CREDENTIALS <string> 4183 credentials = self.sql(expression, "credentials") 4184 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4185 else: 4186 # Snowflake case: CREDENTIALS = (...) 4187 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4188 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4189 4190 storage = self.sql(expression, "storage") 4191 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4192 4193 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4194 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4195 4196 iam_role = self.sql(expression, "iam_role") 4197 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4198 4199 region = self.sql(expression, "region") 4200 region = f" REGION {region}" if region else "" 4201 4202 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4203 4204 def copy_sql(self, expression: exp.Copy) -> str: 4205 this = self.sql(expression, "this") 4206 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4207 4208 credentials = self.sql(expression, "credentials") 4209 credentials = self.seg(credentials) if credentials else "" 4210 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4211 files = self.expressions(expression, key="files", flat=True) 4212 4213 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4214 params = self.expressions( 4215 expression, 4216 key="params", 4217 sep=sep, 4218 new_line=True, 4219 skip_last=True, 4220 skip_first=True, 4221 indent=self.COPY_PARAMS_ARE_WRAPPED, 4222 ) 4223 4224 if params: 4225 if self.COPY_PARAMS_ARE_WRAPPED: 4226 params = f" WITH ({params})" 4227 elif not self.pretty: 4228 params = f" {params}" 4229 4230 return f"COPY{this}{kind} {files}{credentials}{params}" 4231 4232 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4233 return "" 4234 4235 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4236 on_sql = "ON" if expression.args.get("on") else "OFF" 4237 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4238 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4239 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4240 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4241 4242 if filter_col or retention_period: 4243 on_sql = self.func("ON", filter_col, retention_period) 4244 4245 return f"DATA_DELETION={on_sql}" 4246 4247 def maskingpolicycolumnconstraint_sql( 4248 self, expression: exp.MaskingPolicyColumnConstraint 4249 ) -> str: 4250 this = self.sql(expression, "this") 4251 expressions = self.expressions(expression, flat=True) 4252 expressions = f" USING ({expressions})" if expressions else "" 4253 return f"MASKING POLICY {this}{expressions}" 4254 4255 def gapfill_sql(self, expression: exp.GapFill) -> str: 4256 this = self.sql(expression, "this") 4257 this = f"TABLE {this}" 4258 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4259 4260 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4261 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4262 4263 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4264 this = self.sql(expression, "this") 4265 expr = expression.expression 4266 4267 if isinstance(expr, exp.Func): 4268 # T-SQL's CLR functions are case sensitive 4269 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4270 else: 4271 expr = self.sql(expression, "expression") 4272 4273 return self.scope_resolution(expr, this) 4274 4275 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4276 if self.PARSE_JSON_NAME is None: 4277 return self.sql(expression.this) 4278 4279 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4280 4281 def rand_sql(self, expression: exp.Rand) -> str: 4282 lower = self.sql(expression, "lower") 4283 upper = self.sql(expression, "upper") 4284 4285 if lower and upper: 4286 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4287 return self.func("RAND", expression.this) 4288 4289 def changes_sql(self, expression: exp.Changes) -> str: 4290 information = self.sql(expression, "information") 4291 information = f"INFORMATION => {information}" 4292 at_before = self.sql(expression, "at_before") 4293 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4294 end = self.sql(expression, "end") 4295 end = f"{self.seg('')}{end}" if end else "" 4296 4297 return f"CHANGES ({information}){at_before}{end}" 4298 4299 def pad_sql(self, expression: exp.Pad) -> str: 4300 prefix = "L" if expression.args.get("is_left") else "R" 4301 4302 fill_pattern = self.sql(expression, "fill_pattern") or None 4303 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4304 fill_pattern = "' '" 4305 4306 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4307 4308 def summarize_sql(self, expression: exp.Summarize) -> str: 4309 table = " TABLE" if expression.args.get("table") else "" 4310 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4311 4312 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4313 generate_series = exp.GenerateSeries(**expression.args) 4314 4315 parent = expression.parent 4316 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4317 parent = parent.parent 4318 4319 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4320 return self.sql(exp.Unnest(expressions=[generate_series])) 4321 4322 if isinstance(parent, exp.Select): 4323 self.unsupported("GenerateSeries projection unnesting is not supported.") 4324 4325 return self.sql(generate_series) 4326 4327 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4328 exprs = expression.expressions 4329 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4330 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4331 else: 4332 rhs = self.expressions(expression) 4333 4334 return self.func(name, expression.this, rhs or None) 4335 4336 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4337 if self.SUPPORTS_CONVERT_TIMEZONE: 4338 return self.function_fallback_sql(expression) 4339 4340 source_tz = expression.args.get("source_tz") 4341 target_tz = expression.args.get("target_tz") 4342 timestamp = expression.args.get("timestamp") 4343 4344 if source_tz and timestamp: 4345 timestamp = exp.AtTimeZone( 4346 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4347 ) 4348 4349 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4350 4351 return self.sql(expr) 4352 4353 def json_sql(self, expression: exp.JSON) -> str: 4354 this = self.sql(expression, "this") 4355 this = f" {this}" if this else "" 4356 4357 _with = expression.args.get("with") 4358 4359 if _with is None: 4360 with_sql = "" 4361 elif not _with: 4362 with_sql = " WITHOUT" 4363 else: 4364 with_sql = " WITH" 4365 4366 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4367 4368 return f"JSON{this}{with_sql}{unique_sql}" 4369 4370 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4371 def _generate_on_options(arg: t.Any) -> str: 4372 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4373 4374 path = self.sql(expression, "path") 4375 returning = self.sql(expression, "returning") 4376 returning = f" RETURNING {returning}" if returning else "" 4377 4378 on_condition = self.sql(expression, "on_condition") 4379 on_condition = f" {on_condition}" if on_condition else "" 4380 4381 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4382 4383 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4384 else_ = "ELSE " if expression.args.get("else_") else "" 4385 condition = self.sql(expression, "expression") 4386 condition = f"WHEN {condition} THEN " if condition else else_ 4387 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4388 return f"{condition}{insert}" 4389 4390 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4391 kind = self.sql(expression, "kind") 4392 expressions = self.seg(self.expressions(expression, sep=" ")) 4393 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4394 return res 4395 4396 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4397 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4398 empty = expression.args.get("empty") 4399 empty = ( 4400 f"DEFAULT {empty} ON EMPTY" 4401 if isinstance(empty, exp.Expression) 4402 else self.sql(expression, "empty") 4403 ) 4404 4405 error = expression.args.get("error") 4406 error = ( 4407 f"DEFAULT {error} ON ERROR" 4408 if isinstance(error, exp.Expression) 4409 else self.sql(expression, "error") 4410 ) 4411 4412 if error and empty: 4413 error = ( 4414 f"{empty} {error}" 4415 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4416 else f"{error} {empty}" 4417 ) 4418 empty = "" 4419 4420 null = self.sql(expression, "null") 4421 4422 return f"{empty}{error}{null}" 4423 4424 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4425 this = self.sql(expression, "this") 4426 path = self.sql(expression, "path") 4427 4428 passing = self.expressions(expression, "passing") 4429 passing = f" PASSING {passing}" if passing else "" 4430 4431 on_condition = self.sql(expression, "on_condition") 4432 on_condition = f" {on_condition}" if on_condition else "" 4433 4434 path = f"{path}{passing}{on_condition}" 4435 4436 return self.func("JSON_EXISTS", this, path) 4437 4438 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4439 array_agg = self.function_fallback_sql(expression) 4440 4441 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4442 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4443 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4444 parent = expression.parent 4445 if isinstance(parent, exp.Filter): 4446 parent_cond = parent.expression.this 4447 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4448 else: 4449 this = expression.this 4450 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4451 if this.find(exp.Column): 4452 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4453 this_sql = ( 4454 self.expressions(this) 4455 if isinstance(this, exp.Distinct) 4456 else self.sql(expression, "this") 4457 ) 4458 4459 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4460 4461 return array_agg 4462 4463 def apply_sql(self, expression: exp.Apply) -> str: 4464 this = self.sql(expression, "this") 4465 expr = self.sql(expression, "expression") 4466 4467 return f"{this} APPLY({expr})" 4468 4469 def grant_sql(self, expression: exp.Grant) -> str: 4470 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4471 4472 kind = self.sql(expression, "kind") 4473 kind = f" {kind}" if kind else "" 4474 4475 securable = self.sql(expression, "securable") 4476 securable = f" {securable}" if securable else "" 4477 4478 principals = self.expressions(expression, key="principals", flat=True) 4479 4480 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4481 4482 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4483 4484 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4485 this = self.sql(expression, "this") 4486 columns = self.expressions(expression, flat=True) 4487 columns = f"({columns})" if columns else "" 4488 4489 return f"{this}{columns}" 4490 4491 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4492 this = self.sql(expression, "this") 4493 4494 kind = self.sql(expression, "kind") 4495 kind = f"{kind} " if kind else "" 4496 4497 return f"{kind}{this}" 4498 4499 def columns_sql(self, expression: exp.Columns): 4500 func = self.function_fallback_sql(expression) 4501 if expression.args.get("unpack"): 4502 func = f"*{func}" 4503 4504 return func 4505 4506 def overlay_sql(self, expression: exp.Overlay): 4507 this = self.sql(expression, "this") 4508 expr = self.sql(expression, "expression") 4509 from_sql = self.sql(expression, "from") 4510 for_sql = self.sql(expression, "for") 4511 for_sql = f" FOR {for_sql}" if for_sql else "" 4512 4513 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4514 4515 @unsupported_args("format") 4516 def todouble_sql(self, expression: exp.ToDouble) -> str: 4517 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4518 4519 def string_sql(self, expression: exp.String) -> str: 4520 this = expression.this 4521 zone = expression.args.get("zone") 4522 4523 if zone: 4524 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4525 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4526 # set for source_tz to transpile the time conversion before the STRING cast 4527 this = exp.ConvertTimezone( 4528 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4529 ) 4530 4531 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4532 4533 def median_sql(self, expression: exp.Median): 4534 if not self.SUPPORTS_MEDIAN: 4535 return self.sql( 4536 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4537 ) 4538 4539 return self.function_fallback_sql(expression) 4540 4541 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4542 filler = self.sql(expression, "this") 4543 filler = f" {filler}" if filler else "" 4544 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4545 return f"TRUNCATE{filler} {with_count}" 4546 4547 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4548 if self.SUPPORTS_UNIX_SECONDS: 4549 return self.function_fallback_sql(expression) 4550 4551 start_ts = exp.cast( 4552 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4553 ) 4554 4555 return self.sql( 4556 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4557 ) 4558 4559 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4560 dim = expression.expression 4561 4562 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4563 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4564 if not (dim.is_int and dim.name == "1"): 4565 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4566 dim = None 4567 4568 # If dimension is required but not specified, default initialize it 4569 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4570 dim = exp.Literal.number(1) 4571 4572 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4573 4574 def attach_sql(self, expression: exp.Attach) -> str: 4575 this = self.sql(expression, "this") 4576 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4577 expressions = self.expressions(expression) 4578 expressions = f" ({expressions})" if expressions else "" 4579 4580 return f"ATTACH{exists_sql} {this}{expressions}" 4581 4582 def detach_sql(self, expression: exp.Detach) -> str: 4583 this = self.sql(expression, "this") 4584 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4585 4586 return f"DETACH{exists_sql} {this}" 4587 4588 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4589 this = self.sql(expression, "this") 4590 value = self.sql(expression, "expression") 4591 value = f" {value}" if value else "" 4592 return f"{this}{value}" 4593 4594 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4595 this_sql = self.sql(expression, "this") 4596 if isinstance(expression.this, exp.Table): 4597 this_sql = f"TABLE {this_sql}" 4598 4599 return self.func( 4600 "FEATURES_AT_TIME", 4601 this_sql, 4602 expression.args.get("time"), 4603 expression.args.get("num_rows"), 4604 expression.args.get("ignore_feature_nulls"), 4605 ) 4606 4607 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4608 return ( 4609 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4610 ) 4611 4612 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4613 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4614 encode = f"{encode} {self.sql(expression, 'this')}" 4615 4616 properties = expression.args.get("properties") 4617 if properties: 4618 encode = f"{encode} {self.properties(properties)}" 4619 4620 return encode 4621 4622 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4623 this = self.sql(expression, "this") 4624 include = f"INCLUDE {this}" 4625 4626 column_def = self.sql(expression, "column_def") 4627 if column_def: 4628 include = f"{include} {column_def}" 4629 4630 alias = self.sql(expression, "alias") 4631 if alias: 4632 include = f"{include} AS {alias}" 4633 4634 return include 4635 4636 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4637 name = f"NAME {self.sql(expression, 'this')}" 4638 return self.func("XMLELEMENT", name, *expression.expressions) 4639 4640 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4641 partitions = self.expressions(expression, "partition_expressions") 4642 create = self.expressions(expression, "create_expressions") 4643 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4644 4645 def partitionbyrangepropertydynamic_sql( 4646 self, expression: exp.PartitionByRangePropertyDynamic 4647 ) -> str: 4648 start = self.sql(expression, "start") 4649 end = self.sql(expression, "end") 4650 4651 every = expression.args["every"] 4652 if isinstance(every, exp.Interval) and every.this.is_string: 4653 every.this.replace(exp.Literal.number(every.name)) 4654 4655 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4656 4657 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4658 name = self.sql(expression, "this") 4659 values = self.expressions(expression, flat=True) 4660 4661 return f"NAME {name} VALUE {values}" 4662 4663 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4664 kind = self.sql(expression, "kind") 4665 sample = self.sql(expression, "sample") 4666 return f"SAMPLE {sample} {kind}" 4667 4668 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4669 kind = self.sql(expression, "kind") 4670 option = self.sql(expression, "option") 4671 option = f" {option}" if option else "" 4672 this = self.sql(expression, "this") 4673 this = f" {this}" if this else "" 4674 columns = self.expressions(expression) 4675 columns = f" {columns}" if columns else "" 4676 return f"{kind}{option} STATISTICS{this}{columns}" 4677 4678 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4679 this = self.sql(expression, "this") 4680 columns = self.expressions(expression) 4681 inner_expression = self.sql(expression, "expression") 4682 inner_expression = f" {inner_expression}" if inner_expression else "" 4683 update_options = self.sql(expression, "update_options") 4684 update_options = f" {update_options} UPDATE" if update_options else "" 4685 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4686 4687 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4688 kind = self.sql(expression, "kind") 4689 kind = f" {kind}" if kind else "" 4690 return f"DELETE{kind} STATISTICS" 4691 4692 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4693 inner_expression = self.sql(expression, "expression") 4694 return f"LIST CHAINED ROWS{inner_expression}" 4695 4696 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4697 kind = self.sql(expression, "kind") 4698 this = self.sql(expression, "this") 4699 this = f" {this}" if this else "" 4700 inner_expression = self.sql(expression, "expression") 4701 return f"VALIDATE {kind}{this}{inner_expression}" 4702 4703 def analyze_sql(self, expression: exp.Analyze) -> str: 4704 options = self.expressions(expression, key="options", sep=" ") 4705 options = f" {options}" if options else "" 4706 kind = self.sql(expression, "kind") 4707 kind = f" {kind}" if kind else "" 4708 this = self.sql(expression, "this") 4709 this = f" {this}" if this else "" 4710 mode = self.sql(expression, "mode") 4711 mode = f" {mode}" if mode else "" 4712 properties = self.sql(expression, "properties") 4713 properties = f" {properties}" if properties else "" 4714 partition = self.sql(expression, "partition") 4715 partition = f" {partition}" if partition else "" 4716 inner_expression = self.sql(expression, "expression") 4717 inner_expression = f" {inner_expression}" if inner_expression else "" 4718 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4719 4720 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4721 this = self.sql(expression, "this") 4722 passing = self.expressions(expression, key="passing") 4723 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4724 columns = self.expressions(expression, key="columns") 4725 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4726 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4727 return f"XMLTABLE({self.sep('')}{self.indent(this + passing + by_ref + columns)}{self.seg(')', sep='')}"
logger =
<Logger sqlglot (WARNING)>
ESCAPED_UNICODE_RE =
re.compile('\\\\(\\d+)')
UNSUPPORTED_TEMPLATE =
"Argument '{}' is not supported for expression '{}' when targeting {}."
def
unsupported_args( *args: Union[str, Tuple[str, str]]) -> Callable[[Callable[[~G, ~E], str]], Callable[[~G, ~E], str]]:
30def unsupported_args( 31 *args: t.Union[str, t.Tuple[str, str]], 32) -> t.Callable[[GeneratorMethod], GeneratorMethod]: 33 """ 34 Decorator that can be used to mark certain args of an `Expression` subclass as unsupported. 35 It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg). 36 """ 37 diagnostic_by_arg: t.Dict[str, t.Optional[str]] = {} 38 for arg in args: 39 if isinstance(arg, str): 40 diagnostic_by_arg[arg] = None 41 else: 42 diagnostic_by_arg[arg[0]] = arg[1] 43 44 def decorator(func: GeneratorMethod) -> GeneratorMethod: 45 @wraps(func) 46 def _func(generator: G, expression: E) -> str: 47 expression_name = expression.__class__.__name__ 48 dialect_name = generator.dialect.__class__.__name__ 49 50 for arg_name, diagnostic in diagnostic_by_arg.items(): 51 if expression.args.get(arg_name): 52 diagnostic = diagnostic or UNSUPPORTED_TEMPLATE.format( 53 arg_name, expression_name, dialect_name 54 ) 55 generator.unsupported(diagnostic) 56 57 return func(generator, expression) 58 59 return _func 60 61 return decorator
Decorator that can be used to mark certain args of an Expression
subclass as unsupported.
It expects a sequence of argument names or pairs of the form (argument_name, diagnostic_msg).
class
Generator:
75class Generator(metaclass=_Generator): 76 """ 77 Generator converts a given syntax tree to the corresponding SQL string. 78 79 Args: 80 pretty: Whether to format the produced SQL string. 81 Default: False. 82 identify: Determines when an identifier should be quoted. Possible values are: 83 False (default): Never quote, except in cases where it's mandatory by the dialect. 84 True or 'always': Always quote. 85 'safe': Only quote identifiers that are case insensitive. 86 normalize: Whether to normalize identifiers to lowercase. 87 Default: False. 88 pad: The pad size in a formatted string. For example, this affects the indentation of 89 a projection in a query, relative to its nesting level. 90 Default: 2. 91 indent: The indentation size in a formatted string. For example, this affects the 92 indentation of subqueries and filters under a `WHERE` clause. 93 Default: 2. 94 normalize_functions: How to normalize function names. Possible values are: 95 "upper" or True (default): Convert names to uppercase. 96 "lower": Convert names to lowercase. 97 False: Disables function name normalization. 98 unsupported_level: Determines the generator's behavior when it encounters unsupported expressions. 99 Default ErrorLevel.WARN. 100 max_unsupported: Maximum number of unsupported messages to include in a raised UnsupportedError. 101 This is only relevant if unsupported_level is ErrorLevel.RAISE. 102 Default: 3 103 leading_comma: Whether the comma is leading or trailing in select expressions. 104 This is only relevant when generating in pretty mode. 105 Default: False 106 max_text_width: The max number of characters in a segment before creating new lines in pretty mode. 107 The default is on the smaller end because the length only represents a segment and not the true 108 line length. 109 Default: 80 110 comments: Whether to preserve comments in the output SQL code. 111 Default: True 112 """ 113 114 TRANSFORMS: t.Dict[t.Type[exp.Expression], t.Callable[..., str]] = { 115 **JSON_PATH_PART_TRANSFORMS, 116 exp.AllowedValuesProperty: lambda self, 117 e: f"ALLOWED_VALUES {self.expressions(e, flat=True)}", 118 exp.AnalyzeColumns: lambda self, e: self.sql(e, "this"), 119 exp.AnalyzeWith: lambda self, e: self.expressions(e, prefix="WITH ", sep=" "), 120 exp.ArrayContainsAll: lambda self, e: self.binary(e, "@>"), 121 exp.ArrayOverlaps: lambda self, e: self.binary(e, "&&"), 122 exp.AutoRefreshProperty: lambda self, e: f"AUTO REFRESH {self.sql(e, 'this')}", 123 exp.BackupProperty: lambda self, e: f"BACKUP {self.sql(e, 'this')}", 124 exp.CaseSpecificColumnConstraint: lambda _, 125 e: f"{'NOT ' if e.args.get('not_') else ''}CASESPECIFIC", 126 exp.Ceil: lambda self, e: self.ceil_floor(e), 127 exp.CharacterSetColumnConstraint: lambda self, e: f"CHARACTER SET {self.sql(e, 'this')}", 128 exp.CharacterSetProperty: lambda self, 129 e: f"{'DEFAULT ' if e.args.get('default') else ''}CHARACTER SET={self.sql(e, 'this')}", 130 exp.ClusteredColumnConstraint: lambda self, 131 e: f"CLUSTERED ({self.expressions(e, 'this', indent=False)})", 132 exp.CollateColumnConstraint: lambda self, e: f"COLLATE {self.sql(e, 'this')}", 133 exp.CommentColumnConstraint: lambda self, e: f"COMMENT {self.sql(e, 'this')}", 134 exp.ConnectByRoot: lambda self, e: f"CONNECT_BY_ROOT {self.sql(e, 'this')}", 135 exp.CopyGrantsProperty: lambda *_: "COPY GRANTS", 136 exp.DateFormatColumnConstraint: lambda self, e: f"FORMAT {self.sql(e, 'this')}", 137 exp.DefaultColumnConstraint: lambda self, e: f"DEFAULT {self.sql(e, 'this')}", 138 exp.DynamicProperty: lambda *_: "DYNAMIC", 139 exp.EmptyProperty: lambda *_: "EMPTY", 140 exp.EncodeColumnConstraint: lambda self, e: f"ENCODE {self.sql(e, 'this')}", 141 exp.EphemeralColumnConstraint: lambda self, 142 e: f"EPHEMERAL{(' ' + self.sql(e, 'this')) if e.this else ''}", 143 exp.ExcludeColumnConstraint: lambda self, e: f"EXCLUDE {self.sql(e, 'this').lstrip()}", 144 exp.ExecuteAsProperty: lambda self, e: self.naked_property(e), 145 exp.Except: lambda self, e: self.set_operations(e), 146 exp.ExternalProperty: lambda *_: "EXTERNAL", 147 exp.Floor: lambda self, e: self.ceil_floor(e), 148 exp.GlobalProperty: lambda *_: "GLOBAL", 149 exp.HeapProperty: lambda *_: "HEAP", 150 exp.IcebergProperty: lambda *_: "ICEBERG", 151 exp.InheritsProperty: lambda self, e: f"INHERITS ({self.expressions(e, flat=True)})", 152 exp.InlineLengthColumnConstraint: lambda self, e: f"INLINE LENGTH {self.sql(e, 'this')}", 153 exp.InputModelProperty: lambda self, e: f"INPUT{self.sql(e, 'this')}", 154 exp.Intersect: lambda self, e: self.set_operations(e), 155 exp.IntervalSpan: lambda self, e: f"{self.sql(e, 'this')} TO {self.sql(e, 'expression')}", 156 exp.Int64: lambda self, e: self.sql(exp.cast(e.this, exp.DataType.Type.BIGINT)), 157 exp.LanguageProperty: lambda self, e: self.naked_property(e), 158 exp.LocationProperty: lambda self, e: self.naked_property(e), 159 exp.LogProperty: lambda _, e: f"{'NO ' if e.args.get('no') else ''}LOG", 160 exp.MaterializedProperty: lambda *_: "MATERIALIZED", 161 exp.NonClusteredColumnConstraint: lambda self, 162 e: f"NONCLUSTERED ({self.expressions(e, 'this', indent=False)})", 163 exp.NoPrimaryIndexProperty: lambda *_: "NO PRIMARY INDEX", 164 exp.NotForReplicationColumnConstraint: lambda *_: "NOT FOR REPLICATION", 165 exp.OnCommitProperty: lambda _, 166 e: f"ON COMMIT {'DELETE' if e.args.get('delete') else 'PRESERVE'} ROWS", 167 exp.OnProperty: lambda self, e: f"ON {self.sql(e, 'this')}", 168 exp.OnUpdateColumnConstraint: lambda self, e: f"ON UPDATE {self.sql(e, 'this')}", 169 exp.Operator: lambda self, e: self.binary(e, ""), # The operator is produced in `binary` 170 exp.OutputModelProperty: lambda self, e: f"OUTPUT{self.sql(e, 'this')}", 171 exp.PathColumnConstraint: lambda self, e: f"PATH {self.sql(e, 'this')}", 172 exp.PivotAny: lambda self, e: f"ANY{self.sql(e, 'this')}", 173 exp.ProjectionPolicyColumnConstraint: lambda self, 174 e: f"PROJECTION POLICY {self.sql(e, 'this')}", 175 exp.RemoteWithConnectionModelProperty: lambda self, 176 e: f"REMOTE WITH CONNECTION {self.sql(e, 'this')}", 177 exp.ReturnsProperty: lambda self, e: ( 178 "RETURNS NULL ON NULL INPUT" if e.args.get("null") else self.naked_property(e) 179 ), 180 exp.SampleProperty: lambda self, e: f"SAMPLE BY {self.sql(e, 'this')}", 181 exp.SecureProperty: lambda *_: "SECURE", 182 exp.SecurityProperty: lambda self, e: f"SECURITY {self.sql(e, 'this')}", 183 exp.SetConfigProperty: lambda self, e: self.sql(e, "this"), 184 exp.SetProperty: lambda _, e: f"{'MULTI' if e.args.get('multi') else ''}SET", 185 exp.SettingsProperty: lambda self, e: f"SETTINGS{self.seg('')}{(self.expressions(e))}", 186 exp.SharingProperty: lambda self, e: f"SHARING={self.sql(e, 'this')}", 187 exp.SqlReadWriteProperty: lambda _, e: e.name, 188 exp.SqlSecurityProperty: lambda _, 189 e: f"SQL SECURITY {'DEFINER' if e.args.get('definer') else 'INVOKER'}", 190 exp.StabilityProperty: lambda _, e: e.name, 191 exp.Stream: lambda self, e: f"STREAM {self.sql(e, 'this')}", 192 exp.StreamingTableProperty: lambda *_: "STREAMING", 193 exp.StrictProperty: lambda *_: "STRICT", 194 exp.SwapTable: lambda self, e: f"SWAP WITH {self.sql(e, 'this')}", 195 exp.TemporaryProperty: lambda *_: "TEMPORARY", 196 exp.Tags: lambda self, e: f"TAG ({self.expressions(e, flat=True)})", 197 exp.TitleColumnConstraint: lambda self, e: f"TITLE {self.sql(e, 'this')}", 198 exp.ToMap: lambda self, e: f"MAP {self.sql(e, 'this')}", 199 exp.ToTableProperty: lambda self, e: f"TO {self.sql(e.this)}", 200 exp.TransformModelProperty: lambda self, e: self.func("TRANSFORM", *e.expressions), 201 exp.TransientProperty: lambda *_: "TRANSIENT", 202 exp.Union: lambda self, e: self.set_operations(e), 203 exp.UnloggedProperty: lambda *_: "UNLOGGED", 204 exp.UsingData: lambda self, e: f"USING DATA {self.sql(e, 'this')}", 205 exp.Uuid: lambda *_: "UUID()", 206 exp.UppercaseColumnConstraint: lambda *_: "UPPERCASE", 207 exp.VarMap: lambda self, e: self.func("MAP", e.args["keys"], e.args["values"]), 208 exp.ViewAttributeProperty: lambda self, e: f"WITH {self.sql(e, 'this')}", 209 exp.VolatileProperty: lambda *_: "VOLATILE", 210 exp.WithJournalTableProperty: lambda self, e: f"WITH JOURNAL TABLE={self.sql(e, 'this')}", 211 exp.WithProcedureOptions: lambda self, e: f"WITH {self.expressions(e, flat=True)}", 212 exp.WithSchemaBindingProperty: lambda self, e: f"WITH SCHEMA {self.sql(e, 'this')}", 213 exp.WithOperator: lambda self, e: f"{self.sql(e, 'this')} WITH {self.sql(e, 'op')}", 214 } 215 216 # Whether null ordering is supported in order by 217 # True: Full Support, None: No support, False: No support for certain cases 218 # such as window specifications, aggregate functions etc 219 NULL_ORDERING_SUPPORTED: t.Optional[bool] = True 220 221 # Whether ignore nulls is inside the agg or outside. 222 # FIRST(x IGNORE NULLS) OVER vs FIRST (x) IGNORE NULLS OVER 223 IGNORE_NULLS_IN_FUNC = False 224 225 # Whether locking reads (i.e. SELECT ... FOR UPDATE/SHARE) are supported 226 LOCKING_READS_SUPPORTED = False 227 228 # Whether the EXCEPT and INTERSECT operations can return duplicates 229 EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE = True 230 231 # Wrap derived values in parens, usually standard but spark doesn't support it 232 WRAP_DERIVED_VALUES = True 233 234 # Whether create function uses an AS before the RETURN 235 CREATE_FUNCTION_RETURN_AS = True 236 237 # Whether MERGE ... WHEN MATCHED BY SOURCE is allowed 238 MATCHED_BY_SOURCE = True 239 240 # Whether the INTERVAL expression works only with values like '1 day' 241 SINGLE_STRING_INTERVAL = False 242 243 # Whether the plural form of date parts like day (i.e. "days") is supported in INTERVALs 244 INTERVAL_ALLOWS_PLURAL_FORM = True 245 246 # Whether limit and fetch are supported (possible values: "ALL", "LIMIT", "FETCH") 247 LIMIT_FETCH = "ALL" 248 249 # Whether limit and fetch allows expresions or just limits 250 LIMIT_ONLY_LITERALS = False 251 252 # Whether a table is allowed to be renamed with a db 253 RENAME_TABLE_WITH_DB = True 254 255 # The separator for grouping sets and rollups 256 GROUPINGS_SEP = "," 257 258 # The string used for creating an index on a table 259 INDEX_ON = "ON" 260 261 # Whether join hints should be generated 262 JOIN_HINTS = True 263 264 # Whether table hints should be generated 265 TABLE_HINTS = True 266 267 # Whether query hints should be generated 268 QUERY_HINTS = True 269 270 # What kind of separator to use for query hints 271 QUERY_HINT_SEP = ", " 272 273 # Whether comparing against booleans (e.g. x IS TRUE) is supported 274 IS_BOOL_ALLOWED = True 275 276 # Whether to include the "SET" keyword in the "INSERT ... ON DUPLICATE KEY UPDATE" statement 277 DUPLICATE_KEY_UPDATE_WITH_SET = True 278 279 # Whether to generate the limit as TOP <value> instead of LIMIT <value> 280 LIMIT_IS_TOP = False 281 282 # Whether to generate INSERT INTO ... RETURNING or INSERT INTO RETURNING ... 283 RETURNING_END = True 284 285 # Whether to generate an unquoted value for EXTRACT's date part argument 286 EXTRACT_ALLOWS_QUOTES = True 287 288 # Whether TIMETZ / TIMESTAMPTZ will be generated using the "WITH TIME ZONE" syntax 289 TZ_TO_WITH_TIME_ZONE = False 290 291 # Whether the NVL2 function is supported 292 NVL2_SUPPORTED = True 293 294 # https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax 295 SELECT_KINDS: t.Tuple[str, ...] = ("STRUCT", "VALUE") 296 297 # Whether VALUES statements can be used as derived tables. 298 # MySQL 5 and Redshift do not allow this, so when False, it will convert 299 # SELECT * VALUES into SELECT UNION 300 VALUES_AS_TABLE = True 301 302 # Whether the word COLUMN is included when adding a column with ALTER TABLE 303 ALTER_TABLE_INCLUDE_COLUMN_KEYWORD = True 304 305 # UNNEST WITH ORDINALITY (presto) instead of UNNEST WITH OFFSET (bigquery) 306 UNNEST_WITH_ORDINALITY = True 307 308 # Whether FILTER (WHERE cond) can be used for conditional aggregation 309 AGGREGATE_FILTER_SUPPORTED = True 310 311 # Whether JOIN sides (LEFT, RIGHT) are supported in conjunction with SEMI/ANTI join kinds 312 SEMI_ANTI_JOIN_WITH_SIDE = True 313 314 # Whether to include the type of a computed column in the CREATE DDL 315 COMPUTED_COLUMN_WITH_TYPE = True 316 317 # Whether CREATE TABLE .. COPY .. is supported. False means we'll generate CLONE instead of COPY 318 SUPPORTS_TABLE_COPY = True 319 320 # Whether parentheses are required around the table sample's expression 321 TABLESAMPLE_REQUIRES_PARENS = True 322 323 # Whether a table sample clause's size needs to be followed by the ROWS keyword 324 TABLESAMPLE_SIZE_IS_ROWS = True 325 326 # The keyword(s) to use when generating a sample clause 327 TABLESAMPLE_KEYWORDS = "TABLESAMPLE" 328 329 # Whether the TABLESAMPLE clause supports a method name, like BERNOULLI 330 TABLESAMPLE_WITH_METHOD = True 331 332 # The keyword to use when specifying the seed of a sample clause 333 TABLESAMPLE_SEED_KEYWORD = "SEED" 334 335 # Whether COLLATE is a function instead of a binary operator 336 COLLATE_IS_FUNC = False 337 338 # Whether data types support additional specifiers like e.g. CHAR or BYTE (oracle) 339 DATA_TYPE_SPECIFIERS_ALLOWED = False 340 341 # Whether conditions require booleans WHERE x = 0 vs WHERE x 342 ENSURE_BOOLS = False 343 344 # Whether the "RECURSIVE" keyword is required when defining recursive CTEs 345 CTE_RECURSIVE_KEYWORD_REQUIRED = True 346 347 # Whether CONCAT requires >1 arguments 348 SUPPORTS_SINGLE_ARG_CONCAT = True 349 350 # Whether LAST_DAY function supports a date part argument 351 LAST_DAY_SUPPORTS_DATE_PART = True 352 353 # Whether named columns are allowed in table aliases 354 SUPPORTS_TABLE_ALIAS_COLUMNS = True 355 356 # Whether UNPIVOT aliases are Identifiers (False means they're Literals) 357 UNPIVOT_ALIASES_ARE_IDENTIFIERS = True 358 359 # What delimiter to use for separating JSON key/value pairs 360 JSON_KEY_VALUE_PAIR_SEP = ":" 361 362 # INSERT OVERWRITE TABLE x override 363 INSERT_OVERWRITE = " OVERWRITE TABLE" 364 365 # Whether the SELECT .. INTO syntax is used instead of CTAS 366 SUPPORTS_SELECT_INTO = False 367 368 # Whether UNLOGGED tables can be created 369 SUPPORTS_UNLOGGED_TABLES = False 370 371 # Whether the CREATE TABLE LIKE statement is supported 372 SUPPORTS_CREATE_TABLE_LIKE = True 373 374 # Whether the LikeProperty needs to be specified inside of the schema clause 375 LIKE_PROPERTY_INSIDE_SCHEMA = False 376 377 # Whether DISTINCT can be followed by multiple args in an AggFunc. If not, it will be 378 # transpiled into a series of CASE-WHEN-ELSE, ultimately using a tuple conseisting of the args 379 MULTI_ARG_DISTINCT = True 380 381 # Whether the JSON extraction operators expect a value of type JSON 382 JSON_TYPE_REQUIRED_FOR_EXTRACTION = False 383 384 # Whether bracketed keys like ["foo"] are supported in JSON paths 385 JSON_PATH_BRACKETED_KEY_SUPPORTED = True 386 387 # Whether to escape keys using single quotes in JSON paths 388 JSON_PATH_SINGLE_QUOTE_ESCAPE = False 389 390 # The JSONPathPart expressions supported by this dialect 391 SUPPORTED_JSON_PATH_PARTS = ALL_JSON_PATH_PARTS.copy() 392 393 # Whether any(f(x) for x in array) can be implemented by this dialect 394 CAN_IMPLEMENT_ARRAY_ANY = False 395 396 # Whether the function TO_NUMBER is supported 397 SUPPORTS_TO_NUMBER = True 398 399 # Whether or not set op modifiers apply to the outer set op or select. 400 # SELECT * FROM x UNION SELECT * FROM y LIMIT 1 401 # True means limit 1 happens after the set op, False means it it happens on y. 402 SET_OP_MODIFIERS = True 403 404 # Whether parameters from COPY statement are wrapped in parentheses 405 COPY_PARAMS_ARE_WRAPPED = True 406 407 # Whether values of params are set with "=" token or empty space 408 COPY_PARAMS_EQ_REQUIRED = False 409 410 # Whether COPY statement has INTO keyword 411 COPY_HAS_INTO_KEYWORD = True 412 413 # Whether the conditional TRY(expression) function is supported 414 TRY_SUPPORTED = True 415 416 # Whether the UESCAPE syntax in unicode strings is supported 417 SUPPORTS_UESCAPE = True 418 419 # The keyword to use when generating a star projection with excluded columns 420 STAR_EXCEPT = "EXCEPT" 421 422 # The HEX function name 423 HEX_FUNC = "HEX" 424 425 # The keywords to use when prefixing & separating WITH based properties 426 WITH_PROPERTIES_PREFIX = "WITH" 427 428 # Whether to quote the generated expression of exp.JsonPath 429 QUOTE_JSON_PATH = True 430 431 # Whether the text pattern/fill (3rd) parameter of RPAD()/LPAD() is optional (defaults to space) 432 PAD_FILL_PATTERN_IS_REQUIRED = False 433 434 # Whether a projection can explode into multiple rows, e.g. by unnesting an array. 435 SUPPORTS_EXPLODING_PROJECTIONS = True 436 437 # Whether ARRAY_CONCAT can be generated with varlen args or if it should be reduced to 2-arg version 438 ARRAY_CONCAT_IS_VAR_LEN = True 439 440 # Whether CONVERT_TIMEZONE() is supported; if not, it will be generated as exp.AtTimeZone 441 SUPPORTS_CONVERT_TIMEZONE = False 442 443 # Whether MEDIAN(expr) is supported; if not, it will be generated as PERCENTILE_CONT(expr, 0.5) 444 SUPPORTS_MEDIAN = True 445 446 # Whether UNIX_SECONDS(timestamp) is supported 447 SUPPORTS_UNIX_SECONDS = False 448 449 # The name to generate for the JSONPath expression. If `None`, only `this` will be generated 450 PARSE_JSON_NAME: t.Optional[str] = "PARSE_JSON" 451 452 # The function name of the exp.ArraySize expression 453 ARRAY_SIZE_NAME: str = "ARRAY_LENGTH" 454 455 # Whether exp.ArraySize should generate the dimension arg too (valid for Postgres & DuckDB) 456 # None -> Doesn't support it at all 457 # False (DuckDB) -> Has backwards-compatible support, but preferably generated without 458 # True (Postgres) -> Explicitly requires it 459 ARRAY_SIZE_DIM_REQUIRED: t.Optional[bool] = None 460 461 TYPE_MAPPING = { 462 exp.DataType.Type.DATETIME2: "TIMESTAMP", 463 exp.DataType.Type.NCHAR: "CHAR", 464 exp.DataType.Type.NVARCHAR: "VARCHAR", 465 exp.DataType.Type.MEDIUMTEXT: "TEXT", 466 exp.DataType.Type.LONGTEXT: "TEXT", 467 exp.DataType.Type.TINYTEXT: "TEXT", 468 exp.DataType.Type.MEDIUMBLOB: "BLOB", 469 exp.DataType.Type.LONGBLOB: "BLOB", 470 exp.DataType.Type.TINYBLOB: "BLOB", 471 exp.DataType.Type.INET: "INET", 472 exp.DataType.Type.ROWVERSION: "VARBINARY", 473 exp.DataType.Type.SMALLDATETIME: "TIMESTAMP", 474 } 475 476 TIME_PART_SINGULARS = { 477 "MICROSECONDS": "MICROSECOND", 478 "SECONDS": "SECOND", 479 "MINUTES": "MINUTE", 480 "HOURS": "HOUR", 481 "DAYS": "DAY", 482 "WEEKS": "WEEK", 483 "MONTHS": "MONTH", 484 "QUARTERS": "QUARTER", 485 "YEARS": "YEAR", 486 } 487 488 AFTER_HAVING_MODIFIER_TRANSFORMS = { 489 "cluster": lambda self, e: self.sql(e, "cluster"), 490 "distribute": lambda self, e: self.sql(e, "distribute"), 491 "sort": lambda self, e: self.sql(e, "sort"), 492 "windows": lambda self, e: ( 493 self.seg("WINDOW ") + self.expressions(e, key="windows", flat=True) 494 if e.args.get("windows") 495 else "" 496 ), 497 "qualify": lambda self, e: self.sql(e, "qualify"), 498 } 499 500 TOKEN_MAPPING: t.Dict[TokenType, str] = {} 501 502 STRUCT_DELIMITER = ("<", ">") 503 504 PARAMETER_TOKEN = "@" 505 NAMED_PLACEHOLDER_TOKEN = ":" 506 507 EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: t.Set[str] = set() 508 509 PROPERTIES_LOCATION = { 510 exp.AllowedValuesProperty: exp.Properties.Location.POST_SCHEMA, 511 exp.AlgorithmProperty: exp.Properties.Location.POST_CREATE, 512 exp.AutoIncrementProperty: exp.Properties.Location.POST_SCHEMA, 513 exp.AutoRefreshProperty: exp.Properties.Location.POST_SCHEMA, 514 exp.BackupProperty: exp.Properties.Location.POST_SCHEMA, 515 exp.BlockCompressionProperty: exp.Properties.Location.POST_NAME, 516 exp.CharacterSetProperty: exp.Properties.Location.POST_SCHEMA, 517 exp.ChecksumProperty: exp.Properties.Location.POST_NAME, 518 exp.CollateProperty: exp.Properties.Location.POST_SCHEMA, 519 exp.CopyGrantsProperty: exp.Properties.Location.POST_SCHEMA, 520 exp.Cluster: exp.Properties.Location.POST_SCHEMA, 521 exp.ClusteredByProperty: exp.Properties.Location.POST_SCHEMA, 522 exp.DistributedByProperty: exp.Properties.Location.POST_SCHEMA, 523 exp.DuplicateKeyProperty: exp.Properties.Location.POST_SCHEMA, 524 exp.DataBlocksizeProperty: exp.Properties.Location.POST_NAME, 525 exp.DataDeletionProperty: exp.Properties.Location.POST_SCHEMA, 526 exp.DefinerProperty: exp.Properties.Location.POST_CREATE, 527 exp.DictRange: exp.Properties.Location.POST_SCHEMA, 528 exp.DictProperty: exp.Properties.Location.POST_SCHEMA, 529 exp.DynamicProperty: exp.Properties.Location.POST_CREATE, 530 exp.DistKeyProperty: exp.Properties.Location.POST_SCHEMA, 531 exp.DistStyleProperty: exp.Properties.Location.POST_SCHEMA, 532 exp.EmptyProperty: exp.Properties.Location.POST_SCHEMA, 533 exp.EncodeProperty: exp.Properties.Location.POST_EXPRESSION, 534 exp.EngineProperty: exp.Properties.Location.POST_SCHEMA, 535 exp.ExecuteAsProperty: exp.Properties.Location.POST_SCHEMA, 536 exp.ExternalProperty: exp.Properties.Location.POST_CREATE, 537 exp.FallbackProperty: exp.Properties.Location.POST_NAME, 538 exp.FileFormatProperty: exp.Properties.Location.POST_WITH, 539 exp.FreespaceProperty: exp.Properties.Location.POST_NAME, 540 exp.GlobalProperty: exp.Properties.Location.POST_CREATE, 541 exp.HeapProperty: exp.Properties.Location.POST_WITH, 542 exp.InheritsProperty: exp.Properties.Location.POST_SCHEMA, 543 exp.IcebergProperty: exp.Properties.Location.POST_CREATE, 544 exp.IncludeProperty: exp.Properties.Location.POST_SCHEMA, 545 exp.InputModelProperty: exp.Properties.Location.POST_SCHEMA, 546 exp.IsolatedLoadingProperty: exp.Properties.Location.POST_NAME, 547 exp.JournalProperty: exp.Properties.Location.POST_NAME, 548 exp.LanguageProperty: exp.Properties.Location.POST_SCHEMA, 549 exp.LikeProperty: exp.Properties.Location.POST_SCHEMA, 550 exp.LocationProperty: exp.Properties.Location.POST_SCHEMA, 551 exp.LockProperty: exp.Properties.Location.POST_SCHEMA, 552 exp.LockingProperty: exp.Properties.Location.POST_ALIAS, 553 exp.LogProperty: exp.Properties.Location.POST_NAME, 554 exp.MaterializedProperty: exp.Properties.Location.POST_CREATE, 555 exp.MergeBlockRatioProperty: exp.Properties.Location.POST_NAME, 556 exp.NoPrimaryIndexProperty: exp.Properties.Location.POST_EXPRESSION, 557 exp.OnProperty: exp.Properties.Location.POST_SCHEMA, 558 exp.OnCommitProperty: exp.Properties.Location.POST_EXPRESSION, 559 exp.Order: exp.Properties.Location.POST_SCHEMA, 560 exp.OutputModelProperty: exp.Properties.Location.POST_SCHEMA, 561 exp.PartitionedByProperty: exp.Properties.Location.POST_WITH, 562 exp.PartitionedOfProperty: exp.Properties.Location.POST_SCHEMA, 563 exp.PrimaryKey: exp.Properties.Location.POST_SCHEMA, 564 exp.Property: exp.Properties.Location.POST_WITH, 565 exp.RemoteWithConnectionModelProperty: exp.Properties.Location.POST_SCHEMA, 566 exp.ReturnsProperty: exp.Properties.Location.POST_SCHEMA, 567 exp.RowFormatProperty: exp.Properties.Location.POST_SCHEMA, 568 exp.RowFormatDelimitedProperty: exp.Properties.Location.POST_SCHEMA, 569 exp.RowFormatSerdeProperty: exp.Properties.Location.POST_SCHEMA, 570 exp.SampleProperty: exp.Properties.Location.POST_SCHEMA, 571 exp.SchemaCommentProperty: exp.Properties.Location.POST_SCHEMA, 572 exp.SecureProperty: exp.Properties.Location.POST_CREATE, 573 exp.SecurityProperty: exp.Properties.Location.POST_SCHEMA, 574 exp.SerdeProperties: exp.Properties.Location.POST_SCHEMA, 575 exp.Set: exp.Properties.Location.POST_SCHEMA, 576 exp.SettingsProperty: exp.Properties.Location.POST_SCHEMA, 577 exp.SetProperty: exp.Properties.Location.POST_CREATE, 578 exp.SetConfigProperty: exp.Properties.Location.POST_SCHEMA, 579 exp.SharingProperty: exp.Properties.Location.POST_EXPRESSION, 580 exp.SequenceProperties: exp.Properties.Location.POST_EXPRESSION, 581 exp.SortKeyProperty: exp.Properties.Location.POST_SCHEMA, 582 exp.SqlReadWriteProperty: exp.Properties.Location.POST_SCHEMA, 583 exp.SqlSecurityProperty: exp.Properties.Location.POST_CREATE, 584 exp.StabilityProperty: exp.Properties.Location.POST_SCHEMA, 585 exp.StreamingTableProperty: exp.Properties.Location.POST_CREATE, 586 exp.StrictProperty: exp.Properties.Location.POST_SCHEMA, 587 exp.Tags: exp.Properties.Location.POST_WITH, 588 exp.TemporaryProperty: exp.Properties.Location.POST_CREATE, 589 exp.ToTableProperty: exp.Properties.Location.POST_SCHEMA, 590 exp.TransientProperty: exp.Properties.Location.POST_CREATE, 591 exp.TransformModelProperty: exp.Properties.Location.POST_SCHEMA, 592 exp.MergeTreeTTL: exp.Properties.Location.POST_SCHEMA, 593 exp.UnloggedProperty: exp.Properties.Location.POST_CREATE, 594 exp.ViewAttributeProperty: exp.Properties.Location.POST_SCHEMA, 595 exp.VolatileProperty: exp.Properties.Location.POST_CREATE, 596 exp.WithDataProperty: exp.Properties.Location.POST_EXPRESSION, 597 exp.WithJournalTableProperty: exp.Properties.Location.POST_NAME, 598 exp.WithProcedureOptions: exp.Properties.Location.POST_SCHEMA, 599 exp.WithSchemaBindingProperty: exp.Properties.Location.POST_SCHEMA, 600 exp.WithSystemVersioningProperty: exp.Properties.Location.POST_SCHEMA, 601 } 602 603 # Keywords that can't be used as unquoted identifier names 604 RESERVED_KEYWORDS: t.Set[str] = set() 605 606 # Expressions whose comments are separated from them for better formatting 607 WITH_SEPARATED_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 608 exp.Command, 609 exp.Create, 610 exp.Describe, 611 exp.Delete, 612 exp.Drop, 613 exp.From, 614 exp.Insert, 615 exp.Join, 616 exp.MultitableInserts, 617 exp.Select, 618 exp.SetOperation, 619 exp.Update, 620 exp.Where, 621 exp.With, 622 ) 623 624 # Expressions that should not have their comments generated in maybe_comment 625 EXCLUDE_COMMENTS: t.Tuple[t.Type[exp.Expression], ...] = ( 626 exp.Binary, 627 exp.SetOperation, 628 ) 629 630 # Expressions that can remain unwrapped when appearing in the context of an INTERVAL 631 UNWRAPPED_INTERVAL_VALUES: t.Tuple[t.Type[exp.Expression], ...] = ( 632 exp.Column, 633 exp.Literal, 634 exp.Neg, 635 exp.Paren, 636 ) 637 638 PARAMETERIZABLE_TEXT_TYPES = { 639 exp.DataType.Type.NVARCHAR, 640 exp.DataType.Type.VARCHAR, 641 exp.DataType.Type.CHAR, 642 exp.DataType.Type.NCHAR, 643 } 644 645 # Expressions that need to have all CTEs under them bubbled up to them 646 EXPRESSIONS_WITHOUT_NESTED_CTES: t.Set[t.Type[exp.Expression]] = set() 647 648 SENTINEL_LINE_BREAK = "__SQLGLOT__LB__" 649 650 __slots__ = ( 651 "pretty", 652 "identify", 653 "normalize", 654 "pad", 655 "_indent", 656 "normalize_functions", 657 "unsupported_level", 658 "max_unsupported", 659 "leading_comma", 660 "max_text_width", 661 "comments", 662 "dialect", 663 "unsupported_messages", 664 "_escaped_quote_end", 665 "_escaped_identifier_end", 666 "_next_name", 667 "_identifier_start", 668 "_identifier_end", 669 "_quote_json_path_key_using_brackets", 670 ) 671 672 def __init__( 673 self, 674 pretty: t.Optional[bool] = None, 675 identify: str | bool = False, 676 normalize: bool = False, 677 pad: int = 2, 678 indent: int = 2, 679 normalize_functions: t.Optional[str | bool] = None, 680 unsupported_level: ErrorLevel = ErrorLevel.WARN, 681 max_unsupported: int = 3, 682 leading_comma: bool = False, 683 max_text_width: int = 80, 684 comments: bool = True, 685 dialect: DialectType = None, 686 ): 687 import sqlglot 688 from sqlglot.dialects import Dialect 689 690 self.pretty = pretty if pretty is not None else sqlglot.pretty 691 self.identify = identify 692 self.normalize = normalize 693 self.pad = pad 694 self._indent = indent 695 self.unsupported_level = unsupported_level 696 self.max_unsupported = max_unsupported 697 self.leading_comma = leading_comma 698 self.max_text_width = max_text_width 699 self.comments = comments 700 self.dialect = Dialect.get_or_raise(dialect) 701 702 # This is both a Dialect property and a Generator argument, so we prioritize the latter 703 self.normalize_functions = ( 704 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 705 ) 706 707 self.unsupported_messages: t.List[str] = [] 708 self._escaped_quote_end: str = ( 709 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 710 ) 711 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 712 713 self._next_name = name_sequence("_t") 714 715 self._identifier_start = self.dialect.IDENTIFIER_START 716 self._identifier_end = self.dialect.IDENTIFIER_END 717 718 self._quote_json_path_key_using_brackets = True 719 720 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 721 """ 722 Generates the SQL string corresponding to the given syntax tree. 723 724 Args: 725 expression: The syntax tree. 726 copy: Whether to copy the expression. The generator performs mutations so 727 it is safer to copy. 728 729 Returns: 730 The SQL string corresponding to `expression`. 731 """ 732 if copy: 733 expression = expression.copy() 734 735 expression = self.preprocess(expression) 736 737 self.unsupported_messages = [] 738 sql = self.sql(expression).strip() 739 740 if self.pretty: 741 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 742 743 if self.unsupported_level == ErrorLevel.IGNORE: 744 return sql 745 746 if self.unsupported_level == ErrorLevel.WARN: 747 for msg in self.unsupported_messages: 748 logger.warning(msg) 749 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 750 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 751 752 return sql 753 754 def preprocess(self, expression: exp.Expression) -> exp.Expression: 755 """Apply generic preprocessing transformations to a given expression.""" 756 expression = self._move_ctes_to_top_level(expression) 757 758 if self.ENSURE_BOOLS: 759 from sqlglot.transforms import ensure_bools 760 761 expression = ensure_bools(expression) 762 763 return expression 764 765 def _move_ctes_to_top_level(self, expression: E) -> E: 766 if ( 767 not expression.parent 768 and type(expression) in self.EXPRESSIONS_WITHOUT_NESTED_CTES 769 and any(node.parent is not expression for node in expression.find_all(exp.With)) 770 ): 771 from sqlglot.transforms import move_ctes_to_top_level 772 773 expression = move_ctes_to_top_level(expression) 774 return expression 775 776 def unsupported(self, message: str) -> None: 777 if self.unsupported_level == ErrorLevel.IMMEDIATE: 778 raise UnsupportedError(message) 779 self.unsupported_messages.append(message) 780 781 def sep(self, sep: str = " ") -> str: 782 return f"{sep.strip()}\n" if self.pretty else sep 783 784 def seg(self, sql: str, sep: str = " ") -> str: 785 return f"{self.sep(sep)}{sql}" 786 787 def pad_comment(self, comment: str) -> str: 788 comment = " " + comment if comment[0].strip() else comment 789 comment = comment + " " if comment[-1].strip() else comment 790 return comment 791 792 def maybe_comment( 793 self, 794 sql: str, 795 expression: t.Optional[exp.Expression] = None, 796 comments: t.Optional[t.List[str]] = None, 797 separated: bool = False, 798 ) -> str: 799 comments = ( 800 ((expression and expression.comments) if comments is None else comments) # type: ignore 801 if self.comments 802 else None 803 ) 804 805 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 806 return sql 807 808 comments_sql = " ".join( 809 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 810 ) 811 812 if not comments_sql: 813 return sql 814 815 comments_sql = self._replace_line_breaks(comments_sql) 816 817 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 818 return ( 819 f"{self.sep()}{comments_sql}{sql}" 820 if not sql or sql[0].isspace() 821 else f"{comments_sql}{self.sep()}{sql}" 822 ) 823 824 return f"{sql} {comments_sql}" 825 826 def wrap(self, expression: exp.Expression | str) -> str: 827 this_sql = ( 828 self.sql(expression) 829 if isinstance(expression, exp.UNWRAPPED_QUERIES) 830 else self.sql(expression, "this") 831 ) 832 if not this_sql: 833 return "()" 834 835 this_sql = self.indent(this_sql, level=1, pad=0) 836 return f"({self.sep('')}{this_sql}{self.seg(')', sep='')}" 837 838 def no_identify(self, func: t.Callable[..., str], *args, **kwargs) -> str: 839 original = self.identify 840 self.identify = False 841 result = func(*args, **kwargs) 842 self.identify = original 843 return result 844 845 def normalize_func(self, name: str) -> str: 846 if self.normalize_functions == "upper" or self.normalize_functions is True: 847 return name.upper() 848 if self.normalize_functions == "lower": 849 return name.lower() 850 return name 851 852 def indent( 853 self, 854 sql: str, 855 level: int = 0, 856 pad: t.Optional[int] = None, 857 skip_first: bool = False, 858 skip_last: bool = False, 859 ) -> str: 860 if not self.pretty or not sql: 861 return sql 862 863 pad = self.pad if pad is None else pad 864 lines = sql.split("\n") 865 866 return "\n".join( 867 ( 868 line 869 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 870 else f"{' ' * (level * self._indent + pad)}{line}" 871 ) 872 for i, line in enumerate(lines) 873 ) 874 875 def sql( 876 self, 877 expression: t.Optional[str | exp.Expression], 878 key: t.Optional[str] = None, 879 comment: bool = True, 880 ) -> str: 881 if not expression: 882 return "" 883 884 if isinstance(expression, str): 885 return expression 886 887 if key: 888 value = expression.args.get(key) 889 if value: 890 return self.sql(value) 891 return "" 892 893 transform = self.TRANSFORMS.get(expression.__class__) 894 895 if callable(transform): 896 sql = transform(self, expression) 897 elif isinstance(expression, exp.Expression): 898 exp_handler_name = f"{expression.key}_sql" 899 900 if hasattr(self, exp_handler_name): 901 sql = getattr(self, exp_handler_name)(expression) 902 elif isinstance(expression, exp.Func): 903 sql = self.function_fallback_sql(expression) 904 elif isinstance(expression, exp.Property): 905 sql = self.property_sql(expression) 906 else: 907 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 908 else: 909 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 910 911 return self.maybe_comment(sql, expression) if self.comments and comment else sql 912 913 def uncache_sql(self, expression: exp.Uncache) -> str: 914 table = self.sql(expression, "this") 915 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 916 return f"UNCACHE TABLE{exists_sql} {table}" 917 918 def cache_sql(self, expression: exp.Cache) -> str: 919 lazy = " LAZY" if expression.args.get("lazy") else "" 920 table = self.sql(expression, "this") 921 options = expression.args.get("options") 922 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 923 sql = self.sql(expression, "expression") 924 sql = f" AS{self.sep()}{sql}" if sql else "" 925 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 926 return self.prepend_ctes(expression, sql) 927 928 def characterset_sql(self, expression: exp.CharacterSet) -> str: 929 if isinstance(expression.parent, exp.Cast): 930 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 931 default = "DEFAULT " if expression.args.get("default") else "" 932 return f"{default}CHARACTER SET={self.sql(expression, 'this')}" 933 934 def column_parts(self, expression: exp.Column) -> str: 935 return ".".join( 936 self.sql(part) 937 for part in ( 938 expression.args.get("catalog"), 939 expression.args.get("db"), 940 expression.args.get("table"), 941 expression.args.get("this"), 942 ) 943 if part 944 ) 945 946 def column_sql(self, expression: exp.Column) -> str: 947 join_mark = " (+)" if expression.args.get("join_mark") else "" 948 949 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 950 join_mark = "" 951 self.unsupported("Outer join syntax using the (+) operator is not supported.") 952 953 return f"{self.column_parts(expression)}{join_mark}" 954 955 def columnposition_sql(self, expression: exp.ColumnPosition) -> str: 956 this = self.sql(expression, "this") 957 this = f" {this}" if this else "" 958 position = self.sql(expression, "position") 959 return f"{position}{this}" 960 961 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 962 column = self.sql(expression, "this") 963 kind = self.sql(expression, "kind") 964 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 965 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 966 kind = f"{sep}{kind}" if kind else "" 967 constraints = f" {constraints}" if constraints else "" 968 position = self.sql(expression, "position") 969 position = f" {position}" if position else "" 970 971 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 972 kind = "" 973 974 return f"{exists}{column}{kind}{constraints}{position}" 975 976 def columnconstraint_sql(self, expression: exp.ColumnConstraint) -> str: 977 this = self.sql(expression, "this") 978 kind_sql = self.sql(expression, "kind").strip() 979 return f"CONSTRAINT {this} {kind_sql}" if this else kind_sql 980 981 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 982 this = self.sql(expression, "this") 983 if expression.args.get("not_null"): 984 persisted = " PERSISTED NOT NULL" 985 elif expression.args.get("persisted"): 986 persisted = " PERSISTED" 987 else: 988 persisted = "" 989 return f"AS {this}{persisted}" 990 991 def autoincrementcolumnconstraint_sql(self, _) -> str: 992 return self.token_sql(TokenType.AUTO_INCREMENT) 993 994 def compresscolumnconstraint_sql(self, expression: exp.CompressColumnConstraint) -> str: 995 if isinstance(expression.this, list): 996 this = self.wrap(self.expressions(expression, key="this", flat=True)) 997 else: 998 this = self.sql(expression, "this") 999 1000 return f"COMPRESS {this}" 1001 1002 def generatedasidentitycolumnconstraint_sql( 1003 self, expression: exp.GeneratedAsIdentityColumnConstraint 1004 ) -> str: 1005 this = "" 1006 if expression.this is not None: 1007 on_null = " ON NULL" if expression.args.get("on_null") else "" 1008 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1009 1010 start = expression.args.get("start") 1011 start = f"START WITH {start}" if start else "" 1012 increment = expression.args.get("increment") 1013 increment = f" INCREMENT BY {increment}" if increment else "" 1014 minvalue = expression.args.get("minvalue") 1015 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1016 maxvalue = expression.args.get("maxvalue") 1017 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1018 cycle = expression.args.get("cycle") 1019 cycle_sql = "" 1020 1021 if cycle is not None: 1022 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1023 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1024 1025 sequence_opts = "" 1026 if start or increment or cycle_sql: 1027 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1028 sequence_opts = f" ({sequence_opts.strip()})" 1029 1030 expr = self.sql(expression, "expression") 1031 expr = f"({expr})" if expr else "IDENTITY" 1032 1033 return f"GENERATED{this} AS {expr}{sequence_opts}" 1034 1035 def generatedasrowcolumnconstraint_sql( 1036 self, expression: exp.GeneratedAsRowColumnConstraint 1037 ) -> str: 1038 start = "START" if expression.args.get("start") else "END" 1039 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1040 return f"GENERATED ALWAYS AS ROW {start}{hidden}" 1041 1042 def periodforsystemtimeconstraint_sql( 1043 self, expression: exp.PeriodForSystemTimeConstraint 1044 ) -> str: 1045 return f"PERIOD FOR SYSTEM_TIME ({self.sql(expression, 'this')}, {self.sql(expression, 'expression')})" 1046 1047 def notnullcolumnconstraint_sql(self, expression: exp.NotNullColumnConstraint) -> str: 1048 return f"{'' if expression.args.get('allow_null') else 'NOT '}NULL" 1049 1050 def transformcolumnconstraint_sql(self, expression: exp.TransformColumnConstraint) -> str: 1051 return f"AS {self.sql(expression, 'this')}" 1052 1053 def primarykeycolumnconstraint_sql(self, expression: exp.PrimaryKeyColumnConstraint) -> str: 1054 desc = expression.args.get("desc") 1055 if desc is not None: 1056 return f"PRIMARY KEY{' DESC' if desc else ' ASC'}" 1057 return "PRIMARY KEY" 1058 1059 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1060 this = self.sql(expression, "this") 1061 this = f" {this}" if this else "" 1062 index_type = expression.args.get("index_type") 1063 index_type = f" USING {index_type}" if index_type else "" 1064 on_conflict = self.sql(expression, "on_conflict") 1065 on_conflict = f" {on_conflict}" if on_conflict else "" 1066 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1067 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}" 1068 1069 def createable_sql(self, expression: exp.Create, locations: t.DefaultDict) -> str: 1070 return self.sql(expression, "this") 1071 1072 def create_sql(self, expression: exp.Create) -> str: 1073 kind = self.sql(expression, "kind") 1074 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1075 properties = expression.args.get("properties") 1076 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1077 1078 this = self.createable_sql(expression, properties_locs) 1079 1080 properties_sql = "" 1081 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1082 exp.Properties.Location.POST_WITH 1083 ): 1084 properties_sql = self.sql( 1085 exp.Properties( 1086 expressions=[ 1087 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1088 *properties_locs[exp.Properties.Location.POST_WITH], 1089 ] 1090 ) 1091 ) 1092 1093 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1094 properties_sql = self.sep() + properties_sql 1095 elif not self.pretty: 1096 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1097 properties_sql = f" {properties_sql}" 1098 1099 begin = " BEGIN" if expression.args.get("begin") else "" 1100 end = " END" if expression.args.get("end") else "" 1101 1102 expression_sql = self.sql(expression, "expression") 1103 if expression_sql: 1104 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1105 1106 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1107 postalias_props_sql = "" 1108 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1109 postalias_props_sql = self.properties( 1110 exp.Properties( 1111 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1112 ), 1113 wrapped=False, 1114 ) 1115 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1116 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1117 1118 postindex_props_sql = "" 1119 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1120 postindex_props_sql = self.properties( 1121 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1122 wrapped=False, 1123 prefix=" ", 1124 ) 1125 1126 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1127 indexes = f" {indexes}" if indexes else "" 1128 index_sql = indexes + postindex_props_sql 1129 1130 replace = " OR REPLACE" if expression.args.get("replace") else "" 1131 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1132 unique = " UNIQUE" if expression.args.get("unique") else "" 1133 1134 clustered = expression.args.get("clustered") 1135 if clustered is None: 1136 clustered_sql = "" 1137 elif clustered: 1138 clustered_sql = " CLUSTERED COLUMNSTORE" 1139 else: 1140 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1141 1142 postcreate_props_sql = "" 1143 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1144 postcreate_props_sql = self.properties( 1145 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1146 sep=" ", 1147 prefix=" ", 1148 wrapped=False, 1149 ) 1150 1151 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1152 1153 postexpression_props_sql = "" 1154 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1155 postexpression_props_sql = self.properties( 1156 exp.Properties( 1157 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1158 ), 1159 sep=" ", 1160 prefix=" ", 1161 wrapped=False, 1162 ) 1163 1164 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1165 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1166 no_schema_binding = ( 1167 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1168 ) 1169 1170 clone = self.sql(expression, "clone") 1171 clone = f" {clone}" if clone else "" 1172 1173 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1174 properties_expression = f"{expression_sql}{properties_sql}" 1175 else: 1176 properties_expression = f"{properties_sql}{expression_sql}" 1177 1178 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1179 return self.prepend_ctes(expression, expression_sql) 1180 1181 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1182 start = self.sql(expression, "start") 1183 start = f"START WITH {start}" if start else "" 1184 increment = self.sql(expression, "increment") 1185 increment = f" INCREMENT BY {increment}" if increment else "" 1186 minvalue = self.sql(expression, "minvalue") 1187 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1188 maxvalue = self.sql(expression, "maxvalue") 1189 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1190 owned = self.sql(expression, "owned") 1191 owned = f" OWNED BY {owned}" if owned else "" 1192 1193 cache = expression.args.get("cache") 1194 if cache is None: 1195 cache_str = "" 1196 elif cache is True: 1197 cache_str = " CACHE" 1198 else: 1199 cache_str = f" CACHE {cache}" 1200 1201 options = self.expressions(expression, key="options", flat=True, sep=" ") 1202 options = f" {options}" if options else "" 1203 1204 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip() 1205 1206 def clone_sql(self, expression: exp.Clone) -> str: 1207 this = self.sql(expression, "this") 1208 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1209 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1210 return f"{shallow}{keyword} {this}" 1211 1212 def describe_sql(self, expression: exp.Describe) -> str: 1213 style = expression.args.get("style") 1214 style = f" {style}" if style else "" 1215 partition = self.sql(expression, "partition") 1216 partition = f" {partition}" if partition else "" 1217 format = self.sql(expression, "format") 1218 format = f" {format}" if format else "" 1219 1220 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}" 1221 1222 def heredoc_sql(self, expression: exp.Heredoc) -> str: 1223 tag = self.sql(expression, "tag") 1224 return f"${tag}${self.sql(expression, 'this')}${tag}$" 1225 1226 def prepend_ctes(self, expression: exp.Expression, sql: str) -> str: 1227 with_ = self.sql(expression, "with") 1228 if with_: 1229 sql = f"{with_}{self.sep()}{sql}" 1230 return sql 1231 1232 def with_sql(self, expression: exp.With) -> str: 1233 sql = self.expressions(expression, flat=True) 1234 recursive = ( 1235 "RECURSIVE " 1236 if self.CTE_RECURSIVE_KEYWORD_REQUIRED and expression.args.get("recursive") 1237 else "" 1238 ) 1239 1240 return f"WITH {recursive}{sql}" 1241 1242 def cte_sql(self, expression: exp.CTE) -> str: 1243 alias = expression.args.get("alias") 1244 if alias: 1245 alias.add_comments(expression.pop_comments()) 1246 1247 alias_sql = self.sql(expression, "alias") 1248 1249 materialized = expression.args.get("materialized") 1250 if materialized is False: 1251 materialized = "NOT MATERIALIZED " 1252 elif materialized: 1253 materialized = "MATERIALIZED " 1254 1255 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}" 1256 1257 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1258 alias = self.sql(expression, "this") 1259 columns = self.expressions(expression, key="columns", flat=True) 1260 columns = f"({columns})" if columns else "" 1261 1262 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1263 columns = "" 1264 self.unsupported("Named columns are not supported in table alias.") 1265 1266 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1267 alias = self._next_name() 1268 1269 return f"{alias}{columns}" 1270 1271 def bitstring_sql(self, expression: exp.BitString) -> str: 1272 this = self.sql(expression, "this") 1273 if self.dialect.BIT_START: 1274 return f"{self.dialect.BIT_START}{this}{self.dialect.BIT_END}" 1275 return f"{int(this, 2)}" 1276 1277 def hexstring_sql(self, expression: exp.HexString) -> str: 1278 this = self.sql(expression, "this") 1279 if self.dialect.HEX_START: 1280 return f"{self.dialect.HEX_START}{this}{self.dialect.HEX_END}" 1281 return f"{int(this, 16)}" 1282 1283 def bytestring_sql(self, expression: exp.ByteString) -> str: 1284 this = self.sql(expression, "this") 1285 if self.dialect.BYTE_START: 1286 return f"{self.dialect.BYTE_START}{this}{self.dialect.BYTE_END}" 1287 return this 1288 1289 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1290 this = self.sql(expression, "this") 1291 escape = expression.args.get("escape") 1292 1293 if self.dialect.UNICODE_START: 1294 escape_substitute = r"\\\1" 1295 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1296 else: 1297 escape_substitute = r"\\u\1" 1298 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1299 1300 if escape: 1301 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1302 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1303 else: 1304 escape_pattern = ESCAPED_UNICODE_RE 1305 escape_sql = "" 1306 1307 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1308 this = escape_pattern.sub(escape_substitute, this) 1309 1310 return f"{left_quote}{this}{right_quote}{escape_sql}" 1311 1312 def rawstring_sql(self, expression: exp.RawString) -> str: 1313 string = self.escape_str(expression.this.replace("\\", "\\\\"), escape_backslash=False) 1314 return f"{self.dialect.QUOTE_START}{string}{self.dialect.QUOTE_END}" 1315 1316 def datatypeparam_sql(self, expression: exp.DataTypeParam) -> str: 1317 this = self.sql(expression, "this") 1318 specifier = self.sql(expression, "expression") 1319 specifier = f" {specifier}" if specifier and self.DATA_TYPE_SPECIFIERS_ALLOWED else "" 1320 return f"{this}{specifier}" 1321 1322 def datatype_sql(self, expression: exp.DataType) -> str: 1323 nested = "" 1324 values = "" 1325 interior = self.expressions(expression, flat=True) 1326 1327 type_value = expression.this 1328 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1329 type_sql = self.sql(expression, "kind") 1330 else: 1331 type_sql = ( 1332 self.TYPE_MAPPING.get(type_value, type_value.value) 1333 if isinstance(type_value, exp.DataType.Type) 1334 else type_value 1335 ) 1336 1337 if interior: 1338 if expression.args.get("nested"): 1339 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1340 if expression.args.get("values") is not None: 1341 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1342 values = self.expressions(expression, key="values", flat=True) 1343 values = f"{delimiters[0]}{values}{delimiters[1]}" 1344 elif type_value == exp.DataType.Type.INTERVAL: 1345 nested = f" {interior}" 1346 else: 1347 nested = f"({interior})" 1348 1349 type_sql = f"{type_sql}{nested}{values}" 1350 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1351 exp.DataType.Type.TIMETZ, 1352 exp.DataType.Type.TIMESTAMPTZ, 1353 ): 1354 type_sql = f"{type_sql} WITH TIME ZONE" 1355 1356 return type_sql 1357 1358 def directory_sql(self, expression: exp.Directory) -> str: 1359 local = "LOCAL " if expression.args.get("local") else "" 1360 row_format = self.sql(expression, "row_format") 1361 row_format = f" {row_format}" if row_format else "" 1362 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}" 1363 1364 def delete_sql(self, expression: exp.Delete) -> str: 1365 this = self.sql(expression, "this") 1366 this = f" FROM {this}" if this else "" 1367 using = self.sql(expression, "using") 1368 using = f" USING {using}" if using else "" 1369 cluster = self.sql(expression, "cluster") 1370 cluster = f" {cluster}" if cluster else "" 1371 where = self.sql(expression, "where") 1372 returning = self.sql(expression, "returning") 1373 limit = self.sql(expression, "limit") 1374 tables = self.expressions(expression, key="tables") 1375 tables = f" {tables}" if tables else "" 1376 if self.RETURNING_END: 1377 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1378 else: 1379 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1380 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}") 1381 1382 def drop_sql(self, expression: exp.Drop) -> str: 1383 this = self.sql(expression, "this") 1384 expressions = self.expressions(expression, flat=True) 1385 expressions = f" ({expressions})" if expressions else "" 1386 kind = expression.args["kind"] 1387 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1388 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1389 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1390 on_cluster = self.sql(expression, "cluster") 1391 on_cluster = f" {on_cluster}" if on_cluster else "" 1392 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1393 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1394 cascade = " CASCADE" if expression.args.get("cascade") else "" 1395 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1396 purge = " PURGE" if expression.args.get("purge") else "" 1397 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}" 1398 1399 def set_operation(self, expression: exp.SetOperation) -> str: 1400 op_type = type(expression) 1401 op_name = op_type.key.upper() 1402 1403 distinct = expression.args.get("distinct") 1404 if ( 1405 distinct is False 1406 and op_type in (exp.Except, exp.Intersect) 1407 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1408 ): 1409 self.unsupported(f"{op_name} ALL is not supported") 1410 1411 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1412 1413 if distinct is None: 1414 distinct = default_distinct 1415 if distinct is None: 1416 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1417 1418 if distinct is default_distinct: 1419 kind = "" 1420 else: 1421 kind = " DISTINCT" if distinct else " ALL" 1422 1423 by_name = " BY NAME" if expression.args.get("by_name") else "" 1424 return f"{op_name}{kind}{by_name}" 1425 1426 def set_operations(self, expression: exp.SetOperation) -> str: 1427 if not self.SET_OP_MODIFIERS: 1428 limit = expression.args.get("limit") 1429 order = expression.args.get("order") 1430 1431 if limit or order: 1432 select = self._move_ctes_to_top_level( 1433 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1434 ) 1435 1436 if limit: 1437 select = select.limit(limit.pop(), copy=False) 1438 if order: 1439 select = select.order_by(order.pop(), copy=False) 1440 return self.sql(select) 1441 1442 sqls: t.List[str] = [] 1443 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1444 1445 while stack: 1446 node = stack.pop() 1447 1448 if isinstance(node, exp.SetOperation): 1449 stack.append(node.expression) 1450 stack.append( 1451 self.maybe_comment( 1452 self.set_operation(node), comments=node.comments, separated=True 1453 ) 1454 ) 1455 stack.append(node.this) 1456 else: 1457 sqls.append(self.sql(node)) 1458 1459 this = self.sep().join(sqls) 1460 this = self.query_modifiers(expression, this) 1461 return self.prepend_ctes(expression, this) 1462 1463 def fetch_sql(self, expression: exp.Fetch) -> str: 1464 direction = expression.args.get("direction") 1465 direction = f" {direction}" if direction else "" 1466 count = self.sql(expression, "count") 1467 count = f" {count}" if count else "" 1468 if expression.args.get("percent"): 1469 count = f"{count} PERCENT" 1470 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1471 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}" 1472 1473 def filter_sql(self, expression: exp.Filter) -> str: 1474 if self.AGGREGATE_FILTER_SUPPORTED: 1475 this = self.sql(expression, "this") 1476 where = self.sql(expression, "expression").strip() 1477 return f"{this} FILTER({where})" 1478 1479 agg = expression.this 1480 agg_arg = agg.this 1481 cond = expression.expression.this 1482 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1483 return self.sql(agg) 1484 1485 def hint_sql(self, expression: exp.Hint) -> str: 1486 if not self.QUERY_HINTS: 1487 self.unsupported("Hints are not supported") 1488 return "" 1489 1490 return f" /*+ {self.expressions(expression, sep=self.QUERY_HINT_SEP).strip()} */" 1491 1492 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1493 using = self.sql(expression, "using") 1494 using = f" USING {using}" if using else "" 1495 columns = self.expressions(expression, key="columns", flat=True) 1496 columns = f"({columns})" if columns else "" 1497 partition_by = self.expressions(expression, key="partition_by", flat=True) 1498 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1499 where = self.sql(expression, "where") 1500 include = self.expressions(expression, key="include", flat=True) 1501 if include: 1502 include = f" INCLUDE ({include})" 1503 with_storage = self.expressions(expression, key="with_storage", flat=True) 1504 with_storage = f" WITH ({with_storage})" if with_storage else "" 1505 tablespace = self.sql(expression, "tablespace") 1506 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1507 on = self.sql(expression, "on") 1508 on = f" ON {on}" if on else "" 1509 1510 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}" 1511 1512 def index_sql(self, expression: exp.Index) -> str: 1513 unique = "UNIQUE " if expression.args.get("unique") else "" 1514 primary = "PRIMARY " if expression.args.get("primary") else "" 1515 amp = "AMP " if expression.args.get("amp") else "" 1516 name = self.sql(expression, "this") 1517 name = f"{name} " if name else "" 1518 table = self.sql(expression, "table") 1519 table = f"{self.INDEX_ON} {table}" if table else "" 1520 1521 index = "INDEX " if not table else "" 1522 1523 params = self.sql(expression, "params") 1524 return f"{unique}{primary}{amp}{index}{name}{table}{params}" 1525 1526 def identifier_sql(self, expression: exp.Identifier) -> str: 1527 text = expression.name 1528 lower = text.lower() 1529 text = lower if self.normalize and not expression.quoted else text 1530 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1531 if ( 1532 expression.quoted 1533 or self.dialect.can_identify(text, self.identify) 1534 or lower in self.RESERVED_KEYWORDS 1535 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1536 ): 1537 text = f"{self._identifier_start}{text}{self._identifier_end}" 1538 return text 1539 1540 def hex_sql(self, expression: exp.Hex) -> str: 1541 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1542 if self.dialect.HEX_LOWERCASE: 1543 text = self.func("LOWER", text) 1544 1545 return text 1546 1547 def lowerhex_sql(self, expression: exp.LowerHex) -> str: 1548 text = self.func(self.HEX_FUNC, self.sql(expression, "this")) 1549 if not self.dialect.HEX_LOWERCASE: 1550 text = self.func("LOWER", text) 1551 return text 1552 1553 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1554 input_format = self.sql(expression, "input_format") 1555 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1556 output_format = self.sql(expression, "output_format") 1557 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1558 return self.sep().join((input_format, output_format)) 1559 1560 def national_sql(self, expression: exp.National, prefix: str = "N") -> str: 1561 string = self.sql(exp.Literal.string(expression.name)) 1562 return f"{prefix}{string}" 1563 1564 def partition_sql(self, expression: exp.Partition) -> str: 1565 partition_keyword = "SUBPARTITION" if expression.args.get("subpartition") else "PARTITION" 1566 return f"{partition_keyword}({self.expressions(expression, flat=True)})" 1567 1568 def properties_sql(self, expression: exp.Properties) -> str: 1569 root_properties = [] 1570 with_properties = [] 1571 1572 for p in expression.expressions: 1573 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1574 if p_loc == exp.Properties.Location.POST_WITH: 1575 with_properties.append(p) 1576 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1577 root_properties.append(p) 1578 1579 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1580 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1581 1582 if root_props and with_props and not self.pretty: 1583 with_props = " " + with_props 1584 1585 return root_props + with_props 1586 1587 def root_properties(self, properties: exp.Properties) -> str: 1588 if properties.expressions: 1589 return self.expressions(properties, indent=False, sep=" ") 1590 return "" 1591 1592 def properties( 1593 self, 1594 properties: exp.Properties, 1595 prefix: str = "", 1596 sep: str = ", ", 1597 suffix: str = "", 1598 wrapped: bool = True, 1599 ) -> str: 1600 if properties.expressions: 1601 expressions = self.expressions(properties, sep=sep, indent=False) 1602 if expressions: 1603 expressions = self.wrap(expressions) if wrapped else expressions 1604 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1605 return "" 1606 1607 def with_properties(self, properties: exp.Properties) -> str: 1608 return self.properties(properties, prefix=self.seg(self.WITH_PROPERTIES_PREFIX, sep="")) 1609 1610 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1611 properties_locs = defaultdict(list) 1612 for p in properties.expressions: 1613 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1614 if p_loc != exp.Properties.Location.UNSUPPORTED: 1615 properties_locs[p_loc].append(p) 1616 else: 1617 self.unsupported(f"Unsupported property {p.key}") 1618 1619 return properties_locs 1620 1621 def property_name(self, expression: exp.Property, string_key: bool = False) -> str: 1622 if isinstance(expression.this, exp.Dot): 1623 return self.sql(expression, "this") 1624 return f"'{expression.name}'" if string_key else expression.name 1625 1626 def property_sql(self, expression: exp.Property) -> str: 1627 property_cls = expression.__class__ 1628 if property_cls == exp.Property: 1629 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1630 1631 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1632 if not property_name: 1633 self.unsupported(f"Unsupported property {expression.key}") 1634 1635 return f"{property_name}={self.sql(expression, 'this')}" 1636 1637 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1638 if self.SUPPORTS_CREATE_TABLE_LIKE: 1639 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1640 options = f" {options}" if options else "" 1641 1642 like = f"LIKE {self.sql(expression, 'this')}{options}" 1643 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1644 like = f"({like})" 1645 1646 return like 1647 1648 if expression.expressions: 1649 self.unsupported("Transpilation of LIKE property options is unsupported") 1650 1651 select = exp.select("*").from_(expression.this).limit(0) 1652 return f"AS {self.sql(select)}" 1653 1654 def fallbackproperty_sql(self, expression: exp.FallbackProperty) -> str: 1655 no = "NO " if expression.args.get("no") else "" 1656 protection = " PROTECTION" if expression.args.get("protection") else "" 1657 return f"{no}FALLBACK{protection}" 1658 1659 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1660 no = "NO " if expression.args.get("no") else "" 1661 local = expression.args.get("local") 1662 local = f"{local} " if local else "" 1663 dual = "DUAL " if expression.args.get("dual") else "" 1664 before = "BEFORE " if expression.args.get("before") else "" 1665 after = "AFTER " if expression.args.get("after") else "" 1666 return f"{no}{local}{dual}{before}{after}JOURNAL" 1667 1668 def freespaceproperty_sql(self, expression: exp.FreespaceProperty) -> str: 1669 freespace = self.sql(expression, "this") 1670 percent = " PERCENT" if expression.args.get("percent") else "" 1671 return f"FREESPACE={freespace}{percent}" 1672 1673 def checksumproperty_sql(self, expression: exp.ChecksumProperty) -> str: 1674 if expression.args.get("default"): 1675 property = "DEFAULT" 1676 elif expression.args.get("on"): 1677 property = "ON" 1678 else: 1679 property = "OFF" 1680 return f"CHECKSUM={property}" 1681 1682 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1683 if expression.args.get("no"): 1684 return "NO MERGEBLOCKRATIO" 1685 if expression.args.get("default"): 1686 return "DEFAULT MERGEBLOCKRATIO" 1687 1688 percent = " PERCENT" if expression.args.get("percent") else "" 1689 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}" 1690 1691 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1692 default = expression.args.get("default") 1693 minimum = expression.args.get("minimum") 1694 maximum = expression.args.get("maximum") 1695 if default or minimum or maximum: 1696 if default: 1697 prop = "DEFAULT" 1698 elif minimum: 1699 prop = "MINIMUM" 1700 else: 1701 prop = "MAXIMUM" 1702 return f"{prop} DATABLOCKSIZE" 1703 units = expression.args.get("units") 1704 units = f" {units}" if units else "" 1705 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}" 1706 1707 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1708 autotemp = expression.args.get("autotemp") 1709 always = expression.args.get("always") 1710 default = expression.args.get("default") 1711 manual = expression.args.get("manual") 1712 never = expression.args.get("never") 1713 1714 if autotemp is not None: 1715 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1716 elif always: 1717 prop = "ALWAYS" 1718 elif default: 1719 prop = "DEFAULT" 1720 elif manual: 1721 prop = "MANUAL" 1722 elif never: 1723 prop = "NEVER" 1724 return f"BLOCKCOMPRESSION={prop}" 1725 1726 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1727 no = expression.args.get("no") 1728 no = " NO" if no else "" 1729 concurrent = expression.args.get("concurrent") 1730 concurrent = " CONCURRENT" if concurrent else "" 1731 target = self.sql(expression, "target") 1732 target = f" {target}" if target else "" 1733 return f"WITH{no}{concurrent} ISOLATED LOADING{target}" 1734 1735 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1736 if isinstance(expression.this, list): 1737 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1738 if expression.this: 1739 modulus = self.sql(expression, "this") 1740 remainder = self.sql(expression, "expression") 1741 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1742 1743 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1744 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1745 return f"FROM ({from_expressions}) TO ({to_expressions})" 1746 1747 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1748 this = self.sql(expression, "this") 1749 1750 for_values_or_default = expression.expression 1751 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1752 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1753 else: 1754 for_values_or_default = " DEFAULT" 1755 1756 return f"PARTITION OF {this}{for_values_or_default}" 1757 1758 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1759 kind = expression.args.get("kind") 1760 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1761 for_or_in = expression.args.get("for_or_in") 1762 for_or_in = f" {for_or_in}" if for_or_in else "" 1763 lock_type = expression.args.get("lock_type") 1764 override = " OVERRIDE" if expression.args.get("override") else "" 1765 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}" 1766 1767 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1768 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1769 statistics = expression.args.get("statistics") 1770 statistics_sql = "" 1771 if statistics is not None: 1772 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1773 return f"{data_sql}{statistics_sql}" 1774 1775 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1776 this = self.sql(expression, "this") 1777 this = f"HISTORY_TABLE={this}" if this else "" 1778 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1779 data_consistency = ( 1780 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1781 ) 1782 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1783 retention_period = ( 1784 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1785 ) 1786 1787 if this: 1788 on_sql = self.func("ON", this, data_consistency, retention_period) 1789 else: 1790 on_sql = "ON" if expression.args.get("on") else "OFF" 1791 1792 sql = f"SYSTEM_VERSIONING={on_sql}" 1793 1794 return f"WITH({sql})" if expression.args.get("with") else sql 1795 1796 def insert_sql(self, expression: exp.Insert) -> str: 1797 hint = self.sql(expression, "hint") 1798 overwrite = expression.args.get("overwrite") 1799 1800 if isinstance(expression.this, exp.Directory): 1801 this = " OVERWRITE" if overwrite else " INTO" 1802 else: 1803 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1804 1805 stored = self.sql(expression, "stored") 1806 stored = f" {stored}" if stored else "" 1807 alternative = expression.args.get("alternative") 1808 alternative = f" OR {alternative}" if alternative else "" 1809 ignore = " IGNORE" if expression.args.get("ignore") else "" 1810 is_function = expression.args.get("is_function") 1811 if is_function: 1812 this = f"{this} FUNCTION" 1813 this = f"{this} {self.sql(expression, 'this')}" 1814 1815 exists = " IF EXISTS" if expression.args.get("exists") else "" 1816 where = self.sql(expression, "where") 1817 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1818 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1819 on_conflict = self.sql(expression, "conflict") 1820 on_conflict = f" {on_conflict}" if on_conflict else "" 1821 by_name = " BY NAME" if expression.args.get("by_name") else "" 1822 returning = self.sql(expression, "returning") 1823 1824 if self.RETURNING_END: 1825 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1826 else: 1827 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1828 1829 partition_by = self.sql(expression, "partition") 1830 partition_by = f" {partition_by}" if partition_by else "" 1831 settings = self.sql(expression, "settings") 1832 settings = f" {settings}" if settings else "" 1833 1834 source = self.sql(expression, "source") 1835 source = f"TABLE {source}" if source else "" 1836 1837 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1838 return self.prepend_ctes(expression, sql) 1839 1840 def introducer_sql(self, expression: exp.Introducer) -> str: 1841 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 1842 1843 def kill_sql(self, expression: exp.Kill) -> str: 1844 kind = self.sql(expression, "kind") 1845 kind = f" {kind}" if kind else "" 1846 this = self.sql(expression, "this") 1847 this = f" {this}" if this else "" 1848 return f"KILL{kind}{this}" 1849 1850 def pseudotype_sql(self, expression: exp.PseudoType) -> str: 1851 return expression.name 1852 1853 def objectidentifier_sql(self, expression: exp.ObjectIdentifier) -> str: 1854 return expression.name 1855 1856 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1857 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1858 1859 constraint = self.sql(expression, "constraint") 1860 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1861 1862 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1863 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1864 action = self.sql(expression, "action") 1865 1866 expressions = self.expressions(expression, flat=True) 1867 if expressions: 1868 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1869 expressions = f" {set_keyword}{expressions}" 1870 1871 where = self.sql(expression, "where") 1872 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}" 1873 1874 def returning_sql(self, expression: exp.Returning) -> str: 1875 return f"{self.seg('RETURNING')} {self.expressions(expression, flat=True)}" 1876 1877 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1878 fields = self.sql(expression, "fields") 1879 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1880 escaped = self.sql(expression, "escaped") 1881 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1882 items = self.sql(expression, "collection_items") 1883 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1884 keys = self.sql(expression, "map_keys") 1885 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1886 lines = self.sql(expression, "lines") 1887 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1888 null = self.sql(expression, "null") 1889 null = f" NULL DEFINED AS {null}" if null else "" 1890 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}" 1891 1892 def withtablehint_sql(self, expression: exp.WithTableHint) -> str: 1893 return f"WITH ({self.expressions(expression, flat=True)})" 1894 1895 def indextablehint_sql(self, expression: exp.IndexTableHint) -> str: 1896 this = f"{self.sql(expression, 'this')} INDEX" 1897 target = self.sql(expression, "target") 1898 target = f" FOR {target}" if target else "" 1899 return f"{this}{target} ({self.expressions(expression, flat=True)})" 1900 1901 def historicaldata_sql(self, expression: exp.HistoricalData) -> str: 1902 this = self.sql(expression, "this") 1903 kind = self.sql(expression, "kind") 1904 expr = self.sql(expression, "expression") 1905 return f"{this} ({kind} => {expr})" 1906 1907 def table_parts(self, expression: exp.Table) -> str: 1908 return ".".join( 1909 self.sql(part) 1910 for part in ( 1911 expression.args.get("catalog"), 1912 expression.args.get("db"), 1913 expression.args.get("this"), 1914 ) 1915 if part is not None 1916 ) 1917 1918 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1919 table = self.table_parts(expression) 1920 only = "ONLY " if expression.args.get("only") else "" 1921 partition = self.sql(expression, "partition") 1922 partition = f" {partition}" if partition else "" 1923 version = self.sql(expression, "version") 1924 version = f" {version}" if version else "" 1925 alias = self.sql(expression, "alias") 1926 alias = f"{sep}{alias}" if alias else "" 1927 1928 sample = self.sql(expression, "sample") 1929 if self.dialect.ALIAS_POST_TABLESAMPLE: 1930 sample_pre_alias = sample 1931 sample_post_alias = "" 1932 else: 1933 sample_pre_alias = "" 1934 sample_post_alias = sample 1935 1936 hints = self.expressions(expression, key="hints", sep=" ") 1937 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1938 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1939 joins = self.indent( 1940 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1941 ) 1942 laterals = self.expressions(expression, key="laterals", sep="") 1943 1944 file_format = self.sql(expression, "format") 1945 if file_format: 1946 pattern = self.sql(expression, "pattern") 1947 pattern = f", PATTERN => {pattern}" if pattern else "" 1948 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1949 1950 ordinality = expression.args.get("ordinality") or "" 1951 if ordinality: 1952 ordinality = f" WITH ORDINALITY{alias}" 1953 alias = "" 1954 1955 when = self.sql(expression, "when") 1956 if when: 1957 table = f"{table} {when}" 1958 1959 changes = self.sql(expression, "changes") 1960 changes = f" {changes}" if changes else "" 1961 1962 rows_from = self.expressions(expression, key="rows_from") 1963 if rows_from: 1964 table = f"ROWS FROM {self.wrap(rows_from)}" 1965 1966 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}" 1967 1968 def tablesample_sql( 1969 self, 1970 expression: exp.TableSample, 1971 tablesample_keyword: t.Optional[str] = None, 1972 ) -> str: 1973 method = self.sql(expression, "method") 1974 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1975 numerator = self.sql(expression, "bucket_numerator") 1976 denominator = self.sql(expression, "bucket_denominator") 1977 field = self.sql(expression, "bucket_field") 1978 field = f" ON {field}" if field else "" 1979 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1980 seed = self.sql(expression, "seed") 1981 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1982 1983 size = self.sql(expression, "size") 1984 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1985 size = f"{size} ROWS" 1986 1987 percent = self.sql(expression, "percent") 1988 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1989 percent = f"{percent} PERCENT" 1990 1991 expr = f"{bucket}{percent}{size}" 1992 if self.TABLESAMPLE_REQUIRES_PARENS: 1993 expr = f"({expr})" 1994 1995 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}" 1996 1997 def pivot_sql(self, expression: exp.Pivot) -> str: 1998 expressions = self.expressions(expression, flat=True) 1999 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2000 2001 if expression.this: 2002 this = self.sql(expression, "this") 2003 if not expressions: 2004 return f"UNPIVOT {this}" 2005 2006 on = f"{self.seg('ON')} {expressions}" 2007 into = self.sql(expression, "into") 2008 into = f"{self.seg('INTO')} {into}" if into else "" 2009 using = self.expressions(expression, key="using", flat=True) 2010 using = f"{self.seg('USING')} {using}" if using else "" 2011 group = self.sql(expression, "group") 2012 return f"{direction} {this}{on}{into}{using}{group}" 2013 2014 alias = self.sql(expression, "alias") 2015 alias = f" AS {alias}" if alias else "" 2016 2017 field = self.sql(expression, "field") 2018 2019 include_nulls = expression.args.get("include_nulls") 2020 if include_nulls is not None: 2021 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2022 else: 2023 nulls = "" 2024 2025 default_on_null = self.sql(expression, "default_on_null") 2026 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2027 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}" 2028 2029 def version_sql(self, expression: exp.Version) -> str: 2030 this = f"FOR {expression.name}" 2031 kind = expression.text("kind") 2032 expr = self.sql(expression, "expression") 2033 return f"{this} {kind} {expr}" 2034 2035 def tuple_sql(self, expression: exp.Tuple) -> str: 2036 return f"({self.expressions(expression, dynamic=True, new_line=True, skip_first=True, skip_last=True)})" 2037 2038 def update_sql(self, expression: exp.Update) -> str: 2039 this = self.sql(expression, "this") 2040 set_sql = self.expressions(expression, flat=True) 2041 from_sql = self.sql(expression, "from") 2042 where_sql = self.sql(expression, "where") 2043 returning = self.sql(expression, "returning") 2044 order = self.sql(expression, "order") 2045 limit = self.sql(expression, "limit") 2046 if self.RETURNING_END: 2047 expression_sql = f"{from_sql}{where_sql}{returning}" 2048 else: 2049 expression_sql = f"{returning}{from_sql}{where_sql}" 2050 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2051 return self.prepend_ctes(expression, sql) 2052 2053 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2054 values_as_table = values_as_table and self.VALUES_AS_TABLE 2055 2056 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2057 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2058 args = self.expressions(expression) 2059 alias = self.sql(expression, "alias") 2060 values = f"VALUES{self.seg('')}{args}" 2061 values = ( 2062 f"({values})" 2063 if self.WRAP_DERIVED_VALUES 2064 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2065 else values 2066 ) 2067 return f"{values} AS {alias}" if alias else values 2068 2069 # Converts `VALUES...` expression into a series of select unions. 2070 alias_node = expression.args.get("alias") 2071 column_names = alias_node and alias_node.columns 2072 2073 selects: t.List[exp.Query] = [] 2074 2075 for i, tup in enumerate(expression.expressions): 2076 row = tup.expressions 2077 2078 if i == 0 and column_names: 2079 row = [ 2080 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2081 ] 2082 2083 selects.append(exp.Select(expressions=row)) 2084 2085 if self.pretty: 2086 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2087 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2088 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2089 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2090 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2091 2092 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2093 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2094 return f"({unions}){alias}" 2095 2096 def var_sql(self, expression: exp.Var) -> str: 2097 return self.sql(expression, "this") 2098 2099 @unsupported_args("expressions") 2100 def into_sql(self, expression: exp.Into) -> str: 2101 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2102 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2103 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}" 2104 2105 def from_sql(self, expression: exp.From) -> str: 2106 return f"{self.seg('FROM')} {self.sql(expression, 'this')}" 2107 2108 def groupingsets_sql(self, expression: exp.GroupingSets) -> str: 2109 grouping_sets = self.expressions(expression, indent=False) 2110 return f"GROUPING SETS {self.wrap(grouping_sets)}" 2111 2112 def rollup_sql(self, expression: exp.Rollup) -> str: 2113 expressions = self.expressions(expression, indent=False) 2114 return f"ROLLUP {self.wrap(expressions)}" if expressions else "WITH ROLLUP" 2115 2116 def cube_sql(self, expression: exp.Cube) -> str: 2117 expressions = self.expressions(expression, indent=False) 2118 return f"CUBE {self.wrap(expressions)}" if expressions else "WITH CUBE" 2119 2120 def group_sql(self, expression: exp.Group) -> str: 2121 group_by_all = expression.args.get("all") 2122 if group_by_all is True: 2123 modifier = " ALL" 2124 elif group_by_all is False: 2125 modifier = " DISTINCT" 2126 else: 2127 modifier = "" 2128 2129 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2130 2131 grouping_sets = self.expressions(expression, key="grouping_sets") 2132 cube = self.expressions(expression, key="cube") 2133 rollup = self.expressions(expression, key="rollup") 2134 2135 groupings = csv( 2136 self.seg(grouping_sets) if grouping_sets else "", 2137 self.seg(cube) if cube else "", 2138 self.seg(rollup) if rollup else "", 2139 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2140 sep=self.GROUPINGS_SEP, 2141 ) 2142 2143 if ( 2144 expression.expressions 2145 and groupings 2146 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2147 ): 2148 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2149 2150 return f"{group_by}{groupings}" 2151 2152 def having_sql(self, expression: exp.Having) -> str: 2153 this = self.indent(self.sql(expression, "this")) 2154 return f"{self.seg('HAVING')}{self.sep()}{this}" 2155 2156 def connect_sql(self, expression: exp.Connect) -> str: 2157 start = self.sql(expression, "start") 2158 start = self.seg(f"START WITH {start}") if start else "" 2159 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2160 connect = self.sql(expression, "connect") 2161 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2162 return start + connect 2163 2164 def prior_sql(self, expression: exp.Prior) -> str: 2165 return f"PRIOR {self.sql(expression, 'this')}" 2166 2167 def join_sql(self, expression: exp.Join) -> str: 2168 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2169 side = None 2170 else: 2171 side = expression.side 2172 2173 op_sql = " ".join( 2174 op 2175 for op in ( 2176 expression.method, 2177 "GLOBAL" if expression.args.get("global") else None, 2178 side, 2179 expression.kind, 2180 expression.hint if self.JOIN_HINTS else None, 2181 ) 2182 if op 2183 ) 2184 match_cond = self.sql(expression, "match_condition") 2185 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2186 on_sql = self.sql(expression, "on") 2187 using = expression.args.get("using") 2188 2189 if not on_sql and using: 2190 on_sql = csv(*(self.sql(column) for column in using)) 2191 2192 this = expression.this 2193 this_sql = self.sql(this) 2194 2195 exprs = self.expressions(expression) 2196 if exprs: 2197 this_sql = f"{this_sql},{self.seg(exprs)}" 2198 2199 if on_sql: 2200 on_sql = self.indent(on_sql, skip_first=True) 2201 space = self.seg(" " * self.pad) if self.pretty else " " 2202 if using: 2203 on_sql = f"{space}USING ({on_sql})" 2204 else: 2205 on_sql = f"{space}ON {on_sql}" 2206 elif not op_sql: 2207 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2208 return f" {this_sql}" 2209 2210 return f", {this_sql}" 2211 2212 if op_sql != "STRAIGHT_JOIN": 2213 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2214 2215 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}" 2216 2217 def lambda_sql(self, expression: exp.Lambda, arrow_sep: str = "->") -> str: 2218 args = self.expressions(expression, flat=True) 2219 args = f"({args})" if len(args.split(",")) > 1 else args 2220 return f"{args} {arrow_sep} {self.sql(expression, 'this')}" 2221 2222 def lateral_op(self, expression: exp.Lateral) -> str: 2223 cross_apply = expression.args.get("cross_apply") 2224 2225 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2226 if cross_apply is True: 2227 op = "INNER JOIN " 2228 elif cross_apply is False: 2229 op = "LEFT JOIN " 2230 else: 2231 op = "" 2232 2233 return f"{op}LATERAL" 2234 2235 def lateral_sql(self, expression: exp.Lateral) -> str: 2236 this = self.sql(expression, "this") 2237 2238 if expression.args.get("view"): 2239 alias = expression.args["alias"] 2240 columns = self.expressions(alias, key="columns", flat=True) 2241 table = f" {alias.name}" if alias.name else "" 2242 columns = f" AS {columns}" if columns else "" 2243 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2244 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2245 2246 alias = self.sql(expression, "alias") 2247 alias = f" AS {alias}" if alias else "" 2248 return f"{self.lateral_op(expression)} {this}{alias}" 2249 2250 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2251 this = self.sql(expression, "this") 2252 2253 args = [ 2254 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2255 for e in (expression.args.get(k) for k in ("offset", "expression")) 2256 if e 2257 ] 2258 2259 args_sql = ", ".join(self.sql(e) for e in args) 2260 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2261 expressions = self.expressions(expression, flat=True) 2262 expressions = f" BY {expressions}" if expressions else "" 2263 2264 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}" 2265 2266 def offset_sql(self, expression: exp.Offset) -> str: 2267 this = self.sql(expression, "this") 2268 value = expression.expression 2269 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2270 expressions = self.expressions(expression, flat=True) 2271 expressions = f" BY {expressions}" if expressions else "" 2272 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}" 2273 2274 def setitem_sql(self, expression: exp.SetItem) -> str: 2275 kind = self.sql(expression, "kind") 2276 kind = f"{kind} " if kind else "" 2277 this = self.sql(expression, "this") 2278 expressions = self.expressions(expression) 2279 collate = self.sql(expression, "collate") 2280 collate = f" COLLATE {collate}" if collate else "" 2281 global_ = "GLOBAL " if expression.args.get("global") else "" 2282 return f"{global_}{kind}{this}{expressions}{collate}" 2283 2284 def set_sql(self, expression: exp.Set) -> str: 2285 expressions = ( 2286 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2287 ) 2288 tag = " TAG" if expression.args.get("tag") else "" 2289 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}" 2290 2291 def pragma_sql(self, expression: exp.Pragma) -> str: 2292 return f"PRAGMA {self.sql(expression, 'this')}" 2293 2294 def lock_sql(self, expression: exp.Lock) -> str: 2295 if not self.LOCKING_READS_SUPPORTED: 2296 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2297 return "" 2298 2299 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2300 expressions = self.expressions(expression, flat=True) 2301 expressions = f" OF {expressions}" if expressions else "" 2302 wait = expression.args.get("wait") 2303 2304 if wait is not None: 2305 if isinstance(wait, exp.Literal): 2306 wait = f" WAIT {self.sql(wait)}" 2307 else: 2308 wait = " NOWAIT" if wait else " SKIP LOCKED" 2309 2310 return f"{lock_type}{expressions}{wait or ''}" 2311 2312 def literal_sql(self, expression: exp.Literal) -> str: 2313 text = expression.this or "" 2314 if expression.is_string: 2315 text = f"{self.dialect.QUOTE_START}{self.escape_str(text)}{self.dialect.QUOTE_END}" 2316 return text 2317 2318 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2319 if self.dialect.ESCAPED_SEQUENCES: 2320 to_escaped = self.dialect.ESCAPED_SEQUENCES 2321 text = "".join( 2322 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2323 ) 2324 2325 return self._replace_line_breaks(text).replace( 2326 self.dialect.QUOTE_END, self._escaped_quote_end 2327 ) 2328 2329 def loaddata_sql(self, expression: exp.LoadData) -> str: 2330 local = " LOCAL" if expression.args.get("local") else "" 2331 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2332 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2333 this = f" INTO TABLE {self.sql(expression, 'this')}" 2334 partition = self.sql(expression, "partition") 2335 partition = f" {partition}" if partition else "" 2336 input_format = self.sql(expression, "input_format") 2337 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2338 serde = self.sql(expression, "serde") 2339 serde = f" SERDE {serde}" if serde else "" 2340 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}" 2341 2342 def null_sql(self, *_) -> str: 2343 return "NULL" 2344 2345 def boolean_sql(self, expression: exp.Boolean) -> str: 2346 return "TRUE" if expression.this else "FALSE" 2347 2348 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2349 this = self.sql(expression, "this") 2350 this = f"{this} " if this else this 2351 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2352 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore 2353 2354 def withfill_sql(self, expression: exp.WithFill) -> str: 2355 from_sql = self.sql(expression, "from") 2356 from_sql = f" FROM {from_sql}" if from_sql else "" 2357 to_sql = self.sql(expression, "to") 2358 to_sql = f" TO {to_sql}" if to_sql else "" 2359 step_sql = self.sql(expression, "step") 2360 step_sql = f" STEP {step_sql}" if step_sql else "" 2361 interpolated_values = [ 2362 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2363 if isinstance(e, exp.Alias) 2364 else self.sql(e, "this") 2365 for e in expression.args.get("interpolate") or [] 2366 ] 2367 interpolate = ( 2368 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2369 ) 2370 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}" 2371 2372 def cluster_sql(self, expression: exp.Cluster) -> str: 2373 return self.op_expressions("CLUSTER BY", expression) 2374 2375 def distribute_sql(self, expression: exp.Distribute) -> str: 2376 return self.op_expressions("DISTRIBUTE BY", expression) 2377 2378 def sort_sql(self, expression: exp.Sort) -> str: 2379 return self.op_expressions("SORT BY", expression) 2380 2381 def ordered_sql(self, expression: exp.Ordered) -> str: 2382 desc = expression.args.get("desc") 2383 asc = not desc 2384 2385 nulls_first = expression.args.get("nulls_first") 2386 nulls_last = not nulls_first 2387 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2388 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2389 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2390 2391 this = self.sql(expression, "this") 2392 2393 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2394 nulls_sort_change = "" 2395 if nulls_first and ( 2396 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2397 ): 2398 nulls_sort_change = " NULLS FIRST" 2399 elif ( 2400 nulls_last 2401 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2402 and not nulls_are_last 2403 ): 2404 nulls_sort_change = " NULLS LAST" 2405 2406 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2407 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2408 window = expression.find_ancestor(exp.Window, exp.Select) 2409 if isinstance(window, exp.Window) and window.args.get("spec"): 2410 self.unsupported( 2411 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2412 ) 2413 nulls_sort_change = "" 2414 elif self.NULL_ORDERING_SUPPORTED is False and ( 2415 (asc and nulls_sort_change == " NULLS LAST") 2416 or (desc and nulls_sort_change == " NULLS FIRST") 2417 ): 2418 # BigQuery does not allow these ordering/nulls combinations when used under 2419 # an aggregation func or under a window containing one 2420 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2421 2422 if isinstance(ancestor, exp.Window): 2423 ancestor = ancestor.this 2424 if isinstance(ancestor, exp.AggFunc): 2425 self.unsupported( 2426 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2427 ) 2428 nulls_sort_change = "" 2429 elif self.NULL_ORDERING_SUPPORTED is None: 2430 if expression.this.is_int: 2431 self.unsupported( 2432 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2433 ) 2434 elif not isinstance(expression.this, exp.Rand): 2435 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2436 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2437 nulls_sort_change = "" 2438 2439 with_fill = self.sql(expression, "with_fill") 2440 with_fill = f" {with_fill}" if with_fill else "" 2441 2442 return f"{this}{sort_order}{nulls_sort_change}{with_fill}" 2443 2444 def matchrecognizemeasure_sql(self, expression: exp.MatchRecognizeMeasure) -> str: 2445 window_frame = self.sql(expression, "window_frame") 2446 window_frame = f"{window_frame} " if window_frame else "" 2447 2448 this = self.sql(expression, "this") 2449 2450 return f"{window_frame}{this}" 2451 2452 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2453 partition = self.partition_by_sql(expression) 2454 order = self.sql(expression, "order") 2455 measures = self.expressions(expression, key="measures") 2456 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2457 rows = self.sql(expression, "rows") 2458 rows = self.seg(rows) if rows else "" 2459 after = self.sql(expression, "after") 2460 after = self.seg(after) if after else "" 2461 pattern = self.sql(expression, "pattern") 2462 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2463 definition_sqls = [ 2464 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2465 for definition in expression.args.get("define", []) 2466 ] 2467 definitions = self.expressions(sqls=definition_sqls) 2468 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2469 body = "".join( 2470 ( 2471 partition, 2472 order, 2473 measures, 2474 rows, 2475 after, 2476 pattern, 2477 define, 2478 ) 2479 ) 2480 alias = self.sql(expression, "alias") 2481 alias = f" {alias}" if alias else "" 2482 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}" 2483 2484 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2485 limit = expression.args.get("limit") 2486 2487 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2488 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2489 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2490 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2491 2492 return csv( 2493 *sqls, 2494 *[self.sql(join) for join in expression.args.get("joins") or []], 2495 self.sql(expression, "connect"), 2496 self.sql(expression, "match"), 2497 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2498 self.sql(expression, "prewhere"), 2499 self.sql(expression, "where"), 2500 self.sql(expression, "group"), 2501 self.sql(expression, "having"), 2502 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2503 self.sql(expression, "order"), 2504 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2505 *self.after_limit_modifiers(expression), 2506 self.options_modifier(expression), 2507 sep="", 2508 ) 2509 2510 def options_modifier(self, expression: exp.Expression) -> str: 2511 options = self.expressions(expression, key="options") 2512 return f" {options}" if options else "" 2513 2514 def queryoption_sql(self, expression: exp.QueryOption) -> str: 2515 return "" 2516 2517 def offset_limit_modifiers( 2518 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2519 ) -> t.List[str]: 2520 return [ 2521 self.sql(expression, "offset") if fetch else self.sql(limit), 2522 self.sql(limit) if fetch else self.sql(expression, "offset"), 2523 ] 2524 2525 def after_limit_modifiers(self, expression: exp.Expression) -> t.List[str]: 2526 locks = self.expressions(expression, key="locks", sep=" ") 2527 locks = f" {locks}" if locks else "" 2528 return [locks, self.sql(expression, "sample")] 2529 2530 def select_sql(self, expression: exp.Select) -> str: 2531 into = expression.args.get("into") 2532 if not self.SUPPORTS_SELECT_INTO and into: 2533 into.pop() 2534 2535 hint = self.sql(expression, "hint") 2536 distinct = self.sql(expression, "distinct") 2537 distinct = f" {distinct}" if distinct else "" 2538 kind = self.sql(expression, "kind") 2539 2540 limit = expression.args.get("limit") 2541 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2542 top = self.limit_sql(limit, top=True) 2543 limit.pop() 2544 else: 2545 top = "" 2546 2547 expressions = self.expressions(expression) 2548 2549 if kind: 2550 if kind in self.SELECT_KINDS: 2551 kind = f" AS {kind}" 2552 else: 2553 if kind == "STRUCT": 2554 expressions = self.expressions( 2555 sqls=[ 2556 self.sql( 2557 exp.Struct( 2558 expressions=[ 2559 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2560 if isinstance(e, exp.Alias) 2561 else e 2562 for e in expression.expressions 2563 ] 2564 ) 2565 ) 2566 ] 2567 ) 2568 kind = "" 2569 2570 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2571 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2572 2573 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2574 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2575 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2576 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2577 sql = self.query_modifiers( 2578 expression, 2579 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2580 self.sql(expression, "into", comment=False), 2581 self.sql(expression, "from", comment=False), 2582 ) 2583 2584 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2585 if expression.args.get("with"): 2586 sql = self.maybe_comment(sql, expression) 2587 expression.pop_comments() 2588 2589 sql = self.prepend_ctes(expression, sql) 2590 2591 if not self.SUPPORTS_SELECT_INTO and into: 2592 if into.args.get("temporary"): 2593 table_kind = " TEMPORARY" 2594 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2595 table_kind = " UNLOGGED" 2596 else: 2597 table_kind = "" 2598 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2599 2600 return sql 2601 2602 def schema_sql(self, expression: exp.Schema) -> str: 2603 this = self.sql(expression, "this") 2604 sql = self.schema_columns_sql(expression) 2605 return f"{this} {sql}" if this and sql else this or sql 2606 2607 def schema_columns_sql(self, expression: exp.Schema) -> str: 2608 if expression.expressions: 2609 return f"({self.sep('')}{self.expressions(expression)}{self.seg(')', sep='')}" 2610 return "" 2611 2612 def star_sql(self, expression: exp.Star) -> str: 2613 except_ = self.expressions(expression, key="except", flat=True) 2614 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2615 replace = self.expressions(expression, key="replace", flat=True) 2616 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2617 rename = self.expressions(expression, key="rename", flat=True) 2618 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2619 return f"*{except_}{replace}{rename}" 2620 2621 def parameter_sql(self, expression: exp.Parameter) -> str: 2622 this = self.sql(expression, "this") 2623 return f"{self.PARAMETER_TOKEN}{this}" 2624 2625 def sessionparameter_sql(self, expression: exp.SessionParameter) -> str: 2626 this = self.sql(expression, "this") 2627 kind = expression.text("kind") 2628 if kind: 2629 kind = f"{kind}." 2630 return f"@@{kind}{this}" 2631 2632 def placeholder_sql(self, expression: exp.Placeholder) -> str: 2633 return f"{self.NAMED_PLACEHOLDER_TOKEN}{expression.name}" if expression.this else "?" 2634 2635 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2636 alias = self.sql(expression, "alias") 2637 alias = f"{sep}{alias}" if alias else "" 2638 sample = self.sql(expression, "sample") 2639 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2640 alias = f"{sample}{alias}" 2641 2642 # Set to None so it's not generated again by self.query_modifiers() 2643 expression.set("sample", None) 2644 2645 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2646 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2647 return self.prepend_ctes(expression, sql) 2648 2649 def qualify_sql(self, expression: exp.Qualify) -> str: 2650 this = self.indent(self.sql(expression, "this")) 2651 return f"{self.seg('QUALIFY')}{self.sep()}{this}" 2652 2653 def unnest_sql(self, expression: exp.Unnest) -> str: 2654 args = self.expressions(expression, flat=True) 2655 2656 alias = expression.args.get("alias") 2657 offset = expression.args.get("offset") 2658 2659 if self.UNNEST_WITH_ORDINALITY: 2660 if alias and isinstance(offset, exp.Expression): 2661 alias.append("columns", offset) 2662 2663 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2664 columns = alias.columns 2665 alias = self.sql(columns[0]) if columns else "" 2666 else: 2667 alias = self.sql(alias) 2668 2669 alias = f" AS {alias}" if alias else alias 2670 if self.UNNEST_WITH_ORDINALITY: 2671 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2672 else: 2673 if isinstance(offset, exp.Expression): 2674 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2675 elif offset: 2676 suffix = f"{alias} WITH OFFSET" 2677 else: 2678 suffix = alias 2679 2680 return f"UNNEST({args}){suffix}" 2681 2682 def prewhere_sql(self, expression: exp.PreWhere) -> str: 2683 return "" 2684 2685 def where_sql(self, expression: exp.Where) -> str: 2686 this = self.indent(self.sql(expression, "this")) 2687 return f"{self.seg('WHERE')}{self.sep()}{this}" 2688 2689 def window_sql(self, expression: exp.Window) -> str: 2690 this = self.sql(expression, "this") 2691 partition = self.partition_by_sql(expression) 2692 order = expression.args.get("order") 2693 order = self.order_sql(order, flat=True) if order else "" 2694 spec = self.sql(expression, "spec") 2695 alias = self.sql(expression, "alias") 2696 over = self.sql(expression, "over") or "OVER" 2697 2698 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2699 2700 first = expression.args.get("first") 2701 if first is None: 2702 first = "" 2703 else: 2704 first = "FIRST" if first else "LAST" 2705 2706 if not partition and not order and not spec and alias: 2707 return f"{this} {alias}" 2708 2709 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2710 return f"{this} ({args})" 2711 2712 def partition_by_sql(self, expression: exp.Window | exp.MatchRecognize) -> str: 2713 partition = self.expressions(expression, key="partition_by", flat=True) 2714 return f"PARTITION BY {partition}" if partition else "" 2715 2716 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2717 kind = self.sql(expression, "kind") 2718 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2719 end = ( 2720 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2721 or "CURRENT ROW" 2722 ) 2723 return f"{kind} BETWEEN {start} AND {end}" 2724 2725 def withingroup_sql(self, expression: exp.WithinGroup) -> str: 2726 this = self.sql(expression, "this") 2727 expression_sql = self.sql(expression, "expression")[1:] # order has a leading space 2728 return f"{this} WITHIN GROUP ({expression_sql})" 2729 2730 def between_sql(self, expression: exp.Between) -> str: 2731 this = self.sql(expression, "this") 2732 low = self.sql(expression, "low") 2733 high = self.sql(expression, "high") 2734 return f"{this} BETWEEN {low} AND {high}" 2735 2736 def bracket_offset_expressions( 2737 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2738 ) -> t.List[exp.Expression]: 2739 return apply_index_offset( 2740 expression.this, 2741 expression.expressions, 2742 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2743 ) 2744 2745 def bracket_sql(self, expression: exp.Bracket) -> str: 2746 expressions = self.bracket_offset_expressions(expression) 2747 expressions_sql = ", ".join(self.sql(e) for e in expressions) 2748 return f"{self.sql(expression, 'this')}[{expressions_sql}]" 2749 2750 def all_sql(self, expression: exp.All) -> str: 2751 return f"ALL {self.wrap(expression)}" 2752 2753 def any_sql(self, expression: exp.Any) -> str: 2754 this = self.sql(expression, "this") 2755 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2756 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2757 this = self.wrap(this) 2758 return f"ANY{this}" 2759 return f"ANY {this}" 2760 2761 def exists_sql(self, expression: exp.Exists) -> str: 2762 return f"EXISTS{self.wrap(expression)}" 2763 2764 def case_sql(self, expression: exp.Case) -> str: 2765 this = self.sql(expression, "this") 2766 statements = [f"CASE {this}" if this else "CASE"] 2767 2768 for e in expression.args["ifs"]: 2769 statements.append(f"WHEN {self.sql(e, 'this')}") 2770 statements.append(f"THEN {self.sql(e, 'true')}") 2771 2772 default = self.sql(expression, "default") 2773 2774 if default: 2775 statements.append(f"ELSE {default}") 2776 2777 statements.append("END") 2778 2779 if self.pretty and self.too_wide(statements): 2780 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2781 2782 return " ".join(statements) 2783 2784 def constraint_sql(self, expression: exp.Constraint) -> str: 2785 this = self.sql(expression, "this") 2786 expressions = self.expressions(expression, flat=True) 2787 return f"CONSTRAINT {this} {expressions}" 2788 2789 def nextvaluefor_sql(self, expression: exp.NextValueFor) -> str: 2790 order = expression.args.get("order") 2791 order = f" OVER ({self.order_sql(order, flat=True)})" if order else "" 2792 return f"NEXT VALUE FOR {self.sql(expression, 'this')}{order}" 2793 2794 def extract_sql(self, expression: exp.Extract) -> str: 2795 this = self.sql(expression, "this") if self.EXTRACT_ALLOWS_QUOTES else expression.this.name 2796 expression_sql = self.sql(expression, "expression") 2797 return f"EXTRACT({this} FROM {expression_sql})" 2798 2799 def trim_sql(self, expression: exp.Trim) -> str: 2800 trim_type = self.sql(expression, "position") 2801 2802 if trim_type == "LEADING": 2803 func_name = "LTRIM" 2804 elif trim_type == "TRAILING": 2805 func_name = "RTRIM" 2806 else: 2807 func_name = "TRIM" 2808 2809 return self.func(func_name, expression.this, expression.expression) 2810 2811 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2812 args = expression.expressions 2813 if isinstance(expression, exp.ConcatWs): 2814 args = args[1:] # Skip the delimiter 2815 2816 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2817 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2818 2819 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2820 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2821 2822 return args 2823 2824 def concat_sql(self, expression: exp.Concat) -> str: 2825 expressions = self.convert_concat_args(expression) 2826 2827 # Some dialects don't allow a single-argument CONCAT call 2828 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2829 return self.sql(expressions[0]) 2830 2831 return self.func("CONCAT", *expressions) 2832 2833 def concatws_sql(self, expression: exp.ConcatWs) -> str: 2834 return self.func( 2835 "CONCAT_WS", seq_get(expression.expressions, 0), *self.convert_concat_args(expression) 2836 ) 2837 2838 def check_sql(self, expression: exp.Check) -> str: 2839 this = self.sql(expression, key="this") 2840 return f"CHECK ({this})" 2841 2842 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2843 expressions = self.expressions(expression, flat=True) 2844 expressions = f" ({expressions})" if expressions else "" 2845 reference = self.sql(expression, "reference") 2846 reference = f" {reference}" if reference else "" 2847 delete = self.sql(expression, "delete") 2848 delete = f" ON DELETE {delete}" if delete else "" 2849 update = self.sql(expression, "update") 2850 update = f" ON UPDATE {update}" if update else "" 2851 return f"FOREIGN KEY{expressions}{reference}{delete}{update}" 2852 2853 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2854 expressions = self.expressions(expression, flat=True) 2855 options = self.expressions(expression, key="options", flat=True, sep=" ") 2856 options = f" {options}" if options else "" 2857 return f"PRIMARY KEY ({expressions}){options}" 2858 2859 def if_sql(self, expression: exp.If) -> str: 2860 return self.case_sql(exp.Case(ifs=[expression], default=expression.args.get("false"))) 2861 2862 def matchagainst_sql(self, expression: exp.MatchAgainst) -> str: 2863 modifier = expression.args.get("modifier") 2864 modifier = f" {modifier}" if modifier else "" 2865 return f"{self.func('MATCH', *expression.expressions)} AGAINST({self.sql(expression, 'this')}{modifier})" 2866 2867 def jsonkeyvalue_sql(self, expression: exp.JSONKeyValue) -> str: 2868 return f"{self.sql(expression, 'this')}{self.JSON_KEY_VALUE_PAIR_SEP} {self.sql(expression, 'expression')}" 2869 2870 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2871 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2872 2873 if expression.args.get("escape"): 2874 path = self.escape_str(path) 2875 2876 if self.QUOTE_JSON_PATH: 2877 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2878 2879 return path 2880 2881 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2882 if isinstance(expression, exp.JSONPathPart): 2883 transform = self.TRANSFORMS.get(expression.__class__) 2884 if not callable(transform): 2885 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2886 return "" 2887 2888 return transform(self, expression) 2889 2890 if isinstance(expression, int): 2891 return str(expression) 2892 2893 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2894 escaped = expression.replace("'", "\\'") 2895 escaped = f"\\'{expression}\\'" 2896 else: 2897 escaped = expression.replace('"', '\\"') 2898 escaped = f'"{escaped}"' 2899 2900 return escaped 2901 2902 def formatjson_sql(self, expression: exp.FormatJson) -> str: 2903 return f"{self.sql(expression, 'this')} FORMAT JSON" 2904 2905 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2906 null_handling = expression.args.get("null_handling") 2907 null_handling = f" {null_handling}" if null_handling else "" 2908 2909 unique_keys = expression.args.get("unique_keys") 2910 if unique_keys is not None: 2911 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2912 else: 2913 unique_keys = "" 2914 2915 return_type = self.sql(expression, "return_type") 2916 return_type = f" RETURNING {return_type}" if return_type else "" 2917 encoding = self.sql(expression, "encoding") 2918 encoding = f" ENCODING {encoding}" if encoding else "" 2919 2920 return self.func( 2921 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2922 *expression.expressions, 2923 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2924 ) 2925 2926 def jsonobjectagg_sql(self, expression: exp.JSONObjectAgg) -> str: 2927 return self.jsonobject_sql(expression) 2928 2929 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2930 null_handling = expression.args.get("null_handling") 2931 null_handling = f" {null_handling}" if null_handling else "" 2932 return_type = self.sql(expression, "return_type") 2933 return_type = f" RETURNING {return_type}" if return_type else "" 2934 strict = " STRICT" if expression.args.get("strict") else "" 2935 return self.func( 2936 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2937 ) 2938 2939 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2940 this = self.sql(expression, "this") 2941 order = self.sql(expression, "order") 2942 null_handling = expression.args.get("null_handling") 2943 null_handling = f" {null_handling}" if null_handling else "" 2944 return_type = self.sql(expression, "return_type") 2945 return_type = f" RETURNING {return_type}" if return_type else "" 2946 strict = " STRICT" if expression.args.get("strict") else "" 2947 return self.func( 2948 "JSON_ARRAYAGG", 2949 this, 2950 suffix=f"{order}{null_handling}{return_type}{strict})", 2951 ) 2952 2953 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2954 path = self.sql(expression, "path") 2955 path = f" PATH {path}" if path else "" 2956 nested_schema = self.sql(expression, "nested_schema") 2957 2958 if nested_schema: 2959 return f"NESTED{path} {nested_schema}" 2960 2961 this = self.sql(expression, "this") 2962 kind = self.sql(expression, "kind") 2963 kind = f" {kind}" if kind else "" 2964 return f"{this}{kind}{path}" 2965 2966 def jsonschema_sql(self, expression: exp.JSONSchema) -> str: 2967 return self.func("COLUMNS", *expression.expressions) 2968 2969 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2970 this = self.sql(expression, "this") 2971 path = self.sql(expression, "path") 2972 path = f", {path}" if path else "" 2973 error_handling = expression.args.get("error_handling") 2974 error_handling = f" {error_handling}" if error_handling else "" 2975 empty_handling = expression.args.get("empty_handling") 2976 empty_handling = f" {empty_handling}" if empty_handling else "" 2977 schema = self.sql(expression, "schema") 2978 return self.func( 2979 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2980 ) 2981 2982 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2983 this = self.sql(expression, "this") 2984 kind = self.sql(expression, "kind") 2985 path = self.sql(expression, "path") 2986 path = f" {path}" if path else "" 2987 as_json = " AS JSON" if expression.args.get("as_json") else "" 2988 return f"{this} {kind}{path}{as_json}" 2989 2990 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2991 this = self.sql(expression, "this") 2992 path = self.sql(expression, "path") 2993 path = f", {path}" if path else "" 2994 expressions = self.expressions(expression) 2995 with_ = ( 2996 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2997 if expressions 2998 else "" 2999 ) 3000 return f"OPENJSON({this}{path}){with_}" 3001 3002 def in_sql(self, expression: exp.In) -> str: 3003 query = expression.args.get("query") 3004 unnest = expression.args.get("unnest") 3005 field = expression.args.get("field") 3006 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3007 3008 if query: 3009 in_sql = self.sql(query) 3010 elif unnest: 3011 in_sql = self.in_unnest_op(unnest) 3012 elif field: 3013 in_sql = self.sql(field) 3014 else: 3015 in_sql = f"({self.expressions(expression, flat=True)})" 3016 3017 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}" 3018 3019 def in_unnest_op(self, unnest: exp.Unnest) -> str: 3020 return f"(SELECT {self.sql(unnest)})" 3021 3022 def interval_sql(self, expression: exp.Interval) -> str: 3023 unit = self.sql(expression, "unit") 3024 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3025 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3026 unit = f" {unit}" if unit else "" 3027 3028 if self.SINGLE_STRING_INTERVAL: 3029 this = expression.this.name if expression.this else "" 3030 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3031 3032 this = self.sql(expression, "this") 3033 if this: 3034 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3035 this = f" {this}" if unwrapped else f" ({this})" 3036 3037 return f"INTERVAL{this}{unit}" 3038 3039 def return_sql(self, expression: exp.Return) -> str: 3040 return f"RETURN {self.sql(expression, 'this')}" 3041 3042 def reference_sql(self, expression: exp.Reference) -> str: 3043 this = self.sql(expression, "this") 3044 expressions = self.expressions(expression, flat=True) 3045 expressions = f"({expressions})" if expressions else "" 3046 options = self.expressions(expression, key="options", flat=True, sep=" ") 3047 options = f" {options}" if options else "" 3048 return f"REFERENCES {this}{expressions}{options}" 3049 3050 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3051 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3052 parent = expression.parent 3053 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3054 return self.func( 3055 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3056 ) 3057 3058 def paren_sql(self, expression: exp.Paren) -> str: 3059 sql = self.seg(self.indent(self.sql(expression, "this")), sep="") 3060 return f"({sql}{self.seg(')', sep='')}" 3061 3062 def neg_sql(self, expression: exp.Neg) -> str: 3063 # This makes sure we don't convert "- - 5" to "--5", which is a comment 3064 this_sql = self.sql(expression, "this") 3065 sep = " " if this_sql[0] == "-" else "" 3066 return f"-{sep}{this_sql}" 3067 3068 def not_sql(self, expression: exp.Not) -> str: 3069 return f"NOT {self.sql(expression, 'this')}" 3070 3071 def alias_sql(self, expression: exp.Alias) -> str: 3072 alias = self.sql(expression, "alias") 3073 alias = f" AS {alias}" if alias else "" 3074 return f"{self.sql(expression, 'this')}{alias}" 3075 3076 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3077 alias = expression.args["alias"] 3078 3079 identifier_alias = isinstance(alias, exp.Identifier) 3080 literal_alias = isinstance(alias, exp.Literal) 3081 3082 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3083 alias.replace(exp.Literal.string(alias.output_name)) 3084 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3085 alias.replace(exp.to_identifier(alias.output_name)) 3086 3087 return self.alias_sql(expression) 3088 3089 def aliases_sql(self, expression: exp.Aliases) -> str: 3090 return f"{self.sql(expression, 'this')} AS ({self.expressions(expression, flat=True)})" 3091 3092 def atindex_sql(self, expression: exp.AtTimeZone) -> str: 3093 this = self.sql(expression, "this") 3094 index = self.sql(expression, "expression") 3095 return f"{this} AT {index}" 3096 3097 def attimezone_sql(self, expression: exp.AtTimeZone) -> str: 3098 this = self.sql(expression, "this") 3099 zone = self.sql(expression, "zone") 3100 return f"{this} AT TIME ZONE {zone}" 3101 3102 def fromtimezone_sql(self, expression: exp.FromTimeZone) -> str: 3103 this = self.sql(expression, "this") 3104 zone = self.sql(expression, "zone") 3105 return f"{this} AT TIME ZONE {zone} AT TIME ZONE 'UTC'" 3106 3107 def add_sql(self, expression: exp.Add) -> str: 3108 return self.binary(expression, "+") 3109 3110 def and_sql( 3111 self, expression: exp.And, stack: t.Optional[t.List[str | exp.Expression]] = None 3112 ) -> str: 3113 return self.connector_sql(expression, "AND", stack) 3114 3115 def or_sql( 3116 self, expression: exp.Or, stack: t.Optional[t.List[str | exp.Expression]] = None 3117 ) -> str: 3118 return self.connector_sql(expression, "OR", stack) 3119 3120 def xor_sql( 3121 self, expression: exp.Xor, stack: t.Optional[t.List[str | exp.Expression]] = None 3122 ) -> str: 3123 return self.connector_sql(expression, "XOR", stack) 3124 3125 def connector_sql( 3126 self, 3127 expression: exp.Connector, 3128 op: str, 3129 stack: t.Optional[t.List[str | exp.Expression]] = None, 3130 ) -> str: 3131 if stack is not None: 3132 if expression.expressions: 3133 stack.append(self.expressions(expression, sep=f" {op} ")) 3134 else: 3135 stack.append(expression.right) 3136 if expression.comments and self.comments: 3137 for comment in expression.comments: 3138 if comment: 3139 op += f" /*{self.pad_comment(comment)}*/" 3140 stack.extend((op, expression.left)) 3141 return op 3142 3143 stack = [expression] 3144 sqls: t.List[str] = [] 3145 ops = set() 3146 3147 while stack: 3148 node = stack.pop() 3149 if isinstance(node, exp.Connector): 3150 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3151 else: 3152 sql = self.sql(node) 3153 if sqls and sqls[-1] in ops: 3154 sqls[-1] += f" {sql}" 3155 else: 3156 sqls.append(sql) 3157 3158 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3159 return sep.join(sqls) 3160 3161 def bitwiseand_sql(self, expression: exp.BitwiseAnd) -> str: 3162 return self.binary(expression, "&") 3163 3164 def bitwiseleftshift_sql(self, expression: exp.BitwiseLeftShift) -> str: 3165 return self.binary(expression, "<<") 3166 3167 def bitwisenot_sql(self, expression: exp.BitwiseNot) -> str: 3168 return f"~{self.sql(expression, 'this')}" 3169 3170 def bitwiseor_sql(self, expression: exp.BitwiseOr) -> str: 3171 return self.binary(expression, "|") 3172 3173 def bitwiserightshift_sql(self, expression: exp.BitwiseRightShift) -> str: 3174 return self.binary(expression, ">>") 3175 3176 def bitwisexor_sql(self, expression: exp.BitwiseXor) -> str: 3177 return self.binary(expression, "^") 3178 3179 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3180 format_sql = self.sql(expression, "format") 3181 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3182 to_sql = self.sql(expression, "to") 3183 to_sql = f" {to_sql}" if to_sql else "" 3184 action = self.sql(expression, "action") 3185 action = f" {action}" if action else "" 3186 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})" 3187 3188 def currentdate_sql(self, expression: exp.CurrentDate) -> str: 3189 zone = self.sql(expression, "this") 3190 return f"CURRENT_DATE({zone})" if zone else "CURRENT_DATE" 3191 3192 def collate_sql(self, expression: exp.Collate) -> str: 3193 if self.COLLATE_IS_FUNC: 3194 return self.function_fallback_sql(expression) 3195 return self.binary(expression, "COLLATE") 3196 3197 def command_sql(self, expression: exp.Command) -> str: 3198 return f"{self.sql(expression, 'this')} {expression.text('expression').strip()}" 3199 3200 def comment_sql(self, expression: exp.Comment) -> str: 3201 this = self.sql(expression, "this") 3202 kind = expression.args["kind"] 3203 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3204 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3205 expression_sql = self.sql(expression, "expression") 3206 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}" 3207 3208 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3209 this = self.sql(expression, "this") 3210 delete = " DELETE" if expression.args.get("delete") else "" 3211 recompress = self.sql(expression, "recompress") 3212 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3213 to_disk = self.sql(expression, "to_disk") 3214 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3215 to_volume = self.sql(expression, "to_volume") 3216 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3217 return f"{this}{delete}{recompress}{to_disk}{to_volume}" 3218 3219 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3220 where = self.sql(expression, "where") 3221 group = self.sql(expression, "group") 3222 aggregates = self.expressions(expression, key="aggregates") 3223 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3224 3225 if not (where or group or aggregates) and len(expression.expressions) == 1: 3226 return f"TTL {self.expressions(expression, flat=True)}" 3227 3228 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}" 3229 3230 def transaction_sql(self, expression: exp.Transaction) -> str: 3231 return "BEGIN" 3232 3233 def commit_sql(self, expression: exp.Commit) -> str: 3234 chain = expression.args.get("chain") 3235 if chain is not None: 3236 chain = " AND CHAIN" if chain else " AND NO CHAIN" 3237 3238 return f"COMMIT{chain or ''}" 3239 3240 def rollback_sql(self, expression: exp.Rollback) -> str: 3241 savepoint = expression.args.get("savepoint") 3242 savepoint = f" TO {savepoint}" if savepoint else "" 3243 return f"ROLLBACK{savepoint}" 3244 3245 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3246 this = self.sql(expression, "this") 3247 3248 dtype = self.sql(expression, "dtype") 3249 if dtype: 3250 collate = self.sql(expression, "collate") 3251 collate = f" COLLATE {collate}" if collate else "" 3252 using = self.sql(expression, "using") 3253 using = f" USING {using}" if using else "" 3254 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3255 3256 default = self.sql(expression, "default") 3257 if default: 3258 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3259 3260 comment = self.sql(expression, "comment") 3261 if comment: 3262 return f"ALTER COLUMN {this} COMMENT {comment}" 3263 3264 allow_null = expression.args.get("allow_null") 3265 drop = expression.args.get("drop") 3266 3267 if not drop and not allow_null: 3268 self.unsupported("Unsupported ALTER COLUMN syntax") 3269 3270 if allow_null is not None: 3271 keyword = "DROP" if drop else "SET" 3272 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3273 3274 return f"ALTER COLUMN {this} DROP DEFAULT" 3275 3276 def alterdiststyle_sql(self, expression: exp.AlterDistStyle) -> str: 3277 this = self.sql(expression, "this") 3278 if not isinstance(expression.this, exp.Var): 3279 this = f"KEY DISTKEY {this}" 3280 return f"ALTER DISTSTYLE {this}" 3281 3282 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3283 compound = " COMPOUND" if expression.args.get("compound") else "" 3284 this = self.sql(expression, "this") 3285 expressions = self.expressions(expression, flat=True) 3286 expressions = f"({expressions})" if expressions else "" 3287 return f"ALTER{compound} SORTKEY {this or expressions}" 3288 3289 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3290 if not self.RENAME_TABLE_WITH_DB: 3291 # Remove db from tables 3292 expression = expression.transform( 3293 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3294 ).assert_is(exp.AlterRename) 3295 this = self.sql(expression, "this") 3296 return f"RENAME TO {this}" 3297 3298 def renamecolumn_sql(self, expression: exp.RenameColumn) -> str: 3299 exists = " IF EXISTS" if expression.args.get("exists") else "" 3300 old_column = self.sql(expression, "this") 3301 new_column = self.sql(expression, "to") 3302 return f"RENAME COLUMN{exists} {old_column} TO {new_column}" 3303 3304 def alterset_sql(self, expression: exp.AlterSet) -> str: 3305 exprs = self.expressions(expression, flat=True) 3306 return f"SET {exprs}" 3307 3308 def alter_sql(self, expression: exp.Alter) -> str: 3309 actions = expression.args["actions"] 3310 3311 if isinstance(actions[0], exp.ColumnDef): 3312 actions = self.add_column_sql(expression) 3313 elif isinstance(actions[0], exp.Schema): 3314 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3315 elif isinstance(actions[0], exp.Delete): 3316 actions = self.expressions(expression, key="actions", flat=True) 3317 elif isinstance(actions[0], exp.Query): 3318 actions = "AS " + self.expressions(expression, key="actions") 3319 else: 3320 actions = self.expressions(expression, key="actions", flat=True) 3321 3322 exists = " IF EXISTS" if expression.args.get("exists") else "" 3323 on_cluster = self.sql(expression, "cluster") 3324 on_cluster = f" {on_cluster}" if on_cluster else "" 3325 only = " ONLY" if expression.args.get("only") else "" 3326 options = self.expressions(expression, key="options") 3327 options = f", {options}" if options else "" 3328 kind = self.sql(expression, "kind") 3329 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3330 3331 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}" 3332 3333 def add_column_sql(self, expression: exp.Alter) -> str: 3334 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3335 return self.expressions( 3336 expression, 3337 key="actions", 3338 prefix="ADD COLUMN ", 3339 skip_first=True, 3340 ) 3341 return f"ADD {self.expressions(expression, key='actions', flat=True)}" 3342 3343 def droppartition_sql(self, expression: exp.DropPartition) -> str: 3344 expressions = self.expressions(expression) 3345 exists = " IF EXISTS " if expression.args.get("exists") else " " 3346 return f"DROP{exists}{expressions}" 3347 3348 def addconstraint_sql(self, expression: exp.AddConstraint) -> str: 3349 return f"ADD {self.expressions(expression)}" 3350 3351 def distinct_sql(self, expression: exp.Distinct) -> str: 3352 this = self.expressions(expression, flat=True) 3353 3354 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3355 case = exp.case() 3356 for arg in expression.expressions: 3357 case = case.when(arg.is_(exp.null()), exp.null()) 3358 this = self.sql(case.else_(f"({this})")) 3359 3360 this = f" {this}" if this else "" 3361 3362 on = self.sql(expression, "on") 3363 on = f" ON {on}" if on else "" 3364 return f"DISTINCT{this}{on}" 3365 3366 def ignorenulls_sql(self, expression: exp.IgnoreNulls) -> str: 3367 return self._embed_ignore_nulls(expression, "IGNORE NULLS") 3368 3369 def respectnulls_sql(self, expression: exp.RespectNulls) -> str: 3370 return self._embed_ignore_nulls(expression, "RESPECT NULLS") 3371 3372 def havingmax_sql(self, expression: exp.HavingMax) -> str: 3373 this_sql = self.sql(expression, "this") 3374 expression_sql = self.sql(expression, "expression") 3375 kind = "MAX" if expression.args.get("max") else "MIN" 3376 return f"{this_sql} HAVING {kind} {expression_sql}" 3377 3378 def intdiv_sql(self, expression: exp.IntDiv) -> str: 3379 return self.sql( 3380 exp.Cast( 3381 this=exp.Div(this=expression.this, expression=expression.expression), 3382 to=exp.DataType(this=exp.DataType.Type.INT), 3383 ) 3384 ) 3385 3386 def dpipe_sql(self, expression: exp.DPipe) -> str: 3387 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 3388 return self.func( 3389 "CONCAT", *(exp.cast(e, exp.DataType.Type.TEXT) for e in expression.flatten()) 3390 ) 3391 return self.binary(expression, "||") 3392 3393 def div_sql(self, expression: exp.Div) -> str: 3394 l, r = expression.left, expression.right 3395 3396 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3397 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3398 3399 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3400 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3401 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3402 3403 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3404 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3405 return self.sql( 3406 exp.cast( 3407 l / r, 3408 to=exp.DataType.Type.BIGINT, 3409 ) 3410 ) 3411 3412 return self.binary(expression, "/") 3413 3414 def overlaps_sql(self, expression: exp.Overlaps) -> str: 3415 return self.binary(expression, "OVERLAPS") 3416 3417 def distance_sql(self, expression: exp.Distance) -> str: 3418 return self.binary(expression, "<->") 3419 3420 def dot_sql(self, expression: exp.Dot) -> str: 3421 return f"{self.sql(expression, 'this')}.{self.sql(expression, 'expression')}" 3422 3423 def eq_sql(self, expression: exp.EQ) -> str: 3424 return self.binary(expression, "=") 3425 3426 def propertyeq_sql(self, expression: exp.PropertyEQ) -> str: 3427 return self.binary(expression, ":=") 3428 3429 def escape_sql(self, expression: exp.Escape) -> str: 3430 return self.binary(expression, "ESCAPE") 3431 3432 def glob_sql(self, expression: exp.Glob) -> str: 3433 return self.binary(expression, "GLOB") 3434 3435 def gt_sql(self, expression: exp.GT) -> str: 3436 return self.binary(expression, ">") 3437 3438 def gte_sql(self, expression: exp.GTE) -> str: 3439 return self.binary(expression, ">=") 3440 3441 def ilike_sql(self, expression: exp.ILike) -> str: 3442 return self.binary(expression, "ILIKE") 3443 3444 def ilikeany_sql(self, expression: exp.ILikeAny) -> str: 3445 return self.binary(expression, "ILIKE ANY") 3446 3447 def is_sql(self, expression: exp.Is) -> str: 3448 if not self.IS_BOOL_ALLOWED and isinstance(expression.expression, exp.Boolean): 3449 return self.sql( 3450 expression.this if expression.expression.this else exp.not_(expression.this) 3451 ) 3452 return self.binary(expression, "IS") 3453 3454 def like_sql(self, expression: exp.Like) -> str: 3455 return self.binary(expression, "LIKE") 3456 3457 def likeany_sql(self, expression: exp.LikeAny) -> str: 3458 return self.binary(expression, "LIKE ANY") 3459 3460 def similarto_sql(self, expression: exp.SimilarTo) -> str: 3461 return self.binary(expression, "SIMILAR TO") 3462 3463 def lt_sql(self, expression: exp.LT) -> str: 3464 return self.binary(expression, "<") 3465 3466 def lte_sql(self, expression: exp.LTE) -> str: 3467 return self.binary(expression, "<=") 3468 3469 def mod_sql(self, expression: exp.Mod) -> str: 3470 return self.binary(expression, "%") 3471 3472 def mul_sql(self, expression: exp.Mul) -> str: 3473 return self.binary(expression, "*") 3474 3475 def neq_sql(self, expression: exp.NEQ) -> str: 3476 return self.binary(expression, "<>") 3477 3478 def nullsafeeq_sql(self, expression: exp.NullSafeEQ) -> str: 3479 return self.binary(expression, "IS NOT DISTINCT FROM") 3480 3481 def nullsafeneq_sql(self, expression: exp.NullSafeNEQ) -> str: 3482 return self.binary(expression, "IS DISTINCT FROM") 3483 3484 def slice_sql(self, expression: exp.Slice) -> str: 3485 return self.binary(expression, ":") 3486 3487 def sub_sql(self, expression: exp.Sub) -> str: 3488 return self.binary(expression, "-") 3489 3490 def trycast_sql(self, expression: exp.TryCast) -> str: 3491 return self.cast_sql(expression, safe_prefix="TRY_") 3492 3493 def try_sql(self, expression: exp.Try) -> str: 3494 if not self.TRY_SUPPORTED: 3495 self.unsupported("Unsupported TRY function") 3496 return self.sql(expression, "this") 3497 3498 return self.func("TRY", expression.this) 3499 3500 def log_sql(self, expression: exp.Log) -> str: 3501 this = expression.this 3502 expr = expression.expression 3503 3504 if self.dialect.LOG_BASE_FIRST is False: 3505 this, expr = expr, this 3506 elif self.dialect.LOG_BASE_FIRST is None and expr: 3507 if this.name in ("2", "10"): 3508 return self.func(f"LOG{this.name}", expr) 3509 3510 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3511 3512 return self.func("LOG", this, expr) 3513 3514 def use_sql(self, expression: exp.Use) -> str: 3515 kind = self.sql(expression, "kind") 3516 kind = f" {kind}" if kind else "" 3517 this = self.sql(expression, "this") 3518 this = f" {this}" if this else "" 3519 return f"USE{kind}{this}" 3520 3521 def binary(self, expression: exp.Binary, op: str) -> str: 3522 sqls: t.List[str] = [] 3523 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3524 binary_type = type(expression) 3525 3526 while stack: 3527 node = stack.pop() 3528 3529 if type(node) is binary_type: 3530 op_func = node.args.get("operator") 3531 if op_func: 3532 op = f"OPERATOR({self.sql(op_func)})" 3533 3534 stack.append(node.right) 3535 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3536 stack.append(node.left) 3537 else: 3538 sqls.append(self.sql(node)) 3539 3540 return "".join(sqls) 3541 3542 def ceil_floor(self, expression: exp.Ceil | exp.Floor) -> str: 3543 to_clause = self.sql(expression, "to") 3544 if to_clause: 3545 return f"{expression.sql_name()}({self.sql(expression, 'this')} TO {to_clause})" 3546 3547 return self.function_fallback_sql(expression) 3548 3549 def function_fallback_sql(self, expression: exp.Func) -> str: 3550 args = [] 3551 3552 for key in expression.arg_types: 3553 arg_value = expression.args.get(key) 3554 3555 if isinstance(arg_value, list): 3556 for value in arg_value: 3557 args.append(value) 3558 elif arg_value is not None: 3559 args.append(arg_value) 3560 3561 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3562 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3563 else: 3564 name = expression.sql_name() 3565 3566 return self.func(name, *args) 3567 3568 def func( 3569 self, 3570 name: str, 3571 *args: t.Optional[exp.Expression | str], 3572 prefix: str = "(", 3573 suffix: str = ")", 3574 normalize: bool = True, 3575 ) -> str: 3576 name = self.normalize_func(name) if normalize else name 3577 return f"{name}{prefix}{self.format_args(*args)}{suffix}" 3578 3579 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3580 arg_sqls = tuple( 3581 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3582 ) 3583 if self.pretty and self.too_wide(arg_sqls): 3584 return self.indent( 3585 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3586 ) 3587 return sep.join(arg_sqls) 3588 3589 def too_wide(self, args: t.Iterable) -> bool: 3590 return sum(len(arg) for arg in args) > self.max_text_width 3591 3592 def format_time( 3593 self, 3594 expression: exp.Expression, 3595 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3596 inverse_time_trie: t.Optional[t.Dict] = None, 3597 ) -> t.Optional[str]: 3598 return format_time( 3599 self.sql(expression, "format"), 3600 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3601 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3602 ) 3603 3604 def expressions( 3605 self, 3606 expression: t.Optional[exp.Expression] = None, 3607 key: t.Optional[str] = None, 3608 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3609 flat: bool = False, 3610 indent: bool = True, 3611 skip_first: bool = False, 3612 skip_last: bool = False, 3613 sep: str = ", ", 3614 prefix: str = "", 3615 dynamic: bool = False, 3616 new_line: bool = False, 3617 ) -> str: 3618 expressions = expression.args.get(key or "expressions") if expression else sqls 3619 3620 if not expressions: 3621 return "" 3622 3623 if flat: 3624 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3625 3626 num_sqls = len(expressions) 3627 result_sqls = [] 3628 3629 for i, e in enumerate(expressions): 3630 sql = self.sql(e, comment=False) 3631 if not sql: 3632 continue 3633 3634 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3635 3636 if self.pretty: 3637 if self.leading_comma: 3638 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3639 else: 3640 result_sqls.append( 3641 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3642 ) 3643 else: 3644 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3645 3646 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3647 if new_line: 3648 result_sqls.insert(0, "") 3649 result_sqls.append("") 3650 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3651 else: 3652 result_sql = "".join(result_sqls) 3653 3654 return ( 3655 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3656 if indent 3657 else result_sql 3658 ) 3659 3660 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3661 flat = flat or isinstance(expression.parent, exp.Properties) 3662 expressions_sql = self.expressions(expression, flat=flat) 3663 if flat: 3664 return f"{op} {expressions_sql}" 3665 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}" 3666 3667 def naked_property(self, expression: exp.Property) -> str: 3668 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3669 if not property_name: 3670 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3671 return f"{property_name} {self.sql(expression, 'this')}" 3672 3673 def tag_sql(self, expression: exp.Tag) -> str: 3674 return f"{expression.args.get('prefix')}{self.sql(expression.this)}{expression.args.get('postfix')}" 3675 3676 def token_sql(self, token_type: TokenType) -> str: 3677 return self.TOKEN_MAPPING.get(token_type, token_type.name) 3678 3679 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3680 this = self.sql(expression, "this") 3681 expressions = self.no_identify(self.expressions, expression) 3682 expressions = ( 3683 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3684 ) 3685 return f"{this}{expressions}" if expressions.strip() != "" else this 3686 3687 def joinhint_sql(self, expression: exp.JoinHint) -> str: 3688 this = self.sql(expression, "this") 3689 expressions = self.expressions(expression, flat=True) 3690 return f"{this}({expressions})" 3691 3692 def kwarg_sql(self, expression: exp.Kwarg) -> str: 3693 return self.binary(expression, "=>") 3694 3695 def when_sql(self, expression: exp.When) -> str: 3696 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3697 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3698 condition = self.sql(expression, "condition") 3699 condition = f" AND {condition}" if condition else "" 3700 3701 then_expression = expression.args.get("then") 3702 if isinstance(then_expression, exp.Insert): 3703 this = self.sql(then_expression, "this") 3704 this = f"INSERT {this}" if this else "INSERT" 3705 then = self.sql(then_expression, "expression") 3706 then = f"{this} VALUES {then}" if then else this 3707 elif isinstance(then_expression, exp.Update): 3708 if isinstance(then_expression.args.get("expressions"), exp.Star): 3709 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3710 else: 3711 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3712 else: 3713 then = self.sql(then_expression) 3714 return f"WHEN {matched}{source}{condition} THEN {then}" 3715 3716 def whens_sql(self, expression: exp.Whens) -> str: 3717 return self.expressions(expression, sep=" ", indent=False) 3718 3719 def merge_sql(self, expression: exp.Merge) -> str: 3720 table = expression.this 3721 table_alias = "" 3722 3723 hints = table.args.get("hints") 3724 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3725 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3726 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3727 3728 this = self.sql(table) 3729 using = f"USING {self.sql(expression, 'using')}" 3730 on = f"ON {self.sql(expression, 'on')}" 3731 whens = self.sql(expression, "whens") 3732 3733 returning = self.sql(expression, "returning") 3734 if returning: 3735 whens = f"{whens}{returning}" 3736 3737 sep = self.sep() 3738 3739 return self.prepend_ctes( 3740 expression, 3741 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3742 ) 3743 3744 @unsupported_args("format") 3745 def tochar_sql(self, expression: exp.ToChar) -> str: 3746 return self.sql(exp.cast(expression.this, exp.DataType.Type.TEXT)) 3747 3748 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3749 if not self.SUPPORTS_TO_NUMBER: 3750 self.unsupported("Unsupported TO_NUMBER function") 3751 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3752 3753 fmt = expression.args.get("format") 3754 if not fmt: 3755 self.unsupported("Conversion format is required for TO_NUMBER") 3756 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3757 3758 return self.func("TO_NUMBER", expression.this, fmt) 3759 3760 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3761 this = self.sql(expression, "this") 3762 kind = self.sql(expression, "kind") 3763 settings_sql = self.expressions(expression, key="settings", sep=" ") 3764 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3765 return f"{this}({kind}{args})" 3766 3767 def dictrange_sql(self, expression: exp.DictRange) -> str: 3768 this = self.sql(expression, "this") 3769 max = self.sql(expression, "max") 3770 min = self.sql(expression, "min") 3771 return f"{this}(MIN {min} MAX {max})" 3772 3773 def dictsubproperty_sql(self, expression: exp.DictSubProperty) -> str: 3774 return f"{self.sql(expression, 'this')} {self.sql(expression, 'value')}" 3775 3776 def duplicatekeyproperty_sql(self, expression: exp.DuplicateKeyProperty) -> str: 3777 return f"DUPLICATE KEY ({self.expressions(expression, flat=True)})" 3778 3779 # https://docs.starrocks.io/docs/sql-reference/sql-statements/table_bucket_part_index/CREATE_TABLE/ 3780 def uniquekeyproperty_sql(self, expression: exp.UniqueKeyProperty) -> str: 3781 return f"UNIQUE KEY ({self.expressions(expression, flat=True)})" 3782 3783 # https://docs.starrocks.io/docs/sql-reference/sql-statements/data-definition/CREATE_TABLE/#distribution_desc 3784 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3785 expressions = self.expressions(expression, flat=True) 3786 expressions = f" {self.wrap(expressions)}" if expressions else "" 3787 buckets = self.sql(expression, "buckets") 3788 kind = self.sql(expression, "kind") 3789 buckets = f" BUCKETS {buckets}" if buckets else "" 3790 order = self.sql(expression, "order") 3791 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}" 3792 3793 def oncluster_sql(self, expression: exp.OnCluster) -> str: 3794 return "" 3795 3796 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3797 expressions = self.expressions(expression, key="expressions", flat=True) 3798 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3799 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3800 buckets = self.sql(expression, "buckets") 3801 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS" 3802 3803 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3804 this = self.sql(expression, "this") 3805 having = self.sql(expression, "having") 3806 3807 if having: 3808 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3809 3810 return self.func("ANY_VALUE", this) 3811 3812 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3813 transform = self.func("TRANSFORM", *expression.expressions) 3814 row_format_before = self.sql(expression, "row_format_before") 3815 row_format_before = f" {row_format_before}" if row_format_before else "" 3816 record_writer = self.sql(expression, "record_writer") 3817 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3818 using = f" USING {self.sql(expression, 'command_script')}" 3819 schema = self.sql(expression, "schema") 3820 schema = f" AS {schema}" if schema else "" 3821 row_format_after = self.sql(expression, "row_format_after") 3822 row_format_after = f" {row_format_after}" if row_format_after else "" 3823 record_reader = self.sql(expression, "record_reader") 3824 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3825 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}" 3826 3827 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3828 key_block_size = self.sql(expression, "key_block_size") 3829 if key_block_size: 3830 return f"KEY_BLOCK_SIZE = {key_block_size}" 3831 3832 using = self.sql(expression, "using") 3833 if using: 3834 return f"USING {using}" 3835 3836 parser = self.sql(expression, "parser") 3837 if parser: 3838 return f"WITH PARSER {parser}" 3839 3840 comment = self.sql(expression, "comment") 3841 if comment: 3842 return f"COMMENT {comment}" 3843 3844 visible = expression.args.get("visible") 3845 if visible is not None: 3846 return "VISIBLE" if visible else "INVISIBLE" 3847 3848 engine_attr = self.sql(expression, "engine_attr") 3849 if engine_attr: 3850 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3851 3852 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3853 if secondary_engine_attr: 3854 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3855 3856 self.unsupported("Unsupported index constraint option.") 3857 return "" 3858 3859 def checkcolumnconstraint_sql(self, expression: exp.CheckColumnConstraint) -> str: 3860 enforced = " ENFORCED" if expression.args.get("enforced") else "" 3861 return f"CHECK ({self.sql(expression, 'this')}){enforced}" 3862 3863 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3864 kind = self.sql(expression, "kind") 3865 kind = f"{kind} INDEX" if kind else "INDEX" 3866 this = self.sql(expression, "this") 3867 this = f" {this}" if this else "" 3868 index_type = self.sql(expression, "index_type") 3869 index_type = f" USING {index_type}" if index_type else "" 3870 expressions = self.expressions(expression, flat=True) 3871 expressions = f" ({expressions})" if expressions else "" 3872 options = self.expressions(expression, key="options", sep=" ") 3873 options = f" {options}" if options else "" 3874 return f"{kind}{this}{index_type}{expressions}{options}" 3875 3876 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3877 if self.NVL2_SUPPORTED: 3878 return self.function_fallback_sql(expression) 3879 3880 case = exp.Case().when( 3881 expression.this.is_(exp.null()).not_(copy=False), 3882 expression.args["true"], 3883 copy=False, 3884 ) 3885 else_cond = expression.args.get("false") 3886 if else_cond: 3887 case.else_(else_cond, copy=False) 3888 3889 return self.sql(case) 3890 3891 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3892 this = self.sql(expression, "this") 3893 expr = self.sql(expression, "expression") 3894 iterator = self.sql(expression, "iterator") 3895 condition = self.sql(expression, "condition") 3896 condition = f" IF {condition}" if condition else "" 3897 return f"{this} FOR {expr} IN {iterator}{condition}" 3898 3899 def columnprefix_sql(self, expression: exp.ColumnPrefix) -> str: 3900 return f"{self.sql(expression, 'this')}({self.sql(expression, 'expression')})" 3901 3902 def opclass_sql(self, expression: exp.Opclass) -> str: 3903 return f"{self.sql(expression, 'this')} {self.sql(expression, 'expression')}" 3904 3905 def predict_sql(self, expression: exp.Predict) -> str: 3906 model = self.sql(expression, "this") 3907 model = f"MODEL {model}" 3908 table = self.sql(expression, "expression") 3909 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3910 parameters = self.sql(expression, "params_struct") 3911 return self.func("PREDICT", model, table, parameters or None) 3912 3913 def forin_sql(self, expression: exp.ForIn) -> str: 3914 this = self.sql(expression, "this") 3915 expression_sql = self.sql(expression, "expression") 3916 return f"FOR {this} DO {expression_sql}" 3917 3918 def refresh_sql(self, expression: exp.Refresh) -> str: 3919 this = self.sql(expression, "this") 3920 table = "" if isinstance(expression.this, exp.Literal) else "TABLE " 3921 return f"REFRESH {table}{this}" 3922 3923 def toarray_sql(self, expression: exp.ToArray) -> str: 3924 arg = expression.this 3925 if not arg.type: 3926 from sqlglot.optimizer.annotate_types import annotate_types 3927 3928 arg = annotate_types(arg) 3929 3930 if arg.is_type(exp.DataType.Type.ARRAY): 3931 return self.sql(arg) 3932 3933 cond_for_null = arg.is_(exp.null()) 3934 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False))) 3935 3936 def tsordstotime_sql(self, expression: exp.TsOrDsToTime) -> str: 3937 this = expression.this 3938 if isinstance(this, exp.TsOrDsToTime) or this.is_type(exp.DataType.Type.TIME): 3939 return self.sql(this) 3940 3941 return self.sql(exp.cast(this, exp.DataType.Type.TIME)) 3942 3943 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 3944 this = expression.this 3945 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 3946 return self.sql(this) 3947 3948 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect)) 3949 3950 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 3951 this = expression.this 3952 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 3953 return self.sql(this) 3954 3955 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect)) 3956 3957 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3958 this = expression.this 3959 time_format = self.format_time(expression) 3960 3961 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3962 return self.sql( 3963 exp.cast( 3964 exp.StrToTime(this=this, format=expression.args["format"]), 3965 exp.DataType.Type.DATE, 3966 ) 3967 ) 3968 3969 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3970 return self.sql(this) 3971 3972 return self.sql(exp.cast(this, exp.DataType.Type.DATE)) 3973 3974 def unixdate_sql(self, expression: exp.UnixDate) -> str: 3975 return self.sql( 3976 exp.func( 3977 "DATEDIFF", 3978 expression.this, 3979 exp.cast(exp.Literal.string("1970-01-01"), exp.DataType.Type.DATE), 3980 "day", 3981 ) 3982 ) 3983 3984 def lastday_sql(self, expression: exp.LastDay) -> str: 3985 if self.LAST_DAY_SUPPORTS_DATE_PART: 3986 return self.function_fallback_sql(expression) 3987 3988 unit = expression.text("unit") 3989 if unit and unit != "MONTH": 3990 self.unsupported("Date parts are not supported in LAST_DAY.") 3991 3992 return self.func("LAST_DAY", expression.this) 3993 3994 def dateadd_sql(self, expression: exp.DateAdd) -> str: 3995 from sqlglot.dialects.dialect import unit_to_str 3996 3997 return self.func( 3998 "DATE_ADD", expression.this, expression.expression, unit_to_str(expression) 3999 ) 4000 4001 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4002 if self.CAN_IMPLEMENT_ARRAY_ANY: 4003 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4004 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4005 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4006 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4007 4008 from sqlglot.dialects import Dialect 4009 4010 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4011 if self.dialect.__class__ != Dialect: 4012 self.unsupported("ARRAY_ANY is unsupported") 4013 4014 return self.function_fallback_sql(expression) 4015 4016 def struct_sql(self, expression: exp.Struct) -> str: 4017 expression.set( 4018 "expressions", 4019 [ 4020 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4021 if isinstance(e, exp.PropertyEQ) 4022 else e 4023 for e in expression.expressions 4024 ], 4025 ) 4026 4027 return self.function_fallback_sql(expression) 4028 4029 def partitionrange_sql(self, expression: exp.PartitionRange) -> str: 4030 low = self.sql(expression, "this") 4031 high = self.sql(expression, "expression") 4032 4033 return f"{low} TO {high}" 4034 4035 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4036 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4037 tables = f" {self.expressions(expression)}" 4038 4039 exists = " IF EXISTS" if expression.args.get("exists") else "" 4040 4041 on_cluster = self.sql(expression, "cluster") 4042 on_cluster = f" {on_cluster}" if on_cluster else "" 4043 4044 identity = self.sql(expression, "identity") 4045 identity = f" {identity} IDENTITY" if identity else "" 4046 4047 option = self.sql(expression, "option") 4048 option = f" {option}" if option else "" 4049 4050 partition = self.sql(expression, "partition") 4051 partition = f" {partition}" if partition else "" 4052 4053 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}" 4054 4055 # This transpiles T-SQL's CONVERT function 4056 # https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16 4057 def convert_sql(self, expression: exp.Convert) -> str: 4058 to = expression.this 4059 value = expression.expression 4060 style = expression.args.get("style") 4061 safe = expression.args.get("safe") 4062 strict = expression.args.get("strict") 4063 4064 if not to or not value: 4065 return "" 4066 4067 # Retrieve length of datatype and override to default if not specified 4068 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4069 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4070 4071 transformed: t.Optional[exp.Expression] = None 4072 cast = exp.Cast if strict else exp.TryCast 4073 4074 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4075 if isinstance(style, exp.Literal) and style.is_int: 4076 from sqlglot.dialects.tsql import TSQL 4077 4078 style_value = style.name 4079 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4080 if not converted_style: 4081 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4082 4083 fmt = exp.Literal.string(converted_style) 4084 4085 if to.this == exp.DataType.Type.DATE: 4086 transformed = exp.StrToDate(this=value, format=fmt) 4087 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4088 transformed = exp.StrToTime(this=value, format=fmt) 4089 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4090 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4091 elif to.this == exp.DataType.Type.TEXT: 4092 transformed = exp.TimeToStr(this=value, format=fmt) 4093 4094 if not transformed: 4095 transformed = cast(this=value, to=to, safe=safe) 4096 4097 return self.sql(transformed) 4098 4099 def _jsonpathkey_sql(self, expression: exp.JSONPathKey) -> str: 4100 this = expression.this 4101 if isinstance(this, exp.JSONPathWildcard): 4102 this = self.json_path_part(this) 4103 return f".{this}" if this else "" 4104 4105 if exp.SAFE_IDENTIFIER_RE.match(this): 4106 return f".{this}" 4107 4108 this = self.json_path_part(this) 4109 return ( 4110 f"[{this}]" 4111 if self._quote_json_path_key_using_brackets and self.JSON_PATH_BRACKETED_KEY_SUPPORTED 4112 else f".{this}" 4113 ) 4114 4115 def _jsonpathsubscript_sql(self, expression: exp.JSONPathSubscript) -> str: 4116 this = self.json_path_part(expression.this) 4117 return f"[{this}]" if this else "" 4118 4119 def _simplify_unless_literal(self, expression: E) -> E: 4120 if not isinstance(expression, exp.Literal): 4121 from sqlglot.optimizer.simplify import simplify 4122 4123 expression = simplify(expression, dialect=self.dialect) 4124 4125 return expression 4126 4127 def _embed_ignore_nulls(self, expression: exp.IgnoreNulls | exp.RespectNulls, text: str) -> str: 4128 if self.IGNORE_NULLS_IN_FUNC and not expression.meta.get("inline"): 4129 # The first modifier here will be the one closest to the AggFunc's arg 4130 mods = sorted( 4131 expression.find_all(exp.HavingMax, exp.Order, exp.Limit), 4132 key=lambda x: 0 4133 if isinstance(x, exp.HavingMax) 4134 else (1 if isinstance(x, exp.Order) else 2), 4135 ) 4136 4137 if mods: 4138 mod = mods[0] 4139 this = expression.__class__(this=mod.this.copy()) 4140 this.meta["inline"] = True 4141 mod.this.replace(this) 4142 return self.sql(expression.this) 4143 4144 agg_func = expression.find(exp.AggFunc) 4145 4146 if agg_func: 4147 return self.sql(agg_func)[:-1] + f" {text})" 4148 4149 return f"{self.sql(expression, 'this')} {text}" 4150 4151 def _replace_line_breaks(self, string: str) -> str: 4152 """We don't want to extra indent line breaks so we temporarily replace them with sentinels.""" 4153 if self.pretty: 4154 return string.replace("\n", self.SENTINEL_LINE_BREAK) 4155 return string 4156 4157 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4158 option = self.sql(expression, "this") 4159 4160 if expression.expressions: 4161 upper = option.upper() 4162 4163 # Snowflake FILE_FORMAT options are separated by whitespace 4164 sep = " " if upper == "FILE_FORMAT" else ", " 4165 4166 # Databricks copy/format options do not set their list of values with EQ 4167 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4168 values = self.expressions(expression, flat=True, sep=sep) 4169 return f"{option}{op}({values})" 4170 4171 value = self.sql(expression, "expression") 4172 4173 if not value: 4174 return option 4175 4176 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4177 4178 return f"{option}{op}{value}" 4179 4180 def credentials_sql(self, expression: exp.Credentials) -> str: 4181 cred_expr = expression.args.get("credentials") 4182 if isinstance(cred_expr, exp.Literal): 4183 # Redshift case: CREDENTIALS <string> 4184 credentials = self.sql(expression, "credentials") 4185 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4186 else: 4187 # Snowflake case: CREDENTIALS = (...) 4188 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4189 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4190 4191 storage = self.sql(expression, "storage") 4192 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4193 4194 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4195 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4196 4197 iam_role = self.sql(expression, "iam_role") 4198 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4199 4200 region = self.sql(expression, "region") 4201 region = f" REGION {region}" if region else "" 4202 4203 return f"{credentials}{storage}{encryption}{iam_role}{region}" 4204 4205 def copy_sql(self, expression: exp.Copy) -> str: 4206 this = self.sql(expression, "this") 4207 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4208 4209 credentials = self.sql(expression, "credentials") 4210 credentials = self.seg(credentials) if credentials else "" 4211 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4212 files = self.expressions(expression, key="files", flat=True) 4213 4214 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4215 params = self.expressions( 4216 expression, 4217 key="params", 4218 sep=sep, 4219 new_line=True, 4220 skip_last=True, 4221 skip_first=True, 4222 indent=self.COPY_PARAMS_ARE_WRAPPED, 4223 ) 4224 4225 if params: 4226 if self.COPY_PARAMS_ARE_WRAPPED: 4227 params = f" WITH ({params})" 4228 elif not self.pretty: 4229 params = f" {params}" 4230 4231 return f"COPY{this}{kind} {files}{credentials}{params}" 4232 4233 def semicolon_sql(self, expression: exp.Semicolon) -> str: 4234 return "" 4235 4236 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4237 on_sql = "ON" if expression.args.get("on") else "OFF" 4238 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4239 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4240 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4241 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4242 4243 if filter_col or retention_period: 4244 on_sql = self.func("ON", filter_col, retention_period) 4245 4246 return f"DATA_DELETION={on_sql}" 4247 4248 def maskingpolicycolumnconstraint_sql( 4249 self, expression: exp.MaskingPolicyColumnConstraint 4250 ) -> str: 4251 this = self.sql(expression, "this") 4252 expressions = self.expressions(expression, flat=True) 4253 expressions = f" USING ({expressions})" if expressions else "" 4254 return f"MASKING POLICY {this}{expressions}" 4255 4256 def gapfill_sql(self, expression: exp.GapFill) -> str: 4257 this = self.sql(expression, "this") 4258 this = f"TABLE {this}" 4259 return self.func("GAP_FILL", this, *[v for k, v in expression.args.items() if k != "this"]) 4260 4261 def scope_resolution(self, rhs: str, scope_name: str) -> str: 4262 return self.func("SCOPE_RESOLUTION", scope_name or None, rhs) 4263 4264 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4265 this = self.sql(expression, "this") 4266 expr = expression.expression 4267 4268 if isinstance(expr, exp.Func): 4269 # T-SQL's CLR functions are case sensitive 4270 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4271 else: 4272 expr = self.sql(expression, "expression") 4273 4274 return self.scope_resolution(expr, this) 4275 4276 def parsejson_sql(self, expression: exp.ParseJSON) -> str: 4277 if self.PARSE_JSON_NAME is None: 4278 return self.sql(expression.this) 4279 4280 return self.func(self.PARSE_JSON_NAME, expression.this, expression.expression) 4281 4282 def rand_sql(self, expression: exp.Rand) -> str: 4283 lower = self.sql(expression, "lower") 4284 upper = self.sql(expression, "upper") 4285 4286 if lower and upper: 4287 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4288 return self.func("RAND", expression.this) 4289 4290 def changes_sql(self, expression: exp.Changes) -> str: 4291 information = self.sql(expression, "information") 4292 information = f"INFORMATION => {information}" 4293 at_before = self.sql(expression, "at_before") 4294 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4295 end = self.sql(expression, "end") 4296 end = f"{self.seg('')}{end}" if end else "" 4297 4298 return f"CHANGES ({information}){at_before}{end}" 4299 4300 def pad_sql(self, expression: exp.Pad) -> str: 4301 prefix = "L" if expression.args.get("is_left") else "R" 4302 4303 fill_pattern = self.sql(expression, "fill_pattern") or None 4304 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4305 fill_pattern = "' '" 4306 4307 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern) 4308 4309 def summarize_sql(self, expression: exp.Summarize) -> str: 4310 table = " TABLE" if expression.args.get("table") else "" 4311 return f"SUMMARIZE{table} {self.sql(expression.this)}" 4312 4313 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4314 generate_series = exp.GenerateSeries(**expression.args) 4315 4316 parent = expression.parent 4317 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4318 parent = parent.parent 4319 4320 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4321 return self.sql(exp.Unnest(expressions=[generate_series])) 4322 4323 if isinstance(parent, exp.Select): 4324 self.unsupported("GenerateSeries projection unnesting is not supported.") 4325 4326 return self.sql(generate_series) 4327 4328 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4329 exprs = expression.expressions 4330 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4331 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4332 else: 4333 rhs = self.expressions(expression) 4334 4335 return self.func(name, expression.this, rhs or None) 4336 4337 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4338 if self.SUPPORTS_CONVERT_TIMEZONE: 4339 return self.function_fallback_sql(expression) 4340 4341 source_tz = expression.args.get("source_tz") 4342 target_tz = expression.args.get("target_tz") 4343 timestamp = expression.args.get("timestamp") 4344 4345 if source_tz and timestamp: 4346 timestamp = exp.AtTimeZone( 4347 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4348 ) 4349 4350 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4351 4352 return self.sql(expr) 4353 4354 def json_sql(self, expression: exp.JSON) -> str: 4355 this = self.sql(expression, "this") 4356 this = f" {this}" if this else "" 4357 4358 _with = expression.args.get("with") 4359 4360 if _with is None: 4361 with_sql = "" 4362 elif not _with: 4363 with_sql = " WITHOUT" 4364 else: 4365 with_sql = " WITH" 4366 4367 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4368 4369 return f"JSON{this}{with_sql}{unique_sql}" 4370 4371 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4372 def _generate_on_options(arg: t.Any) -> str: 4373 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4374 4375 path = self.sql(expression, "path") 4376 returning = self.sql(expression, "returning") 4377 returning = f" RETURNING {returning}" if returning else "" 4378 4379 on_condition = self.sql(expression, "on_condition") 4380 on_condition = f" {on_condition}" if on_condition else "" 4381 4382 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}") 4383 4384 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4385 else_ = "ELSE " if expression.args.get("else_") else "" 4386 condition = self.sql(expression, "expression") 4387 condition = f"WHEN {condition} THEN " if condition else else_ 4388 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4389 return f"{condition}{insert}" 4390 4391 def multitableinserts_sql(self, expression: exp.MultitableInserts) -> str: 4392 kind = self.sql(expression, "kind") 4393 expressions = self.seg(self.expressions(expression, sep=" ")) 4394 res = f"INSERT {kind}{expressions}{self.seg(self.sql(expression, 'source'))}" 4395 return res 4396 4397 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4398 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4399 empty = expression.args.get("empty") 4400 empty = ( 4401 f"DEFAULT {empty} ON EMPTY" 4402 if isinstance(empty, exp.Expression) 4403 else self.sql(expression, "empty") 4404 ) 4405 4406 error = expression.args.get("error") 4407 error = ( 4408 f"DEFAULT {error} ON ERROR" 4409 if isinstance(error, exp.Expression) 4410 else self.sql(expression, "error") 4411 ) 4412 4413 if error and empty: 4414 error = ( 4415 f"{empty} {error}" 4416 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4417 else f"{error} {empty}" 4418 ) 4419 empty = "" 4420 4421 null = self.sql(expression, "null") 4422 4423 return f"{empty}{error}{null}" 4424 4425 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4426 this = self.sql(expression, "this") 4427 path = self.sql(expression, "path") 4428 4429 passing = self.expressions(expression, "passing") 4430 passing = f" PASSING {passing}" if passing else "" 4431 4432 on_condition = self.sql(expression, "on_condition") 4433 on_condition = f" {on_condition}" if on_condition else "" 4434 4435 path = f"{path}{passing}{on_condition}" 4436 4437 return self.func("JSON_EXISTS", this, path) 4438 4439 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4440 array_agg = self.function_fallback_sql(expression) 4441 4442 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4443 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4444 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4445 parent = expression.parent 4446 if isinstance(parent, exp.Filter): 4447 parent_cond = parent.expression.this 4448 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4449 else: 4450 this = expression.this 4451 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4452 if this.find(exp.Column): 4453 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4454 this_sql = ( 4455 self.expressions(this) 4456 if isinstance(this, exp.Distinct) 4457 else self.sql(expression, "this") 4458 ) 4459 4460 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4461 4462 return array_agg 4463 4464 def apply_sql(self, expression: exp.Apply) -> str: 4465 this = self.sql(expression, "this") 4466 expr = self.sql(expression, "expression") 4467 4468 return f"{this} APPLY({expr})" 4469 4470 def grant_sql(self, expression: exp.Grant) -> str: 4471 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4472 4473 kind = self.sql(expression, "kind") 4474 kind = f" {kind}" if kind else "" 4475 4476 securable = self.sql(expression, "securable") 4477 securable = f" {securable}" if securable else "" 4478 4479 principals = self.expressions(expression, key="principals", flat=True) 4480 4481 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4482 4483 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}" 4484 4485 def grantprivilege_sql(self, expression: exp.GrantPrivilege): 4486 this = self.sql(expression, "this") 4487 columns = self.expressions(expression, flat=True) 4488 columns = f"({columns})" if columns else "" 4489 4490 return f"{this}{columns}" 4491 4492 def grantprincipal_sql(self, expression: exp.GrantPrincipal): 4493 this = self.sql(expression, "this") 4494 4495 kind = self.sql(expression, "kind") 4496 kind = f"{kind} " if kind else "" 4497 4498 return f"{kind}{this}" 4499 4500 def columns_sql(self, expression: exp.Columns): 4501 func = self.function_fallback_sql(expression) 4502 if expression.args.get("unpack"): 4503 func = f"*{func}" 4504 4505 return func 4506 4507 def overlay_sql(self, expression: exp.Overlay): 4508 this = self.sql(expression, "this") 4509 expr = self.sql(expression, "expression") 4510 from_sql = self.sql(expression, "from") 4511 for_sql = self.sql(expression, "for") 4512 for_sql = f" FOR {for_sql}" if for_sql else "" 4513 4514 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})" 4515 4516 @unsupported_args("format") 4517 def todouble_sql(self, expression: exp.ToDouble) -> str: 4518 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 4519 4520 def string_sql(self, expression: exp.String) -> str: 4521 this = expression.this 4522 zone = expression.args.get("zone") 4523 4524 if zone: 4525 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4526 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4527 # set for source_tz to transpile the time conversion before the STRING cast 4528 this = exp.ConvertTimezone( 4529 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4530 ) 4531 4532 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR)) 4533 4534 def median_sql(self, expression: exp.Median): 4535 if not self.SUPPORTS_MEDIAN: 4536 return self.sql( 4537 exp.PercentileCont(this=expression.this, expression=exp.Literal.number(0.5)) 4538 ) 4539 4540 return self.function_fallback_sql(expression) 4541 4542 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4543 filler = self.sql(expression, "this") 4544 filler = f" {filler}" if filler else "" 4545 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4546 return f"TRUNCATE{filler} {with_count}" 4547 4548 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4549 if self.SUPPORTS_UNIX_SECONDS: 4550 return self.function_fallback_sql(expression) 4551 4552 start_ts = exp.cast( 4553 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4554 ) 4555 4556 return self.sql( 4557 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4558 ) 4559 4560 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4561 dim = expression.expression 4562 4563 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4564 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4565 if not (dim.is_int and dim.name == "1"): 4566 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4567 dim = None 4568 4569 # If dimension is required but not specified, default initialize it 4570 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4571 dim = exp.Literal.number(1) 4572 4573 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim) 4574 4575 def attach_sql(self, expression: exp.Attach) -> str: 4576 this = self.sql(expression, "this") 4577 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4578 expressions = self.expressions(expression) 4579 expressions = f" ({expressions})" if expressions else "" 4580 4581 return f"ATTACH{exists_sql} {this}{expressions}" 4582 4583 def detach_sql(self, expression: exp.Detach) -> str: 4584 this = self.sql(expression, "this") 4585 exists_sql = " IF EXISTS" if expression.args.get("exists") else "" 4586 4587 return f"DETACH{exists_sql} {this}" 4588 4589 def attachoption_sql(self, expression: exp.AttachOption) -> str: 4590 this = self.sql(expression, "this") 4591 value = self.sql(expression, "expression") 4592 value = f" {value}" if value else "" 4593 return f"{this}{value}" 4594 4595 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4596 this_sql = self.sql(expression, "this") 4597 if isinstance(expression.this, exp.Table): 4598 this_sql = f"TABLE {this_sql}" 4599 4600 return self.func( 4601 "FEATURES_AT_TIME", 4602 this_sql, 4603 expression.args.get("time"), 4604 expression.args.get("num_rows"), 4605 expression.args.get("ignore_feature_nulls"), 4606 ) 4607 4608 def watermarkcolumnconstraint_sql(self, expression: exp.WatermarkColumnConstraint) -> str: 4609 return ( 4610 f"WATERMARK FOR {self.sql(expression, 'this')} AS {self.sql(expression, 'expression')}" 4611 ) 4612 4613 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4614 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4615 encode = f"{encode} {self.sql(expression, 'this')}" 4616 4617 properties = expression.args.get("properties") 4618 if properties: 4619 encode = f"{encode} {self.properties(properties)}" 4620 4621 return encode 4622 4623 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4624 this = self.sql(expression, "this") 4625 include = f"INCLUDE {this}" 4626 4627 column_def = self.sql(expression, "column_def") 4628 if column_def: 4629 include = f"{include} {column_def}" 4630 4631 alias = self.sql(expression, "alias") 4632 if alias: 4633 include = f"{include} AS {alias}" 4634 4635 return include 4636 4637 def xmlelement_sql(self, expression: exp.XMLElement) -> str: 4638 name = f"NAME {self.sql(expression, 'this')}" 4639 return self.func("XMLELEMENT", name, *expression.expressions) 4640 4641 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4642 partitions = self.expressions(expression, "partition_expressions") 4643 create = self.expressions(expression, "create_expressions") 4644 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}" 4645 4646 def partitionbyrangepropertydynamic_sql( 4647 self, expression: exp.PartitionByRangePropertyDynamic 4648 ) -> str: 4649 start = self.sql(expression, "start") 4650 end = self.sql(expression, "end") 4651 4652 every = expression.args["every"] 4653 if isinstance(every, exp.Interval) and every.this.is_string: 4654 every.this.replace(exp.Literal.number(every.name)) 4655 4656 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}" 4657 4658 def unpivotcolumns_sql(self, expression: exp.UnpivotColumns) -> str: 4659 name = self.sql(expression, "this") 4660 values = self.expressions(expression, flat=True) 4661 4662 return f"NAME {name} VALUE {values}" 4663 4664 def analyzesample_sql(self, expression: exp.AnalyzeSample) -> str: 4665 kind = self.sql(expression, "kind") 4666 sample = self.sql(expression, "sample") 4667 return f"SAMPLE {sample} {kind}" 4668 4669 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4670 kind = self.sql(expression, "kind") 4671 option = self.sql(expression, "option") 4672 option = f" {option}" if option else "" 4673 this = self.sql(expression, "this") 4674 this = f" {this}" if this else "" 4675 columns = self.expressions(expression) 4676 columns = f" {columns}" if columns else "" 4677 return f"{kind}{option} STATISTICS{this}{columns}" 4678 4679 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4680 this = self.sql(expression, "this") 4681 columns = self.expressions(expression) 4682 inner_expression = self.sql(expression, "expression") 4683 inner_expression = f" {inner_expression}" if inner_expression else "" 4684 update_options = self.sql(expression, "update_options") 4685 update_options = f" {update_options} UPDATE" if update_options else "" 4686 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}" 4687 4688 def analyzedelete_sql(self, expression: exp.AnalyzeDelete) -> str: 4689 kind = self.sql(expression, "kind") 4690 kind = f" {kind}" if kind else "" 4691 return f"DELETE{kind} STATISTICS" 4692 4693 def analyzelistchainedrows_sql(self, expression: exp.AnalyzeListChainedRows) -> str: 4694 inner_expression = self.sql(expression, "expression") 4695 return f"LIST CHAINED ROWS{inner_expression}" 4696 4697 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4698 kind = self.sql(expression, "kind") 4699 this = self.sql(expression, "this") 4700 this = f" {this}" if this else "" 4701 inner_expression = self.sql(expression, "expression") 4702 return f"VALIDATE {kind}{this}{inner_expression}" 4703 4704 def analyze_sql(self, expression: exp.Analyze) -> str: 4705 options = self.expressions(expression, key="options", sep=" ") 4706 options = f" {options}" if options else "" 4707 kind = self.sql(expression, "kind") 4708 kind = f" {kind}" if kind else "" 4709 this = self.sql(expression, "this") 4710 this = f" {this}" if this else "" 4711 mode = self.sql(expression, "mode") 4712 mode = f" {mode}" if mode else "" 4713 properties = self.sql(expression, "properties") 4714 properties = f" {properties}" if properties else "" 4715 partition = self.sql(expression, "partition") 4716 partition = f" {partition}" if partition else "" 4717 inner_expression = self.sql(expression, "expression") 4718 inner_expression = f" {inner_expression}" if inner_expression else "" 4719 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}" 4720 4721 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4722 this = self.sql(expression, "this") 4723 passing = self.expressions(expression, key="passing") 4724 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4725 columns = self.expressions(expression, key="columns") 4726 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4727 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4728 return f"XMLTABLE({self.sep('')}{self.indent(this + passing + by_ref + columns)}{self.seg(')', sep='')}"
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.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None)
672 def __init__( 673 self, 674 pretty: t.Optional[bool] = None, 675 identify: str | bool = False, 676 normalize: bool = False, 677 pad: int = 2, 678 indent: int = 2, 679 normalize_functions: t.Optional[str | bool] = None, 680 unsupported_level: ErrorLevel = ErrorLevel.WARN, 681 max_unsupported: int = 3, 682 leading_comma: bool = False, 683 max_text_width: int = 80, 684 comments: bool = True, 685 dialect: DialectType = None, 686 ): 687 import sqlglot 688 from sqlglot.dialects import Dialect 689 690 self.pretty = pretty if pretty is not None else sqlglot.pretty 691 self.identify = identify 692 self.normalize = normalize 693 self.pad = pad 694 self._indent = indent 695 self.unsupported_level = unsupported_level 696 self.max_unsupported = max_unsupported 697 self.leading_comma = leading_comma 698 self.max_text_width = max_text_width 699 self.comments = comments 700 self.dialect = Dialect.get_or_raise(dialect) 701 702 # This is both a Dialect property and a Generator argument, so we prioritize the latter 703 self.normalize_functions = ( 704 self.dialect.NORMALIZE_FUNCTIONS if normalize_functions is None else normalize_functions 705 ) 706 707 self.unsupported_messages: t.List[str] = [] 708 self._escaped_quote_end: str = ( 709 self.dialect.tokenizer_class.STRING_ESCAPES[0] + self.dialect.QUOTE_END 710 ) 711 self._escaped_identifier_end = self.dialect.IDENTIFIER_END * 2 712 713 self._next_name = name_sequence("_t") 714 715 self._identifier_start = self.dialect.IDENTIFIER_START 716 self._identifier_end = self.dialect.IDENTIFIER_END 717 718 self._quote_json_path_key_using_brackets = True
TRANSFORMS: Dict[Type[sqlglot.expressions.Expression], Callable[..., str]] =
{<class 'sqlglot.expressions.JSONPathFilter'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathKey'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRecursive'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathRoot'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathScript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSelector'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSlice'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathSubscript'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathUnion'>: <function <lambda>>, <class 'sqlglot.expressions.JSONPathWildcard'>: <function <lambda>>, <class 'sqlglot.expressions.AllowedValuesProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeColumns'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AnalyzeWith'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayContainsAll'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ArrayOverlaps'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.BackupProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CaseSpecificColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Ceil'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CharacterSetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CollateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CommentColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ConnectByRoot'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DateFormatColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DefaultColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.DynamicProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EmptyProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EncodeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.EphemeralColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExcludeColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Except'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ExternalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Floor'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.GlobalProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.HeapProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IcebergProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InheritsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InlineLengthColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.InputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Intersect'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.IntervalSpan'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Int64'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LanguageProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LocationProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.LogProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.MaterializedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NonClusteredColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.NotForReplicationColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnCommitProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OnUpdateColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Operator'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.OutputModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PathColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.PivotAny'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ProjectionPolicyColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ReturnsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SampleProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecureProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetConfigProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SetProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SettingsProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SharingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StabilityProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Stream'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StreamingTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.StrictProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.SwapTable'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TemporaryProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Tags'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TitleColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ToTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransformModelProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.TransientProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Union'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UnloggedProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UsingData'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.Uuid'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.UppercaseColumnConstraint'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VarMap'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.VolatileProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithProcedureOptions'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <function Generator.<lambda>>, <class 'sqlglot.expressions.WithOperator'>: <function Generator.<lambda>>}
SUPPORTED_JSON_PATH_PARTS =
{<class 'sqlglot.expressions.JSONPathSubscript'>, <class 'sqlglot.expressions.JSONPathWildcard'>, <class 'sqlglot.expressions.JSONPathSelector'>, <class 'sqlglot.expressions.JSONPathSlice'>, <class 'sqlglot.expressions.JSONPathScript'>, <class 'sqlglot.expressions.JSONPathRoot'>, <class 'sqlglot.expressions.JSONPathUnion'>, <class 'sqlglot.expressions.JSONPathRecursive'>, <class 'sqlglot.expressions.JSONPathKey'>, <class 'sqlglot.expressions.JSONPathFilter'>}
TYPE_MAPPING =
{<Type.DATETIME2: 'DATETIME2'>: 'TIMESTAMP', <Type.NCHAR: 'NCHAR'>: 'CHAR', <Type.NVARCHAR: 'NVARCHAR'>: 'VARCHAR', <Type.MEDIUMTEXT: 'MEDIUMTEXT'>: 'TEXT', <Type.LONGTEXT: 'LONGTEXT'>: 'TEXT', <Type.TINYTEXT: 'TINYTEXT'>: 'TEXT', <Type.MEDIUMBLOB: 'MEDIUMBLOB'>: 'BLOB', <Type.LONGBLOB: 'LONGBLOB'>: 'BLOB', <Type.TINYBLOB: 'TINYBLOB'>: 'BLOB', <Type.INET: 'INET'>: 'INET', <Type.ROWVERSION: 'ROWVERSION'>: 'VARBINARY', <Type.SMALLDATETIME: 'SMALLDATETIME'>: 'TIMESTAMP'}
TIME_PART_SINGULARS =
{'MICROSECONDS': 'MICROSECOND', 'SECONDS': 'SECOND', 'MINUTES': 'MINUTE', 'HOURS': 'HOUR', 'DAYS': 'DAY', 'WEEKS': 'WEEK', 'MONTHS': 'MONTH', 'QUARTERS': 'QUARTER', 'YEARS': 'YEAR'}
AFTER_HAVING_MODIFIER_TRANSFORMS =
{'cluster': <function Generator.<lambda>>, 'distribute': <function Generator.<lambda>>, 'sort': <function Generator.<lambda>>, 'windows': <function Generator.<lambda>>, 'qualify': <function Generator.<lambda>>}
PROPERTIES_LOCATION =
{<class 'sqlglot.expressions.AllowedValuesProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AlgorithmProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.AutoIncrementProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.AutoRefreshProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BackupProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.BlockCompressionProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CharacterSetProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ChecksumProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.CollateProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.CopyGrantsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Cluster'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ClusteredByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistributedByProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DuplicateKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DataBlocksizeProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.DataDeletionProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DefinerProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DictRange'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DynamicProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.DistKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.DistStyleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EmptyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.EncodeProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.EngineProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExecuteAsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ExternalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.FallbackProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.FileFormatProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.FreespaceProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.GlobalProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.HeapProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.InheritsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IcebergProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.IncludeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.InputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.IsolatedLoadingProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.JournalProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.LanguageProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LikeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LocationProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.LockingProperty'>: <Location.POST_ALIAS: 'POST_ALIAS'>, <class 'sqlglot.expressions.LogProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.MaterializedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.MergeBlockRatioProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.NoPrimaryIndexProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.OnProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OnCommitProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.Order'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.OutputModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PartitionedByProperty'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.PartitionedOfProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.PrimaryKey'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Property'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.RemoteWithConnectionModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.ReturnsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatDelimitedProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.RowFormatSerdeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SampleProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SchemaCommentProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SecureProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SecurityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SerdeProperties'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Set'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SettingsProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SetProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.SetConfigProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SharingProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SequenceProperties'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.SortKeyProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlReadWriteProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.SqlSecurityProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StabilityProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.StreamingTableProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.StrictProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.Tags'>: <Location.POST_WITH: 'POST_WITH'>, <class 'sqlglot.expressions.TemporaryProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ToTableProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.TransientProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.TransformModelProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.MergeTreeTTL'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.UnloggedProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.ViewAttributeProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.VolatileProperty'>: <Location.POST_CREATE: 'POST_CREATE'>, <class 'sqlglot.expressions.WithDataProperty'>: <Location.POST_EXPRESSION: 'POST_EXPRESSION'>, <class 'sqlglot.expressions.WithJournalTableProperty'>: <Location.POST_NAME: 'POST_NAME'>, <class 'sqlglot.expressions.WithProcedureOptions'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSchemaBindingProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>, <class 'sqlglot.expressions.WithSystemVersioningProperty'>: <Location.POST_SCHEMA: 'POST_SCHEMA'>}
WITH_SEPARATED_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Command'>, <class 'sqlglot.expressions.Create'>, <class 'sqlglot.expressions.Describe'>, <class 'sqlglot.expressions.Delete'>, <class 'sqlglot.expressions.Drop'>, <class 'sqlglot.expressions.From'>, <class 'sqlglot.expressions.Insert'>, <class 'sqlglot.expressions.Join'>, <class 'sqlglot.expressions.MultitableInserts'>, <class 'sqlglot.expressions.Select'>, <class 'sqlglot.expressions.SetOperation'>, <class 'sqlglot.expressions.Update'>, <class 'sqlglot.expressions.Where'>, <class 'sqlglot.expressions.With'>)
EXCLUDE_COMMENTS: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Binary'>, <class 'sqlglot.expressions.SetOperation'>)
UNWRAPPED_INTERVAL_VALUES: Tuple[Type[sqlglot.expressions.Expression], ...] =
(<class 'sqlglot.expressions.Column'>, <class 'sqlglot.expressions.Literal'>, <class 'sqlglot.expressions.Neg'>, <class 'sqlglot.expressions.Paren'>)
PARAMETERIZABLE_TEXT_TYPES =
{<Type.NCHAR: 'NCHAR'>, <Type.CHAR: 'CHAR'>, <Type.NVARCHAR: 'NVARCHAR'>, <Type.VARCHAR: 'VARCHAR'>}
720 def generate(self, expression: exp.Expression, copy: bool = True) -> str: 721 """ 722 Generates the SQL string corresponding to the given syntax tree. 723 724 Args: 725 expression: The syntax tree. 726 copy: Whether to copy the expression. The generator performs mutations so 727 it is safer to copy. 728 729 Returns: 730 The SQL string corresponding to `expression`. 731 """ 732 if copy: 733 expression = expression.copy() 734 735 expression = self.preprocess(expression) 736 737 self.unsupported_messages = [] 738 sql = self.sql(expression).strip() 739 740 if self.pretty: 741 sql = sql.replace(self.SENTINEL_LINE_BREAK, "\n") 742 743 if self.unsupported_level == ErrorLevel.IGNORE: 744 return sql 745 746 if self.unsupported_level == ErrorLevel.WARN: 747 for msg in self.unsupported_messages: 748 logger.warning(msg) 749 elif self.unsupported_level == ErrorLevel.RAISE and self.unsupported_messages: 750 raise UnsupportedError(concat_messages(self.unsupported_messages, self.max_unsupported)) 751 752 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:
754 def preprocess(self, expression: exp.Expression) -> exp.Expression: 755 """Apply generic preprocessing transformations to a given expression.""" 756 expression = self._move_ctes_to_top_level(expression) 757 758 if self.ENSURE_BOOLS: 759 from sqlglot.transforms import ensure_bools 760 761 expression = ensure_bools(expression) 762 763 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:
792 def maybe_comment( 793 self, 794 sql: str, 795 expression: t.Optional[exp.Expression] = None, 796 comments: t.Optional[t.List[str]] = None, 797 separated: bool = False, 798 ) -> str: 799 comments = ( 800 ((expression and expression.comments) if comments is None else comments) # type: ignore 801 if self.comments 802 else None 803 ) 804 805 if not comments or isinstance(expression, self.EXCLUDE_COMMENTS): 806 return sql 807 808 comments_sql = " ".join( 809 f"/*{self.pad_comment(comment)}*/" for comment in comments if comment 810 ) 811 812 if not comments_sql: 813 return sql 814 815 comments_sql = self._replace_line_breaks(comments_sql) 816 817 if separated or isinstance(expression, self.WITH_SEPARATED_COMMENTS): 818 return ( 819 f"{self.sep()}{comments_sql}{sql}" 820 if not sql or sql[0].isspace() 821 else f"{comments_sql}{self.sep()}{sql}" 822 ) 823 824 return f"{sql} {comments_sql}"
826 def wrap(self, expression: exp.Expression | str) -> str: 827 this_sql = ( 828 self.sql(expression) 829 if isinstance(expression, exp.UNWRAPPED_QUERIES) 830 else self.sql(expression, "this") 831 ) 832 if not this_sql: 833 return "()" 834 835 this_sql = self.indent(this_sql, level=1, pad=0) 836 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:
852 def indent( 853 self, 854 sql: str, 855 level: int = 0, 856 pad: t.Optional[int] = None, 857 skip_first: bool = False, 858 skip_last: bool = False, 859 ) -> str: 860 if not self.pretty or not sql: 861 return sql 862 863 pad = self.pad if pad is None else pad 864 lines = sql.split("\n") 865 866 return "\n".join( 867 ( 868 line 869 if (skip_first and i == 0) or (skip_last and i == len(lines) - 1) 870 else f"{' ' * (level * self._indent + pad)}{line}" 871 ) 872 for i, line in enumerate(lines) 873 )
def
sql( self, expression: Union[str, sqlglot.expressions.Expression, NoneType], key: Optional[str] = None, comment: bool = True) -> str:
875 def sql( 876 self, 877 expression: t.Optional[str | exp.Expression], 878 key: t.Optional[str] = None, 879 comment: bool = True, 880 ) -> str: 881 if not expression: 882 return "" 883 884 if isinstance(expression, str): 885 return expression 886 887 if key: 888 value = expression.args.get(key) 889 if value: 890 return self.sql(value) 891 return "" 892 893 transform = self.TRANSFORMS.get(expression.__class__) 894 895 if callable(transform): 896 sql = transform(self, expression) 897 elif isinstance(expression, exp.Expression): 898 exp_handler_name = f"{expression.key}_sql" 899 900 if hasattr(self, exp_handler_name): 901 sql = getattr(self, exp_handler_name)(expression) 902 elif isinstance(expression, exp.Func): 903 sql = self.function_fallback_sql(expression) 904 elif isinstance(expression, exp.Property): 905 sql = self.property_sql(expression) 906 else: 907 raise ValueError(f"Unsupported expression type {expression.__class__.__name__}") 908 else: 909 raise ValueError(f"Expected an Expression. Received {type(expression)}: {expression}") 910 911 return self.maybe_comment(sql, expression) if self.comments and comment else sql
918 def cache_sql(self, expression: exp.Cache) -> str: 919 lazy = " LAZY" if expression.args.get("lazy") else "" 920 table = self.sql(expression, "this") 921 options = expression.args.get("options") 922 options = f" OPTIONS({self.sql(options[0])} = {self.sql(options[1])})" if options else "" 923 sql = self.sql(expression, "expression") 924 sql = f" AS{self.sep()}{sql}" if sql else "" 925 sql = f"CACHE{lazy} TABLE {table}{options}{sql}" 926 return self.prepend_ctes(expression, sql)
928 def characterset_sql(self, expression: exp.CharacterSet) -> str: 929 if isinstance(expression.parent, exp.Cast): 930 return f"CHAR CHARACTER SET {self.sql(expression, 'this')}" 931 default = "DEFAULT " if expression.args.get("default") else "" 932 return f"{default}CHARACTER SET={self.sql(expression, 'this')}"
946 def column_sql(self, expression: exp.Column) -> str: 947 join_mark = " (+)" if expression.args.get("join_mark") else "" 948 949 if join_mark and not self.dialect.SUPPORTS_COLUMN_JOIN_MARKS: 950 join_mark = "" 951 self.unsupported("Outer join syntax using the (+) operator is not supported.") 952 953 return f"{self.column_parts(expression)}{join_mark}"
961 def columndef_sql(self, expression: exp.ColumnDef, sep: str = " ") -> str: 962 column = self.sql(expression, "this") 963 kind = self.sql(expression, "kind") 964 constraints = self.expressions(expression, key="constraints", sep=" ", flat=True) 965 exists = "IF NOT EXISTS " if expression.args.get("exists") else "" 966 kind = f"{sep}{kind}" if kind else "" 967 constraints = f" {constraints}" if constraints else "" 968 position = self.sql(expression, "position") 969 position = f" {position}" if position else "" 970 971 if expression.find(exp.ComputedColumnConstraint) and not self.COMPUTED_COLUMN_WITH_TYPE: 972 kind = "" 973 974 return f"{exists}{column}{kind}{constraints}{position}"
def
computedcolumnconstraint_sql(self, expression: sqlglot.expressions.ComputedColumnConstraint) -> str:
981 def computedcolumnconstraint_sql(self, expression: exp.ComputedColumnConstraint) -> str: 982 this = self.sql(expression, "this") 983 if expression.args.get("not_null"): 984 persisted = " PERSISTED NOT NULL" 985 elif expression.args.get("persisted"): 986 persisted = " PERSISTED" 987 else: 988 persisted = "" 989 return f"AS {this}{persisted}"
def
compresscolumnconstraint_sql(self, expression: sqlglot.expressions.CompressColumnConstraint) -> str:
def
generatedasidentitycolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsIdentityColumnConstraint) -> str:
1002 def generatedasidentitycolumnconstraint_sql( 1003 self, expression: exp.GeneratedAsIdentityColumnConstraint 1004 ) -> str: 1005 this = "" 1006 if expression.this is not None: 1007 on_null = " ON NULL" if expression.args.get("on_null") else "" 1008 this = " ALWAYS" if expression.this else f" BY DEFAULT{on_null}" 1009 1010 start = expression.args.get("start") 1011 start = f"START WITH {start}" if start else "" 1012 increment = expression.args.get("increment") 1013 increment = f" INCREMENT BY {increment}" if increment else "" 1014 minvalue = expression.args.get("minvalue") 1015 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1016 maxvalue = expression.args.get("maxvalue") 1017 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1018 cycle = expression.args.get("cycle") 1019 cycle_sql = "" 1020 1021 if cycle is not None: 1022 cycle_sql = f"{' NO' if not cycle else ''} CYCLE" 1023 cycle_sql = cycle_sql.strip() if not start and not increment else cycle_sql 1024 1025 sequence_opts = "" 1026 if start or increment or cycle_sql: 1027 sequence_opts = f"{start}{increment}{minvalue}{maxvalue}{cycle_sql}" 1028 sequence_opts = f" ({sequence_opts.strip()})" 1029 1030 expr = self.sql(expression, "expression") 1031 expr = f"({expr})" if expr else "IDENTITY" 1032 1033 return f"GENERATED{this} AS {expr}{sequence_opts}"
def
generatedasrowcolumnconstraint_sql( self, expression: sqlglot.expressions.GeneratedAsRowColumnConstraint) -> str:
1035 def generatedasrowcolumnconstraint_sql( 1036 self, expression: exp.GeneratedAsRowColumnConstraint 1037 ) -> str: 1038 start = "START" if expression.args.get("start") else "END" 1039 hidden = " HIDDEN" if expression.args.get("hidden") else "" 1040 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:
1059 def uniquecolumnconstraint_sql(self, expression: exp.UniqueColumnConstraint) -> str: 1060 this = self.sql(expression, "this") 1061 this = f" {this}" if this else "" 1062 index_type = expression.args.get("index_type") 1063 index_type = f" USING {index_type}" if index_type else "" 1064 on_conflict = self.sql(expression, "on_conflict") 1065 on_conflict = f" {on_conflict}" if on_conflict else "" 1066 nulls_sql = " NULLS NOT DISTINCT" if expression.args.get("nulls") else "" 1067 return f"UNIQUE{nulls_sql}{this}{index_type}{on_conflict}"
1072 def create_sql(self, expression: exp.Create) -> str: 1073 kind = self.sql(expression, "kind") 1074 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1075 properties = expression.args.get("properties") 1076 properties_locs = self.locate_properties(properties) if properties else defaultdict() 1077 1078 this = self.createable_sql(expression, properties_locs) 1079 1080 properties_sql = "" 1081 if properties_locs.get(exp.Properties.Location.POST_SCHEMA) or properties_locs.get( 1082 exp.Properties.Location.POST_WITH 1083 ): 1084 properties_sql = self.sql( 1085 exp.Properties( 1086 expressions=[ 1087 *properties_locs[exp.Properties.Location.POST_SCHEMA], 1088 *properties_locs[exp.Properties.Location.POST_WITH], 1089 ] 1090 ) 1091 ) 1092 1093 if properties_locs.get(exp.Properties.Location.POST_SCHEMA): 1094 properties_sql = self.sep() + properties_sql 1095 elif not self.pretty: 1096 # Standalone POST_WITH properties need a leading whitespace in non-pretty mode 1097 properties_sql = f" {properties_sql}" 1098 1099 begin = " BEGIN" if expression.args.get("begin") else "" 1100 end = " END" if expression.args.get("end") else "" 1101 1102 expression_sql = self.sql(expression, "expression") 1103 if expression_sql: 1104 expression_sql = f"{begin}{self.sep()}{expression_sql}{end}" 1105 1106 if self.CREATE_FUNCTION_RETURN_AS or not isinstance(expression.expression, exp.Return): 1107 postalias_props_sql = "" 1108 if properties_locs.get(exp.Properties.Location.POST_ALIAS): 1109 postalias_props_sql = self.properties( 1110 exp.Properties( 1111 expressions=properties_locs[exp.Properties.Location.POST_ALIAS] 1112 ), 1113 wrapped=False, 1114 ) 1115 postalias_props_sql = f" {postalias_props_sql}" if postalias_props_sql else "" 1116 expression_sql = f" AS{postalias_props_sql}{expression_sql}" 1117 1118 postindex_props_sql = "" 1119 if properties_locs.get(exp.Properties.Location.POST_INDEX): 1120 postindex_props_sql = self.properties( 1121 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_INDEX]), 1122 wrapped=False, 1123 prefix=" ", 1124 ) 1125 1126 indexes = self.expressions(expression, key="indexes", indent=False, sep=" ") 1127 indexes = f" {indexes}" if indexes else "" 1128 index_sql = indexes + postindex_props_sql 1129 1130 replace = " OR REPLACE" if expression.args.get("replace") else "" 1131 refresh = " OR REFRESH" if expression.args.get("refresh") else "" 1132 unique = " UNIQUE" if expression.args.get("unique") else "" 1133 1134 clustered = expression.args.get("clustered") 1135 if clustered is None: 1136 clustered_sql = "" 1137 elif clustered: 1138 clustered_sql = " CLUSTERED COLUMNSTORE" 1139 else: 1140 clustered_sql = " NONCLUSTERED COLUMNSTORE" 1141 1142 postcreate_props_sql = "" 1143 if properties_locs.get(exp.Properties.Location.POST_CREATE): 1144 postcreate_props_sql = self.properties( 1145 exp.Properties(expressions=properties_locs[exp.Properties.Location.POST_CREATE]), 1146 sep=" ", 1147 prefix=" ", 1148 wrapped=False, 1149 ) 1150 1151 modifiers = "".join((clustered_sql, replace, refresh, unique, postcreate_props_sql)) 1152 1153 postexpression_props_sql = "" 1154 if properties_locs.get(exp.Properties.Location.POST_EXPRESSION): 1155 postexpression_props_sql = self.properties( 1156 exp.Properties( 1157 expressions=properties_locs[exp.Properties.Location.POST_EXPRESSION] 1158 ), 1159 sep=" ", 1160 prefix=" ", 1161 wrapped=False, 1162 ) 1163 1164 concurrently = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1165 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 1166 no_schema_binding = ( 1167 " WITH NO SCHEMA BINDING" if expression.args.get("no_schema_binding") else "" 1168 ) 1169 1170 clone = self.sql(expression, "clone") 1171 clone = f" {clone}" if clone else "" 1172 1173 if kind in self.EXPRESSION_PRECEDES_PROPERTIES_CREATABLES: 1174 properties_expression = f"{expression_sql}{properties_sql}" 1175 else: 1176 properties_expression = f"{properties_sql}{expression_sql}" 1177 1178 expression_sql = f"CREATE{modifiers} {kind}{concurrently}{exists_sql} {this}{properties_expression}{postexpression_props_sql}{index_sql}{no_schema_binding}{clone}" 1179 return self.prepend_ctes(expression, expression_sql)
1181 def sequenceproperties_sql(self, expression: exp.SequenceProperties) -> str: 1182 start = self.sql(expression, "start") 1183 start = f"START WITH {start}" if start else "" 1184 increment = self.sql(expression, "increment") 1185 increment = f" INCREMENT BY {increment}" if increment else "" 1186 minvalue = self.sql(expression, "minvalue") 1187 minvalue = f" MINVALUE {minvalue}" if minvalue else "" 1188 maxvalue = self.sql(expression, "maxvalue") 1189 maxvalue = f" MAXVALUE {maxvalue}" if maxvalue else "" 1190 owned = self.sql(expression, "owned") 1191 owned = f" OWNED BY {owned}" if owned else "" 1192 1193 cache = expression.args.get("cache") 1194 if cache is None: 1195 cache_str = "" 1196 elif cache is True: 1197 cache_str = " CACHE" 1198 else: 1199 cache_str = f" CACHE {cache}" 1200 1201 options = self.expressions(expression, key="options", flat=True, sep=" ") 1202 options = f" {options}" if options else "" 1203 1204 return f"{start}{increment}{minvalue}{maxvalue}{cache_str}{options}{owned}".lstrip()
1206 def clone_sql(self, expression: exp.Clone) -> str: 1207 this = self.sql(expression, "this") 1208 shallow = "SHALLOW " if expression.args.get("shallow") else "" 1209 keyword = "COPY" if expression.args.get("copy") and self.SUPPORTS_TABLE_COPY else "CLONE" 1210 return f"{shallow}{keyword} {this}"
1212 def describe_sql(self, expression: exp.Describe) -> str: 1213 style = expression.args.get("style") 1214 style = f" {style}" if style else "" 1215 partition = self.sql(expression, "partition") 1216 partition = f" {partition}" if partition else "" 1217 format = self.sql(expression, "format") 1218 format = f" {format}" if format else "" 1219 1220 return f"DESCRIBE{style}{format} {self.sql(expression, 'this')}{partition}"
1242 def cte_sql(self, expression: exp.CTE) -> str: 1243 alias = expression.args.get("alias") 1244 if alias: 1245 alias.add_comments(expression.pop_comments()) 1246 1247 alias_sql = self.sql(expression, "alias") 1248 1249 materialized = expression.args.get("materialized") 1250 if materialized is False: 1251 materialized = "NOT MATERIALIZED " 1252 elif materialized: 1253 materialized = "MATERIALIZED " 1254 1255 return f"{alias_sql} AS {materialized or ''}{self.wrap(expression)}"
1257 def tablealias_sql(self, expression: exp.TableAlias) -> str: 1258 alias = self.sql(expression, "this") 1259 columns = self.expressions(expression, key="columns", flat=True) 1260 columns = f"({columns})" if columns else "" 1261 1262 if columns and not self.SUPPORTS_TABLE_ALIAS_COLUMNS: 1263 columns = "" 1264 self.unsupported("Named columns are not supported in table alias.") 1265 1266 if not alias and not self.dialect.UNNEST_COLUMN_ONLY: 1267 alias = self._next_name() 1268 1269 return f"{alias}{columns}"
1289 def unicodestring_sql(self, expression: exp.UnicodeString) -> str: 1290 this = self.sql(expression, "this") 1291 escape = expression.args.get("escape") 1292 1293 if self.dialect.UNICODE_START: 1294 escape_substitute = r"\\\1" 1295 left_quote, right_quote = self.dialect.UNICODE_START, self.dialect.UNICODE_END 1296 else: 1297 escape_substitute = r"\\u\1" 1298 left_quote, right_quote = self.dialect.QUOTE_START, self.dialect.QUOTE_END 1299 1300 if escape: 1301 escape_pattern = re.compile(rf"{escape.name}(\d+)") 1302 escape_sql = f" UESCAPE {self.sql(escape)}" if self.SUPPORTS_UESCAPE else "" 1303 else: 1304 escape_pattern = ESCAPED_UNICODE_RE 1305 escape_sql = "" 1306 1307 if not self.dialect.UNICODE_START or (escape and not self.SUPPORTS_UESCAPE): 1308 this = escape_pattern.sub(escape_substitute, this) 1309 1310 return f"{left_quote}{this}{right_quote}{escape_sql}"
1322 def datatype_sql(self, expression: exp.DataType) -> str: 1323 nested = "" 1324 values = "" 1325 interior = self.expressions(expression, flat=True) 1326 1327 type_value = expression.this 1328 if type_value == exp.DataType.Type.USERDEFINED and expression.args.get("kind"): 1329 type_sql = self.sql(expression, "kind") 1330 else: 1331 type_sql = ( 1332 self.TYPE_MAPPING.get(type_value, type_value.value) 1333 if isinstance(type_value, exp.DataType.Type) 1334 else type_value 1335 ) 1336 1337 if interior: 1338 if expression.args.get("nested"): 1339 nested = f"{self.STRUCT_DELIMITER[0]}{interior}{self.STRUCT_DELIMITER[1]}" 1340 if expression.args.get("values") is not None: 1341 delimiters = ("[", "]") if type_value == exp.DataType.Type.ARRAY else ("(", ")") 1342 values = self.expressions(expression, key="values", flat=True) 1343 values = f"{delimiters[0]}{values}{delimiters[1]}" 1344 elif type_value == exp.DataType.Type.INTERVAL: 1345 nested = f" {interior}" 1346 else: 1347 nested = f"({interior})" 1348 1349 type_sql = f"{type_sql}{nested}{values}" 1350 if self.TZ_TO_WITH_TIME_ZONE and type_value in ( 1351 exp.DataType.Type.TIMETZ, 1352 exp.DataType.Type.TIMESTAMPTZ, 1353 ): 1354 type_sql = f"{type_sql} WITH TIME ZONE" 1355 1356 return type_sql
1358 def directory_sql(self, expression: exp.Directory) -> str: 1359 local = "LOCAL " if expression.args.get("local") else "" 1360 row_format = self.sql(expression, "row_format") 1361 row_format = f" {row_format}" if row_format else "" 1362 return f"{local}DIRECTORY {self.sql(expression, 'this')}{row_format}"
1364 def delete_sql(self, expression: exp.Delete) -> str: 1365 this = self.sql(expression, "this") 1366 this = f" FROM {this}" if this else "" 1367 using = self.sql(expression, "using") 1368 using = f" USING {using}" if using else "" 1369 cluster = self.sql(expression, "cluster") 1370 cluster = f" {cluster}" if cluster else "" 1371 where = self.sql(expression, "where") 1372 returning = self.sql(expression, "returning") 1373 limit = self.sql(expression, "limit") 1374 tables = self.expressions(expression, key="tables") 1375 tables = f" {tables}" if tables else "" 1376 if self.RETURNING_END: 1377 expression_sql = f"{this}{using}{cluster}{where}{returning}{limit}" 1378 else: 1379 expression_sql = f"{returning}{this}{using}{cluster}{where}{limit}" 1380 return self.prepend_ctes(expression, f"DELETE{tables}{expression_sql}")
1382 def drop_sql(self, expression: exp.Drop) -> str: 1383 this = self.sql(expression, "this") 1384 expressions = self.expressions(expression, flat=True) 1385 expressions = f" ({expressions})" if expressions else "" 1386 kind = expression.args["kind"] 1387 kind = self.dialect.INVERSE_CREATABLE_KIND_MAPPING.get(kind) or kind 1388 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 1389 concurrently_sql = " CONCURRENTLY" if expression.args.get("concurrently") else "" 1390 on_cluster = self.sql(expression, "cluster") 1391 on_cluster = f" {on_cluster}" if on_cluster else "" 1392 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 1393 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 1394 cascade = " CASCADE" if expression.args.get("cascade") else "" 1395 constraints = " CONSTRAINTS" if expression.args.get("constraints") else "" 1396 purge = " PURGE" if expression.args.get("purge") else "" 1397 return f"DROP{temporary}{materialized} {kind}{concurrently_sql}{exists_sql}{this}{on_cluster}{expressions}{cascade}{constraints}{purge}"
1399 def set_operation(self, expression: exp.SetOperation) -> str: 1400 op_type = type(expression) 1401 op_name = op_type.key.upper() 1402 1403 distinct = expression.args.get("distinct") 1404 if ( 1405 distinct is False 1406 and op_type in (exp.Except, exp.Intersect) 1407 and not self.EXCEPT_INTERSECT_SUPPORT_ALL_CLAUSE 1408 ): 1409 self.unsupported(f"{op_name} ALL is not supported") 1410 1411 default_distinct = self.dialect.SET_OP_DISTINCT_BY_DEFAULT[op_type] 1412 1413 if distinct is None: 1414 distinct = default_distinct 1415 if distinct is None: 1416 self.unsupported(f"{op_name} requires DISTINCT or ALL to be specified") 1417 1418 if distinct is default_distinct: 1419 kind = "" 1420 else: 1421 kind = " DISTINCT" if distinct else " ALL" 1422 1423 by_name = " BY NAME" if expression.args.get("by_name") else "" 1424 return f"{op_name}{kind}{by_name}"
1426 def set_operations(self, expression: exp.SetOperation) -> str: 1427 if not self.SET_OP_MODIFIERS: 1428 limit = expression.args.get("limit") 1429 order = expression.args.get("order") 1430 1431 if limit or order: 1432 select = self._move_ctes_to_top_level( 1433 exp.subquery(expression, "_l_0", copy=False).select("*", copy=False) 1434 ) 1435 1436 if limit: 1437 select = select.limit(limit.pop(), copy=False) 1438 if order: 1439 select = select.order_by(order.pop(), copy=False) 1440 return self.sql(select) 1441 1442 sqls: t.List[str] = [] 1443 stack: t.List[t.Union[str, exp.Expression]] = [expression] 1444 1445 while stack: 1446 node = stack.pop() 1447 1448 if isinstance(node, exp.SetOperation): 1449 stack.append(node.expression) 1450 stack.append( 1451 self.maybe_comment( 1452 self.set_operation(node), comments=node.comments, separated=True 1453 ) 1454 ) 1455 stack.append(node.this) 1456 else: 1457 sqls.append(self.sql(node)) 1458 1459 this = self.sep().join(sqls) 1460 this = self.query_modifiers(expression, this) 1461 return self.prepend_ctes(expression, this)
1463 def fetch_sql(self, expression: exp.Fetch) -> str: 1464 direction = expression.args.get("direction") 1465 direction = f" {direction}" if direction else "" 1466 count = self.sql(expression, "count") 1467 count = f" {count}" if count else "" 1468 if expression.args.get("percent"): 1469 count = f"{count} PERCENT" 1470 with_ties_or_only = "WITH TIES" if expression.args.get("with_ties") else "ONLY" 1471 return f"{self.seg('FETCH')}{direction}{count} ROWS {with_ties_or_only}"
1473 def filter_sql(self, expression: exp.Filter) -> str: 1474 if self.AGGREGATE_FILTER_SUPPORTED: 1475 this = self.sql(expression, "this") 1476 where = self.sql(expression, "expression").strip() 1477 return f"{this} FILTER({where})" 1478 1479 agg = expression.this 1480 agg_arg = agg.this 1481 cond = expression.expression.this 1482 agg_arg.replace(exp.If(this=cond.copy(), true=agg_arg.copy())) 1483 return self.sql(agg)
1492 def indexparameters_sql(self, expression: exp.IndexParameters) -> str: 1493 using = self.sql(expression, "using") 1494 using = f" USING {using}" if using else "" 1495 columns = self.expressions(expression, key="columns", flat=True) 1496 columns = f"({columns})" if columns else "" 1497 partition_by = self.expressions(expression, key="partition_by", flat=True) 1498 partition_by = f" PARTITION BY {partition_by}" if partition_by else "" 1499 where = self.sql(expression, "where") 1500 include = self.expressions(expression, key="include", flat=True) 1501 if include: 1502 include = f" INCLUDE ({include})" 1503 with_storage = self.expressions(expression, key="with_storage", flat=True) 1504 with_storage = f" WITH ({with_storage})" if with_storage else "" 1505 tablespace = self.sql(expression, "tablespace") 1506 tablespace = f" USING INDEX TABLESPACE {tablespace}" if tablespace else "" 1507 on = self.sql(expression, "on") 1508 on = f" ON {on}" if on else "" 1509 1510 return f"{using}{columns}{include}{with_storage}{tablespace}{partition_by}{where}{on}"
1512 def index_sql(self, expression: exp.Index) -> str: 1513 unique = "UNIQUE " if expression.args.get("unique") else "" 1514 primary = "PRIMARY " if expression.args.get("primary") else "" 1515 amp = "AMP " if expression.args.get("amp") else "" 1516 name = self.sql(expression, "this") 1517 name = f"{name} " if name else "" 1518 table = self.sql(expression, "table") 1519 table = f"{self.INDEX_ON} {table}" if table else "" 1520 1521 index = "INDEX " if not table else "" 1522 1523 params = self.sql(expression, "params") 1524 return f"{unique}{primary}{amp}{index}{name}{table}{params}"
1526 def identifier_sql(self, expression: exp.Identifier) -> str: 1527 text = expression.name 1528 lower = text.lower() 1529 text = lower if self.normalize and not expression.quoted else text 1530 text = text.replace(self._identifier_end, self._escaped_identifier_end) 1531 if ( 1532 expression.quoted 1533 or self.dialect.can_identify(text, self.identify) 1534 or lower in self.RESERVED_KEYWORDS 1535 or (not self.dialect.IDENTIFIERS_CAN_START_WITH_DIGIT and text[:1].isdigit()) 1536 ): 1537 text = f"{self._identifier_start}{text}{self._identifier_end}" 1538 return text
1553 def inputoutputformat_sql(self, expression: exp.InputOutputFormat) -> str: 1554 input_format = self.sql(expression, "input_format") 1555 input_format = f"INPUTFORMAT {input_format}" if input_format else "" 1556 output_format = self.sql(expression, "output_format") 1557 output_format = f"OUTPUTFORMAT {output_format}" if output_format else "" 1558 return self.sep().join((input_format, output_format))
1568 def properties_sql(self, expression: exp.Properties) -> str: 1569 root_properties = [] 1570 with_properties = [] 1571 1572 for p in expression.expressions: 1573 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1574 if p_loc == exp.Properties.Location.POST_WITH: 1575 with_properties.append(p) 1576 elif p_loc == exp.Properties.Location.POST_SCHEMA: 1577 root_properties.append(p) 1578 1579 root_props = self.root_properties(exp.Properties(expressions=root_properties)) 1580 with_props = self.with_properties(exp.Properties(expressions=with_properties)) 1581 1582 if root_props and with_props and not self.pretty: 1583 with_props = " " + with_props 1584 1585 return root_props + with_props
def
properties( self, properties: sqlglot.expressions.Properties, prefix: str = '', sep: str = ', ', suffix: str = '', wrapped: bool = True) -> str:
1592 def properties( 1593 self, 1594 properties: exp.Properties, 1595 prefix: str = "", 1596 sep: str = ", ", 1597 suffix: str = "", 1598 wrapped: bool = True, 1599 ) -> str: 1600 if properties.expressions: 1601 expressions = self.expressions(properties, sep=sep, indent=False) 1602 if expressions: 1603 expressions = self.wrap(expressions) if wrapped else expressions 1604 return f"{prefix}{' ' if prefix.strip() else ''}{expressions}{suffix}" 1605 return ""
1610 def locate_properties(self, properties: exp.Properties) -> t.DefaultDict: 1611 properties_locs = defaultdict(list) 1612 for p in properties.expressions: 1613 p_loc = self.PROPERTIES_LOCATION[p.__class__] 1614 if p_loc != exp.Properties.Location.UNSUPPORTED: 1615 properties_locs[p_loc].append(p) 1616 else: 1617 self.unsupported(f"Unsupported property {p.key}") 1618 1619 return properties_locs
def
property_name( self, expression: sqlglot.expressions.Property, string_key: bool = False) -> str:
1626 def property_sql(self, expression: exp.Property) -> str: 1627 property_cls = expression.__class__ 1628 if property_cls == exp.Property: 1629 return f"{self.property_name(expression)}={self.sql(expression, 'value')}" 1630 1631 property_name = exp.Properties.PROPERTY_TO_NAME.get(property_cls) 1632 if not property_name: 1633 self.unsupported(f"Unsupported property {expression.key}") 1634 1635 return f"{property_name}={self.sql(expression, 'this')}"
1637 def likeproperty_sql(self, expression: exp.LikeProperty) -> str: 1638 if self.SUPPORTS_CREATE_TABLE_LIKE: 1639 options = " ".join(f"{e.name} {self.sql(e, 'value')}" for e in expression.expressions) 1640 options = f" {options}" if options else "" 1641 1642 like = f"LIKE {self.sql(expression, 'this')}{options}" 1643 if self.LIKE_PROPERTY_INSIDE_SCHEMA and not isinstance(expression.parent, exp.Schema): 1644 like = f"({like})" 1645 1646 return like 1647 1648 if expression.expressions: 1649 self.unsupported("Transpilation of LIKE property options is unsupported") 1650 1651 select = exp.select("*").from_(expression.this).limit(0) 1652 return f"AS {self.sql(select)}"
1659 def journalproperty_sql(self, expression: exp.JournalProperty) -> str: 1660 no = "NO " if expression.args.get("no") else "" 1661 local = expression.args.get("local") 1662 local = f"{local} " if local else "" 1663 dual = "DUAL " if expression.args.get("dual") else "" 1664 before = "BEFORE " if expression.args.get("before") else "" 1665 after = "AFTER " if expression.args.get("after") else "" 1666 return f"{no}{local}{dual}{before}{after}JOURNAL"
def
mergeblockratioproperty_sql(self, expression: sqlglot.expressions.MergeBlockRatioProperty) -> str:
1682 def mergeblockratioproperty_sql(self, expression: exp.MergeBlockRatioProperty) -> str: 1683 if expression.args.get("no"): 1684 return "NO MERGEBLOCKRATIO" 1685 if expression.args.get("default"): 1686 return "DEFAULT MERGEBLOCKRATIO" 1687 1688 percent = " PERCENT" if expression.args.get("percent") else "" 1689 return f"MERGEBLOCKRATIO={self.sql(expression, 'this')}{percent}"
1691 def datablocksizeproperty_sql(self, expression: exp.DataBlocksizeProperty) -> str: 1692 default = expression.args.get("default") 1693 minimum = expression.args.get("minimum") 1694 maximum = expression.args.get("maximum") 1695 if default or minimum or maximum: 1696 if default: 1697 prop = "DEFAULT" 1698 elif minimum: 1699 prop = "MINIMUM" 1700 else: 1701 prop = "MAXIMUM" 1702 return f"{prop} DATABLOCKSIZE" 1703 units = expression.args.get("units") 1704 units = f" {units}" if units else "" 1705 return f"DATABLOCKSIZE={self.sql(expression, 'size')}{units}"
def
blockcompressionproperty_sql(self, expression: sqlglot.expressions.BlockCompressionProperty) -> str:
1707 def blockcompressionproperty_sql(self, expression: exp.BlockCompressionProperty) -> str: 1708 autotemp = expression.args.get("autotemp") 1709 always = expression.args.get("always") 1710 default = expression.args.get("default") 1711 manual = expression.args.get("manual") 1712 never = expression.args.get("never") 1713 1714 if autotemp is not None: 1715 prop = f"AUTOTEMP({self.expressions(autotemp)})" 1716 elif always: 1717 prop = "ALWAYS" 1718 elif default: 1719 prop = "DEFAULT" 1720 elif manual: 1721 prop = "MANUAL" 1722 elif never: 1723 prop = "NEVER" 1724 return f"BLOCKCOMPRESSION={prop}"
def
isolatedloadingproperty_sql(self, expression: sqlglot.expressions.IsolatedLoadingProperty) -> str:
1726 def isolatedloadingproperty_sql(self, expression: exp.IsolatedLoadingProperty) -> str: 1727 no = expression.args.get("no") 1728 no = " NO" if no else "" 1729 concurrent = expression.args.get("concurrent") 1730 concurrent = " CONCURRENT" if concurrent else "" 1731 target = self.sql(expression, "target") 1732 target = f" {target}" if target else "" 1733 return f"WITH{no}{concurrent} ISOLATED LOADING{target}"
1735 def partitionboundspec_sql(self, expression: exp.PartitionBoundSpec) -> str: 1736 if isinstance(expression.this, list): 1737 return f"IN ({self.expressions(expression, key='this', flat=True)})" 1738 if expression.this: 1739 modulus = self.sql(expression, "this") 1740 remainder = self.sql(expression, "expression") 1741 return f"WITH (MODULUS {modulus}, REMAINDER {remainder})" 1742 1743 from_expressions = self.expressions(expression, key="from_expressions", flat=True) 1744 to_expressions = self.expressions(expression, key="to_expressions", flat=True) 1745 return f"FROM ({from_expressions}) TO ({to_expressions})"
1747 def partitionedofproperty_sql(self, expression: exp.PartitionedOfProperty) -> str: 1748 this = self.sql(expression, "this") 1749 1750 for_values_or_default = expression.expression 1751 if isinstance(for_values_or_default, exp.PartitionBoundSpec): 1752 for_values_or_default = f" FOR VALUES {self.sql(for_values_or_default)}" 1753 else: 1754 for_values_or_default = " DEFAULT" 1755 1756 return f"PARTITION OF {this}{for_values_or_default}"
1758 def lockingproperty_sql(self, expression: exp.LockingProperty) -> str: 1759 kind = expression.args.get("kind") 1760 this = f" {self.sql(expression, 'this')}" if expression.this else "" 1761 for_or_in = expression.args.get("for_or_in") 1762 for_or_in = f" {for_or_in}" if for_or_in else "" 1763 lock_type = expression.args.get("lock_type") 1764 override = " OVERRIDE" if expression.args.get("override") else "" 1765 return f"LOCKING {kind}{this}{for_or_in} {lock_type}{override}"
1767 def withdataproperty_sql(self, expression: exp.WithDataProperty) -> str: 1768 data_sql = f"WITH {'NO ' if expression.args.get('no') else ''}DATA" 1769 statistics = expression.args.get("statistics") 1770 statistics_sql = "" 1771 if statistics is not None: 1772 statistics_sql = f" AND {'NO ' if not statistics else ''}STATISTICS" 1773 return f"{data_sql}{statistics_sql}"
def
withsystemversioningproperty_sql( self, expression: sqlglot.expressions.WithSystemVersioningProperty) -> str:
1775 def withsystemversioningproperty_sql(self, expression: exp.WithSystemVersioningProperty) -> str: 1776 this = self.sql(expression, "this") 1777 this = f"HISTORY_TABLE={this}" if this else "" 1778 data_consistency: t.Optional[str] = self.sql(expression, "data_consistency") 1779 data_consistency = ( 1780 f"DATA_CONSISTENCY_CHECK={data_consistency}" if data_consistency else None 1781 ) 1782 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 1783 retention_period = ( 1784 f"HISTORY_RETENTION_PERIOD={retention_period}" if retention_period else None 1785 ) 1786 1787 if this: 1788 on_sql = self.func("ON", this, data_consistency, retention_period) 1789 else: 1790 on_sql = "ON" if expression.args.get("on") else "OFF" 1791 1792 sql = f"SYSTEM_VERSIONING={on_sql}" 1793 1794 return f"WITH({sql})" if expression.args.get("with") else sql
1796 def insert_sql(self, expression: exp.Insert) -> str: 1797 hint = self.sql(expression, "hint") 1798 overwrite = expression.args.get("overwrite") 1799 1800 if isinstance(expression.this, exp.Directory): 1801 this = " OVERWRITE" if overwrite else " INTO" 1802 else: 1803 this = self.INSERT_OVERWRITE if overwrite else " INTO" 1804 1805 stored = self.sql(expression, "stored") 1806 stored = f" {stored}" if stored else "" 1807 alternative = expression.args.get("alternative") 1808 alternative = f" OR {alternative}" if alternative else "" 1809 ignore = " IGNORE" if expression.args.get("ignore") else "" 1810 is_function = expression.args.get("is_function") 1811 if is_function: 1812 this = f"{this} FUNCTION" 1813 this = f"{this} {self.sql(expression, 'this')}" 1814 1815 exists = " IF EXISTS" if expression.args.get("exists") else "" 1816 where = self.sql(expression, "where") 1817 where = f"{self.sep()}REPLACE WHERE {where}" if where else "" 1818 expression_sql = f"{self.sep()}{self.sql(expression, 'expression')}" 1819 on_conflict = self.sql(expression, "conflict") 1820 on_conflict = f" {on_conflict}" if on_conflict else "" 1821 by_name = " BY NAME" if expression.args.get("by_name") else "" 1822 returning = self.sql(expression, "returning") 1823 1824 if self.RETURNING_END: 1825 expression_sql = f"{expression_sql}{on_conflict}{returning}" 1826 else: 1827 expression_sql = f"{returning}{expression_sql}{on_conflict}" 1828 1829 partition_by = self.sql(expression, "partition") 1830 partition_by = f" {partition_by}" if partition_by else "" 1831 settings = self.sql(expression, "settings") 1832 settings = f" {settings}" if settings else "" 1833 1834 source = self.sql(expression, "source") 1835 source = f"TABLE {source}" if source else "" 1836 1837 sql = f"INSERT{hint}{alternative}{ignore}{this}{stored}{by_name}{exists}{partition_by}{settings}{where}{expression_sql}{source}" 1838 return self.prepend_ctes(expression, sql)
1856 def onconflict_sql(self, expression: exp.OnConflict) -> str: 1857 conflict = "ON DUPLICATE KEY" if expression.args.get("duplicate") else "ON CONFLICT" 1858 1859 constraint = self.sql(expression, "constraint") 1860 constraint = f" ON CONSTRAINT {constraint}" if constraint else "" 1861 1862 conflict_keys = self.expressions(expression, key="conflict_keys", flat=True) 1863 conflict_keys = f"({conflict_keys}) " if conflict_keys else " " 1864 action = self.sql(expression, "action") 1865 1866 expressions = self.expressions(expression, flat=True) 1867 if expressions: 1868 set_keyword = "SET " if self.DUPLICATE_KEY_UPDATE_WITH_SET else "" 1869 expressions = f" {set_keyword}{expressions}" 1870 1871 where = self.sql(expression, "where") 1872 return f"{conflict}{constraint}{conflict_keys}{action}{expressions}{where}"
def
rowformatdelimitedproperty_sql(self, expression: sqlglot.expressions.RowFormatDelimitedProperty) -> str:
1877 def rowformatdelimitedproperty_sql(self, expression: exp.RowFormatDelimitedProperty) -> str: 1878 fields = self.sql(expression, "fields") 1879 fields = f" FIELDS TERMINATED BY {fields}" if fields else "" 1880 escaped = self.sql(expression, "escaped") 1881 escaped = f" ESCAPED BY {escaped}" if escaped else "" 1882 items = self.sql(expression, "collection_items") 1883 items = f" COLLECTION ITEMS TERMINATED BY {items}" if items else "" 1884 keys = self.sql(expression, "map_keys") 1885 keys = f" MAP KEYS TERMINATED BY {keys}" if keys else "" 1886 lines = self.sql(expression, "lines") 1887 lines = f" LINES TERMINATED BY {lines}" if lines else "" 1888 null = self.sql(expression, "null") 1889 null = f" NULL DEFINED AS {null}" if null else "" 1890 return f"ROW FORMAT DELIMITED{fields}{escaped}{items}{keys}{lines}{null}"
1918 def table_sql(self, expression: exp.Table, sep: str = " AS ") -> str: 1919 table = self.table_parts(expression) 1920 only = "ONLY " if expression.args.get("only") else "" 1921 partition = self.sql(expression, "partition") 1922 partition = f" {partition}" if partition else "" 1923 version = self.sql(expression, "version") 1924 version = f" {version}" if version else "" 1925 alias = self.sql(expression, "alias") 1926 alias = f"{sep}{alias}" if alias else "" 1927 1928 sample = self.sql(expression, "sample") 1929 if self.dialect.ALIAS_POST_TABLESAMPLE: 1930 sample_pre_alias = sample 1931 sample_post_alias = "" 1932 else: 1933 sample_pre_alias = "" 1934 sample_post_alias = sample 1935 1936 hints = self.expressions(expression, key="hints", sep=" ") 1937 hints = f" {hints}" if hints and self.TABLE_HINTS else "" 1938 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 1939 joins = self.indent( 1940 self.expressions(expression, key="joins", sep="", flat=True), skip_first=True 1941 ) 1942 laterals = self.expressions(expression, key="laterals", sep="") 1943 1944 file_format = self.sql(expression, "format") 1945 if file_format: 1946 pattern = self.sql(expression, "pattern") 1947 pattern = f", PATTERN => {pattern}" if pattern else "" 1948 file_format = f" (FILE_FORMAT => {file_format}{pattern})" 1949 1950 ordinality = expression.args.get("ordinality") or "" 1951 if ordinality: 1952 ordinality = f" WITH ORDINALITY{alias}" 1953 alias = "" 1954 1955 when = self.sql(expression, "when") 1956 if when: 1957 table = f"{table} {when}" 1958 1959 changes = self.sql(expression, "changes") 1960 changes = f" {changes}" if changes else "" 1961 1962 rows_from = self.expressions(expression, key="rows_from") 1963 if rows_from: 1964 table = f"ROWS FROM {self.wrap(rows_from)}" 1965 1966 return f"{only}{table}{changes}{partition}{version}{file_format}{sample_pre_alias}{alias}{hints}{pivots}{sample_post_alias}{joins}{laterals}{ordinality}"
def
tablesample_sql( self, expression: sqlglot.expressions.TableSample, tablesample_keyword: Optional[str] = None) -> str:
1968 def tablesample_sql( 1969 self, 1970 expression: exp.TableSample, 1971 tablesample_keyword: t.Optional[str] = None, 1972 ) -> str: 1973 method = self.sql(expression, "method") 1974 method = f"{method} " if method and self.TABLESAMPLE_WITH_METHOD else "" 1975 numerator = self.sql(expression, "bucket_numerator") 1976 denominator = self.sql(expression, "bucket_denominator") 1977 field = self.sql(expression, "bucket_field") 1978 field = f" ON {field}" if field else "" 1979 bucket = f"BUCKET {numerator} OUT OF {denominator}{field}" if numerator else "" 1980 seed = self.sql(expression, "seed") 1981 seed = f" {self.TABLESAMPLE_SEED_KEYWORD} ({seed})" if seed else "" 1982 1983 size = self.sql(expression, "size") 1984 if size and self.TABLESAMPLE_SIZE_IS_ROWS: 1985 size = f"{size} ROWS" 1986 1987 percent = self.sql(expression, "percent") 1988 if percent and not self.dialect.TABLESAMPLE_SIZE_IS_PERCENT: 1989 percent = f"{percent} PERCENT" 1990 1991 expr = f"{bucket}{percent}{size}" 1992 if self.TABLESAMPLE_REQUIRES_PARENS: 1993 expr = f"({expr})" 1994 1995 return f" {tablesample_keyword or self.TABLESAMPLE_KEYWORDS} {method}{expr}{seed}"
1997 def pivot_sql(self, expression: exp.Pivot) -> str: 1998 expressions = self.expressions(expression, flat=True) 1999 direction = "UNPIVOT" if expression.unpivot else "PIVOT" 2000 2001 if expression.this: 2002 this = self.sql(expression, "this") 2003 if not expressions: 2004 return f"UNPIVOT {this}" 2005 2006 on = f"{self.seg('ON')} {expressions}" 2007 into = self.sql(expression, "into") 2008 into = f"{self.seg('INTO')} {into}" if into else "" 2009 using = self.expressions(expression, key="using", flat=True) 2010 using = f"{self.seg('USING')} {using}" if using else "" 2011 group = self.sql(expression, "group") 2012 return f"{direction} {this}{on}{into}{using}{group}" 2013 2014 alias = self.sql(expression, "alias") 2015 alias = f" AS {alias}" if alias else "" 2016 2017 field = self.sql(expression, "field") 2018 2019 include_nulls = expression.args.get("include_nulls") 2020 if include_nulls is not None: 2021 nulls = " INCLUDE NULLS " if include_nulls else " EXCLUDE NULLS " 2022 else: 2023 nulls = "" 2024 2025 default_on_null = self.sql(expression, "default_on_null") 2026 default_on_null = f" DEFAULT ON NULL ({default_on_null})" if default_on_null else "" 2027 return f"{self.seg(direction)}{nulls}({expressions} FOR {field}{default_on_null}){alias}"
2038 def update_sql(self, expression: exp.Update) -> str: 2039 this = self.sql(expression, "this") 2040 set_sql = self.expressions(expression, flat=True) 2041 from_sql = self.sql(expression, "from") 2042 where_sql = self.sql(expression, "where") 2043 returning = self.sql(expression, "returning") 2044 order = self.sql(expression, "order") 2045 limit = self.sql(expression, "limit") 2046 if self.RETURNING_END: 2047 expression_sql = f"{from_sql}{where_sql}{returning}" 2048 else: 2049 expression_sql = f"{returning}{from_sql}{where_sql}" 2050 sql = f"UPDATE {this} SET {set_sql}{expression_sql}{order}{limit}" 2051 return self.prepend_ctes(expression, sql)
2053 def values_sql(self, expression: exp.Values, values_as_table: bool = True) -> str: 2054 values_as_table = values_as_table and self.VALUES_AS_TABLE 2055 2056 # The VALUES clause is still valid in an `INSERT INTO ..` statement, for example 2057 if values_as_table or not expression.find_ancestor(exp.From, exp.Join): 2058 args = self.expressions(expression) 2059 alias = self.sql(expression, "alias") 2060 values = f"VALUES{self.seg('')}{args}" 2061 values = ( 2062 f"({values})" 2063 if self.WRAP_DERIVED_VALUES 2064 and (alias or isinstance(expression.parent, (exp.From, exp.Table))) 2065 else values 2066 ) 2067 return f"{values} AS {alias}" if alias else values 2068 2069 # Converts `VALUES...` expression into a series of select unions. 2070 alias_node = expression.args.get("alias") 2071 column_names = alias_node and alias_node.columns 2072 2073 selects: t.List[exp.Query] = [] 2074 2075 for i, tup in enumerate(expression.expressions): 2076 row = tup.expressions 2077 2078 if i == 0 and column_names: 2079 row = [ 2080 exp.alias_(value, column_name) for value, column_name in zip(row, column_names) 2081 ] 2082 2083 selects.append(exp.Select(expressions=row)) 2084 2085 if self.pretty: 2086 # This may result in poor performance for large-cardinality `VALUES` tables, due to 2087 # the deep nesting of the resulting exp.Unions. If this is a problem, either increase 2088 # `sys.setrecursionlimit` to avoid RecursionErrors, or don't set `pretty`. 2089 query = reduce(lambda x, y: exp.union(x, y, distinct=False, copy=False), selects) 2090 return self.subquery_sql(query.subquery(alias_node and alias_node.this, copy=False)) 2091 2092 alias = f" AS {self.sql(alias_node, 'this')}" if alias_node else "" 2093 unions = " UNION ALL ".join(self.sql(select) for select in selects) 2094 return f"({unions}){alias}"
2099 @unsupported_args("expressions") 2100 def into_sql(self, expression: exp.Into) -> str: 2101 temporary = " TEMPORARY" if expression.args.get("temporary") else "" 2102 unlogged = " UNLOGGED" if expression.args.get("unlogged") else "" 2103 return f"{self.seg('INTO')}{temporary or unlogged} {self.sql(expression, 'this')}"
2120 def group_sql(self, expression: exp.Group) -> str: 2121 group_by_all = expression.args.get("all") 2122 if group_by_all is True: 2123 modifier = " ALL" 2124 elif group_by_all is False: 2125 modifier = " DISTINCT" 2126 else: 2127 modifier = "" 2128 2129 group_by = self.op_expressions(f"GROUP BY{modifier}", expression) 2130 2131 grouping_sets = self.expressions(expression, key="grouping_sets") 2132 cube = self.expressions(expression, key="cube") 2133 rollup = self.expressions(expression, key="rollup") 2134 2135 groupings = csv( 2136 self.seg(grouping_sets) if grouping_sets else "", 2137 self.seg(cube) if cube else "", 2138 self.seg(rollup) if rollup else "", 2139 self.seg("WITH TOTALS") if expression.args.get("totals") else "", 2140 sep=self.GROUPINGS_SEP, 2141 ) 2142 2143 if ( 2144 expression.expressions 2145 and groupings 2146 and groupings.strip() not in ("WITH CUBE", "WITH ROLLUP") 2147 ): 2148 group_by = f"{group_by}{self.GROUPINGS_SEP}" 2149 2150 return f"{group_by}{groupings}"
2156 def connect_sql(self, expression: exp.Connect) -> str: 2157 start = self.sql(expression, "start") 2158 start = self.seg(f"START WITH {start}") if start else "" 2159 nocycle = " NOCYCLE" if expression.args.get("nocycle") else "" 2160 connect = self.sql(expression, "connect") 2161 connect = self.seg(f"CONNECT BY{nocycle} {connect}") 2162 return start + connect
2167 def join_sql(self, expression: exp.Join) -> str: 2168 if not self.SEMI_ANTI_JOIN_WITH_SIDE and expression.kind in ("SEMI", "ANTI"): 2169 side = None 2170 else: 2171 side = expression.side 2172 2173 op_sql = " ".join( 2174 op 2175 for op in ( 2176 expression.method, 2177 "GLOBAL" if expression.args.get("global") else None, 2178 side, 2179 expression.kind, 2180 expression.hint if self.JOIN_HINTS else None, 2181 ) 2182 if op 2183 ) 2184 match_cond = self.sql(expression, "match_condition") 2185 match_cond = f" MATCH_CONDITION ({match_cond})" if match_cond else "" 2186 on_sql = self.sql(expression, "on") 2187 using = expression.args.get("using") 2188 2189 if not on_sql and using: 2190 on_sql = csv(*(self.sql(column) for column in using)) 2191 2192 this = expression.this 2193 this_sql = self.sql(this) 2194 2195 exprs = self.expressions(expression) 2196 if exprs: 2197 this_sql = f"{this_sql},{self.seg(exprs)}" 2198 2199 if on_sql: 2200 on_sql = self.indent(on_sql, skip_first=True) 2201 space = self.seg(" " * self.pad) if self.pretty else " " 2202 if using: 2203 on_sql = f"{space}USING ({on_sql})" 2204 else: 2205 on_sql = f"{space}ON {on_sql}" 2206 elif not op_sql: 2207 if isinstance(this, exp.Lateral) and this.args.get("cross_apply") is not None: 2208 return f" {this_sql}" 2209 2210 return f", {this_sql}" 2211 2212 if op_sql != "STRAIGHT_JOIN": 2213 op_sql = f"{op_sql} JOIN" if op_sql else "JOIN" 2214 2215 return f"{self.seg(op_sql)} {this_sql}{match_cond}{on_sql}"
2222 def lateral_op(self, expression: exp.Lateral) -> str: 2223 cross_apply = expression.args.get("cross_apply") 2224 2225 # https://www.mssqltips.com/sqlservertip/1958/sql-server-cross-apply-and-outer-apply/ 2226 if cross_apply is True: 2227 op = "INNER JOIN " 2228 elif cross_apply is False: 2229 op = "LEFT JOIN " 2230 else: 2231 op = "" 2232 2233 return f"{op}LATERAL"
2235 def lateral_sql(self, expression: exp.Lateral) -> str: 2236 this = self.sql(expression, "this") 2237 2238 if expression.args.get("view"): 2239 alias = expression.args["alias"] 2240 columns = self.expressions(alias, key="columns", flat=True) 2241 table = f" {alias.name}" if alias.name else "" 2242 columns = f" AS {columns}" if columns else "" 2243 op_sql = self.seg(f"LATERAL VIEW{' OUTER' if expression.args.get('outer') else ''}") 2244 return f"{op_sql}{self.sep()}{this}{table}{columns}" 2245 2246 alias = self.sql(expression, "alias") 2247 alias = f" AS {alias}" if alias else "" 2248 return f"{self.lateral_op(expression)} {this}{alias}"
2250 def limit_sql(self, expression: exp.Limit, top: bool = False) -> str: 2251 this = self.sql(expression, "this") 2252 2253 args = [ 2254 self._simplify_unless_literal(e) if self.LIMIT_ONLY_LITERALS else e 2255 for e in (expression.args.get(k) for k in ("offset", "expression")) 2256 if e 2257 ] 2258 2259 args_sql = ", ".join(self.sql(e) for e in args) 2260 args_sql = f"({args_sql})" if top and any(not e.is_number for e in args) else args_sql 2261 expressions = self.expressions(expression, flat=True) 2262 expressions = f" BY {expressions}" if expressions else "" 2263 2264 return f"{this}{self.seg('TOP' if top else 'LIMIT')} {args_sql}{expressions}"
2266 def offset_sql(self, expression: exp.Offset) -> str: 2267 this = self.sql(expression, "this") 2268 value = expression.expression 2269 value = self._simplify_unless_literal(value) if self.LIMIT_ONLY_LITERALS else value 2270 expressions = self.expressions(expression, flat=True) 2271 expressions = f" BY {expressions}" if expressions else "" 2272 return f"{this}{self.seg('OFFSET')} {self.sql(value)}{expressions}"
2274 def setitem_sql(self, expression: exp.SetItem) -> str: 2275 kind = self.sql(expression, "kind") 2276 kind = f"{kind} " if kind else "" 2277 this = self.sql(expression, "this") 2278 expressions = self.expressions(expression) 2279 collate = self.sql(expression, "collate") 2280 collate = f" COLLATE {collate}" if collate else "" 2281 global_ = "GLOBAL " if expression.args.get("global") else "" 2282 return f"{global_}{kind}{this}{expressions}{collate}"
2284 def set_sql(self, expression: exp.Set) -> str: 2285 expressions = ( 2286 f" {self.expressions(expression, flat=True)}" if expression.expressions else "" 2287 ) 2288 tag = " TAG" if expression.args.get("tag") else "" 2289 return f"{'UNSET' if expression.args.get('unset') else 'SET'}{tag}{expressions}"
2294 def lock_sql(self, expression: exp.Lock) -> str: 2295 if not self.LOCKING_READS_SUPPORTED: 2296 self.unsupported("Locking reads using 'FOR UPDATE/SHARE' are not supported") 2297 return "" 2298 2299 lock_type = "FOR UPDATE" if expression.args["update"] else "FOR SHARE" 2300 expressions = self.expressions(expression, flat=True) 2301 expressions = f" OF {expressions}" if expressions else "" 2302 wait = expression.args.get("wait") 2303 2304 if wait is not None: 2305 if isinstance(wait, exp.Literal): 2306 wait = f" WAIT {self.sql(wait)}" 2307 else: 2308 wait = " NOWAIT" if wait else " SKIP LOCKED" 2309 2310 return f"{lock_type}{expressions}{wait or ''}"
def
escape_str(self, text: str, escape_backslash: bool = True) -> str:
2318 def escape_str(self, text: str, escape_backslash: bool = True) -> str: 2319 if self.dialect.ESCAPED_SEQUENCES: 2320 to_escaped = self.dialect.ESCAPED_SEQUENCES 2321 text = "".join( 2322 to_escaped.get(ch, ch) if escape_backslash or ch != "\\" else ch for ch in text 2323 ) 2324 2325 return self._replace_line_breaks(text).replace( 2326 self.dialect.QUOTE_END, self._escaped_quote_end 2327 )
2329 def loaddata_sql(self, expression: exp.LoadData) -> str: 2330 local = " LOCAL" if expression.args.get("local") else "" 2331 inpath = f" INPATH {self.sql(expression, 'inpath')}" 2332 overwrite = " OVERWRITE" if expression.args.get("overwrite") else "" 2333 this = f" INTO TABLE {self.sql(expression, 'this')}" 2334 partition = self.sql(expression, "partition") 2335 partition = f" {partition}" if partition else "" 2336 input_format = self.sql(expression, "input_format") 2337 input_format = f" INPUTFORMAT {input_format}" if input_format else "" 2338 serde = self.sql(expression, "serde") 2339 serde = f" SERDE {serde}" if serde else "" 2340 return f"LOAD DATA{local}{inpath}{overwrite}{this}{partition}{input_format}{serde}"
2348 def order_sql(self, expression: exp.Order, flat: bool = False) -> str: 2349 this = self.sql(expression, "this") 2350 this = f"{this} " if this else this 2351 siblings = "SIBLINGS " if expression.args.get("siblings") else "" 2352 return self.op_expressions(f"{this}ORDER {siblings}BY", expression, flat=this or flat) # type: ignore
2354 def withfill_sql(self, expression: exp.WithFill) -> str: 2355 from_sql = self.sql(expression, "from") 2356 from_sql = f" FROM {from_sql}" if from_sql else "" 2357 to_sql = self.sql(expression, "to") 2358 to_sql = f" TO {to_sql}" if to_sql else "" 2359 step_sql = self.sql(expression, "step") 2360 step_sql = f" STEP {step_sql}" if step_sql else "" 2361 interpolated_values = [ 2362 f"{self.sql(e, 'alias')} AS {self.sql(e, 'this')}" 2363 if isinstance(e, exp.Alias) 2364 else self.sql(e, "this") 2365 for e in expression.args.get("interpolate") or [] 2366 ] 2367 interpolate = ( 2368 f" INTERPOLATE ({', '.join(interpolated_values)})" if interpolated_values else "" 2369 ) 2370 return f"WITH FILL{from_sql}{to_sql}{step_sql}{interpolate}"
2381 def ordered_sql(self, expression: exp.Ordered) -> str: 2382 desc = expression.args.get("desc") 2383 asc = not desc 2384 2385 nulls_first = expression.args.get("nulls_first") 2386 nulls_last = not nulls_first 2387 nulls_are_large = self.dialect.NULL_ORDERING == "nulls_are_large" 2388 nulls_are_small = self.dialect.NULL_ORDERING == "nulls_are_small" 2389 nulls_are_last = self.dialect.NULL_ORDERING == "nulls_are_last" 2390 2391 this = self.sql(expression, "this") 2392 2393 sort_order = " DESC" if desc else (" ASC" if desc is False else "") 2394 nulls_sort_change = "" 2395 if nulls_first and ( 2396 (asc and nulls_are_large) or (desc and nulls_are_small) or nulls_are_last 2397 ): 2398 nulls_sort_change = " NULLS FIRST" 2399 elif ( 2400 nulls_last 2401 and ((asc and nulls_are_small) or (desc and nulls_are_large)) 2402 and not nulls_are_last 2403 ): 2404 nulls_sort_change = " NULLS LAST" 2405 2406 # If the NULLS FIRST/LAST clause is unsupported, we add another sort key to simulate it 2407 if nulls_sort_change and not self.NULL_ORDERING_SUPPORTED: 2408 window = expression.find_ancestor(exp.Window, exp.Select) 2409 if isinstance(window, exp.Window) and window.args.get("spec"): 2410 self.unsupported( 2411 f"'{nulls_sort_change.strip()}' translation not supported in window functions" 2412 ) 2413 nulls_sort_change = "" 2414 elif self.NULL_ORDERING_SUPPORTED is False and ( 2415 (asc and nulls_sort_change == " NULLS LAST") 2416 or (desc and nulls_sort_change == " NULLS FIRST") 2417 ): 2418 # BigQuery does not allow these ordering/nulls combinations when used under 2419 # an aggregation func or under a window containing one 2420 ancestor = expression.find_ancestor(exp.AggFunc, exp.Window, exp.Select) 2421 2422 if isinstance(ancestor, exp.Window): 2423 ancestor = ancestor.this 2424 if isinstance(ancestor, exp.AggFunc): 2425 self.unsupported( 2426 f"'{nulls_sort_change.strip()}' translation not supported for aggregate functions with {sort_order} sort order" 2427 ) 2428 nulls_sort_change = "" 2429 elif self.NULL_ORDERING_SUPPORTED is None: 2430 if expression.this.is_int: 2431 self.unsupported( 2432 f"'{nulls_sort_change.strip()}' translation not supported with positional ordering" 2433 ) 2434 elif not isinstance(expression.this, exp.Rand): 2435 null_sort_order = " DESC" if nulls_sort_change == " NULLS FIRST" else "" 2436 this = f"CASE WHEN {this} IS NULL THEN 1 ELSE 0 END{null_sort_order}, {this}" 2437 nulls_sort_change = "" 2438 2439 with_fill = self.sql(expression, "with_fill") 2440 with_fill = f" {with_fill}" if with_fill else "" 2441 2442 return f"{this}{sort_order}{nulls_sort_change}{with_fill}"
2452 def matchrecognize_sql(self, expression: exp.MatchRecognize) -> str: 2453 partition = self.partition_by_sql(expression) 2454 order = self.sql(expression, "order") 2455 measures = self.expressions(expression, key="measures") 2456 measures = self.seg(f"MEASURES{self.seg(measures)}") if measures else "" 2457 rows = self.sql(expression, "rows") 2458 rows = self.seg(rows) if rows else "" 2459 after = self.sql(expression, "after") 2460 after = self.seg(after) if after else "" 2461 pattern = self.sql(expression, "pattern") 2462 pattern = self.seg(f"PATTERN ({pattern})") if pattern else "" 2463 definition_sqls = [ 2464 f"{self.sql(definition, 'alias')} AS {self.sql(definition, 'this')}" 2465 for definition in expression.args.get("define", []) 2466 ] 2467 definitions = self.expressions(sqls=definition_sqls) 2468 define = self.seg(f"DEFINE{self.seg(definitions)}") if definitions else "" 2469 body = "".join( 2470 ( 2471 partition, 2472 order, 2473 measures, 2474 rows, 2475 after, 2476 pattern, 2477 define, 2478 ) 2479 ) 2480 alias = self.sql(expression, "alias") 2481 alias = f" {alias}" if alias else "" 2482 return f"{self.seg('MATCH_RECOGNIZE')} {self.wrap(body)}{alias}"
2484 def query_modifiers(self, expression: exp.Expression, *sqls: str) -> str: 2485 limit = expression.args.get("limit") 2486 2487 if self.LIMIT_FETCH == "LIMIT" and isinstance(limit, exp.Fetch): 2488 limit = exp.Limit(expression=exp.maybe_copy(limit.args.get("count"))) 2489 elif self.LIMIT_FETCH == "FETCH" and isinstance(limit, exp.Limit): 2490 limit = exp.Fetch(direction="FIRST", count=exp.maybe_copy(limit.expression)) 2491 2492 return csv( 2493 *sqls, 2494 *[self.sql(join) for join in expression.args.get("joins") or []], 2495 self.sql(expression, "connect"), 2496 self.sql(expression, "match"), 2497 *[self.sql(lateral) for lateral in expression.args.get("laterals") or []], 2498 self.sql(expression, "prewhere"), 2499 self.sql(expression, "where"), 2500 self.sql(expression, "group"), 2501 self.sql(expression, "having"), 2502 *[gen(self, expression) for gen in self.AFTER_HAVING_MODIFIER_TRANSFORMS.values()], 2503 self.sql(expression, "order"), 2504 *self.offset_limit_modifiers(expression, isinstance(limit, exp.Fetch), limit), 2505 *self.after_limit_modifiers(expression), 2506 self.options_modifier(expression), 2507 sep="", 2508 )
def
offset_limit_modifiers( self, expression: sqlglot.expressions.Expression, fetch: bool, limit: Union[sqlglot.expressions.Fetch, sqlglot.expressions.Limit, NoneType]) -> List[str]:
2517 def offset_limit_modifiers( 2518 self, expression: exp.Expression, fetch: bool, limit: t.Optional[exp.Fetch | exp.Limit] 2519 ) -> t.List[str]: 2520 return [ 2521 self.sql(expression, "offset") if fetch else self.sql(limit), 2522 self.sql(limit) if fetch else self.sql(expression, "offset"), 2523 ]
2530 def select_sql(self, expression: exp.Select) -> str: 2531 into = expression.args.get("into") 2532 if not self.SUPPORTS_SELECT_INTO and into: 2533 into.pop() 2534 2535 hint = self.sql(expression, "hint") 2536 distinct = self.sql(expression, "distinct") 2537 distinct = f" {distinct}" if distinct else "" 2538 kind = self.sql(expression, "kind") 2539 2540 limit = expression.args.get("limit") 2541 if isinstance(limit, exp.Limit) and self.LIMIT_IS_TOP: 2542 top = self.limit_sql(limit, top=True) 2543 limit.pop() 2544 else: 2545 top = "" 2546 2547 expressions = self.expressions(expression) 2548 2549 if kind: 2550 if kind in self.SELECT_KINDS: 2551 kind = f" AS {kind}" 2552 else: 2553 if kind == "STRUCT": 2554 expressions = self.expressions( 2555 sqls=[ 2556 self.sql( 2557 exp.Struct( 2558 expressions=[ 2559 exp.PropertyEQ(this=e.args.get("alias"), expression=e.this) 2560 if isinstance(e, exp.Alias) 2561 else e 2562 for e in expression.expressions 2563 ] 2564 ) 2565 ) 2566 ] 2567 ) 2568 kind = "" 2569 2570 operation_modifiers = self.expressions(expression, key="operation_modifiers", sep=" ") 2571 operation_modifiers = f"{self.sep()}{operation_modifiers}" if operation_modifiers else "" 2572 2573 # We use LIMIT_IS_TOP as a proxy for whether DISTINCT should go first because tsql and Teradata 2574 # are the only dialects that use LIMIT_IS_TOP and both place DISTINCT first. 2575 top_distinct = f"{distinct}{hint}{top}" if self.LIMIT_IS_TOP else f"{top}{hint}{distinct}" 2576 expressions = f"{self.sep()}{expressions}" if expressions else expressions 2577 sql = self.query_modifiers( 2578 expression, 2579 f"SELECT{top_distinct}{operation_modifiers}{kind}{expressions}", 2580 self.sql(expression, "into", comment=False), 2581 self.sql(expression, "from", comment=False), 2582 ) 2583 2584 # If both the CTE and SELECT clauses have comments, generate the latter earlier 2585 if expression.args.get("with"): 2586 sql = self.maybe_comment(sql, expression) 2587 expression.pop_comments() 2588 2589 sql = self.prepend_ctes(expression, sql) 2590 2591 if not self.SUPPORTS_SELECT_INTO and into: 2592 if into.args.get("temporary"): 2593 table_kind = " TEMPORARY" 2594 elif self.SUPPORTS_UNLOGGED_TABLES and into.args.get("unlogged"): 2595 table_kind = " UNLOGGED" 2596 else: 2597 table_kind = "" 2598 sql = f"CREATE{table_kind} TABLE {self.sql(into.this)} AS {sql}" 2599 2600 return sql
2612 def star_sql(self, expression: exp.Star) -> str: 2613 except_ = self.expressions(expression, key="except", flat=True) 2614 except_ = f"{self.seg(self.STAR_EXCEPT)} ({except_})" if except_ else "" 2615 replace = self.expressions(expression, key="replace", flat=True) 2616 replace = f"{self.seg('REPLACE')} ({replace})" if replace else "" 2617 rename = self.expressions(expression, key="rename", flat=True) 2618 rename = f"{self.seg('RENAME')} ({rename})" if rename else "" 2619 return f"*{except_}{replace}{rename}"
2635 def subquery_sql(self, expression: exp.Subquery, sep: str = " AS ") -> str: 2636 alias = self.sql(expression, "alias") 2637 alias = f"{sep}{alias}" if alias else "" 2638 sample = self.sql(expression, "sample") 2639 if self.dialect.ALIAS_POST_TABLESAMPLE and sample: 2640 alias = f"{sample}{alias}" 2641 2642 # Set to None so it's not generated again by self.query_modifiers() 2643 expression.set("sample", None) 2644 2645 pivots = self.expressions(expression, key="pivots", sep="", flat=True) 2646 sql = self.query_modifiers(expression, self.wrap(expression), alias, pivots) 2647 return self.prepend_ctes(expression, sql)
2653 def unnest_sql(self, expression: exp.Unnest) -> str: 2654 args = self.expressions(expression, flat=True) 2655 2656 alias = expression.args.get("alias") 2657 offset = expression.args.get("offset") 2658 2659 if self.UNNEST_WITH_ORDINALITY: 2660 if alias and isinstance(offset, exp.Expression): 2661 alias.append("columns", offset) 2662 2663 if alias and self.dialect.UNNEST_COLUMN_ONLY: 2664 columns = alias.columns 2665 alias = self.sql(columns[0]) if columns else "" 2666 else: 2667 alias = self.sql(alias) 2668 2669 alias = f" AS {alias}" if alias else alias 2670 if self.UNNEST_WITH_ORDINALITY: 2671 suffix = f" WITH ORDINALITY{alias}" if offset else alias 2672 else: 2673 if isinstance(offset, exp.Expression): 2674 suffix = f"{alias} WITH OFFSET AS {self.sql(offset)}" 2675 elif offset: 2676 suffix = f"{alias} WITH OFFSET" 2677 else: 2678 suffix = alias 2679 2680 return f"UNNEST({args}){suffix}"
2689 def window_sql(self, expression: exp.Window) -> str: 2690 this = self.sql(expression, "this") 2691 partition = self.partition_by_sql(expression) 2692 order = expression.args.get("order") 2693 order = self.order_sql(order, flat=True) if order else "" 2694 spec = self.sql(expression, "spec") 2695 alias = self.sql(expression, "alias") 2696 over = self.sql(expression, "over") or "OVER" 2697 2698 this = f"{this} {'AS' if expression.arg_key == 'windows' else over}" 2699 2700 first = expression.args.get("first") 2701 if first is None: 2702 first = "" 2703 else: 2704 first = "FIRST" if first else "LAST" 2705 2706 if not partition and not order and not spec and alias: 2707 return f"{this} {alias}" 2708 2709 args = " ".join(arg for arg in (alias, first, partition, order, spec) if arg) 2710 return f"{this} ({args})"
def
partition_by_sql( self, expression: sqlglot.expressions.Window | sqlglot.expressions.MatchRecognize) -> str:
2716 def windowspec_sql(self, expression: exp.WindowSpec) -> str: 2717 kind = self.sql(expression, "kind") 2718 start = csv(self.sql(expression, "start"), self.sql(expression, "start_side"), sep=" ") 2719 end = ( 2720 csv(self.sql(expression, "end"), self.sql(expression, "end_side"), sep=" ") 2721 or "CURRENT ROW" 2722 ) 2723 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]:
2736 def bracket_offset_expressions( 2737 self, expression: exp.Bracket, index_offset: t.Optional[int] = None 2738 ) -> t.List[exp.Expression]: 2739 return apply_index_offset( 2740 expression.this, 2741 expression.expressions, 2742 (index_offset or self.dialect.INDEX_OFFSET) - expression.args.get("offset", 0), 2743 )
2753 def any_sql(self, expression: exp.Any) -> str: 2754 this = self.sql(expression, "this") 2755 if isinstance(expression.this, (*exp.UNWRAPPED_QUERIES, exp.Paren)): 2756 if isinstance(expression.this, exp.UNWRAPPED_QUERIES): 2757 this = self.wrap(this) 2758 return f"ANY{this}" 2759 return f"ANY {this}"
2764 def case_sql(self, expression: exp.Case) -> str: 2765 this = self.sql(expression, "this") 2766 statements = [f"CASE {this}" if this else "CASE"] 2767 2768 for e in expression.args["ifs"]: 2769 statements.append(f"WHEN {self.sql(e, 'this')}") 2770 statements.append(f"THEN {self.sql(e, 'true')}") 2771 2772 default = self.sql(expression, "default") 2773 2774 if default: 2775 statements.append(f"ELSE {default}") 2776 2777 statements.append("END") 2778 2779 if self.pretty and self.too_wide(statements): 2780 return self.indent("\n".join(statements), skip_first=True, skip_last=True) 2781 2782 return " ".join(statements)
2799 def trim_sql(self, expression: exp.Trim) -> str: 2800 trim_type = self.sql(expression, "position") 2801 2802 if trim_type == "LEADING": 2803 func_name = "LTRIM" 2804 elif trim_type == "TRAILING": 2805 func_name = "RTRIM" 2806 else: 2807 func_name = "TRIM" 2808 2809 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]:
2811 def convert_concat_args(self, expression: exp.Concat | exp.ConcatWs) -> t.List[exp.Expression]: 2812 args = expression.expressions 2813 if isinstance(expression, exp.ConcatWs): 2814 args = args[1:] # Skip the delimiter 2815 2816 if self.dialect.STRICT_STRING_CONCAT and expression.args.get("safe"): 2817 args = [exp.cast(e, exp.DataType.Type.TEXT) for e in args] 2818 2819 if not self.dialect.CONCAT_COALESCE and expression.args.get("coalesce"): 2820 args = [exp.func("coalesce", e, exp.Literal.string("")) for e in args] 2821 2822 return args
2824 def concat_sql(self, expression: exp.Concat) -> str: 2825 expressions = self.convert_concat_args(expression) 2826 2827 # Some dialects don't allow a single-argument CONCAT call 2828 if not self.SUPPORTS_SINGLE_ARG_CONCAT and len(expressions) == 1: 2829 return self.sql(expressions[0]) 2830 2831 return self.func("CONCAT", *expressions)
2842 def foreignkey_sql(self, expression: exp.ForeignKey) -> str: 2843 expressions = self.expressions(expression, flat=True) 2844 expressions = f" ({expressions})" if expressions else "" 2845 reference = self.sql(expression, "reference") 2846 reference = f" {reference}" if reference else "" 2847 delete = self.sql(expression, "delete") 2848 delete = f" ON DELETE {delete}" if delete else "" 2849 update = self.sql(expression, "update") 2850 update = f" ON UPDATE {update}" if update else "" 2851 return f"FOREIGN KEY{expressions}{reference}{delete}{update}"
2853 def primarykey_sql(self, expression: exp.ForeignKey) -> str: 2854 expressions = self.expressions(expression, flat=True) 2855 options = self.expressions(expression, key="options", flat=True, sep=" ") 2856 options = f" {options}" if options else "" 2857 return f"PRIMARY KEY ({expressions}){options}"
2870 def jsonpath_sql(self, expression: exp.JSONPath) -> str: 2871 path = self.expressions(expression, sep="", flat=True).lstrip(".") 2872 2873 if expression.args.get("escape"): 2874 path = self.escape_str(path) 2875 2876 if self.QUOTE_JSON_PATH: 2877 path = f"{self.dialect.QUOTE_START}{path}{self.dialect.QUOTE_END}" 2878 2879 return path
2881 def json_path_part(self, expression: int | str | exp.JSONPathPart) -> str: 2882 if isinstance(expression, exp.JSONPathPart): 2883 transform = self.TRANSFORMS.get(expression.__class__) 2884 if not callable(transform): 2885 self.unsupported(f"Unsupported JSONPathPart type {expression.__class__.__name__}") 2886 return "" 2887 2888 return transform(self, expression) 2889 2890 if isinstance(expression, int): 2891 return str(expression) 2892 2893 if self._quote_json_path_key_using_brackets and self.JSON_PATH_SINGLE_QUOTE_ESCAPE: 2894 escaped = expression.replace("'", "\\'") 2895 escaped = f"\\'{expression}\\'" 2896 else: 2897 escaped = expression.replace('"', '\\"') 2898 escaped = f'"{escaped}"' 2899 2900 return escaped
def
jsonobject_sql( self, expression: sqlglot.expressions.JSONObject | sqlglot.expressions.JSONObjectAgg) -> str:
2905 def jsonobject_sql(self, expression: exp.JSONObject | exp.JSONObjectAgg) -> str: 2906 null_handling = expression.args.get("null_handling") 2907 null_handling = f" {null_handling}" if null_handling else "" 2908 2909 unique_keys = expression.args.get("unique_keys") 2910 if unique_keys is not None: 2911 unique_keys = f" {'WITH' if unique_keys else 'WITHOUT'} UNIQUE KEYS" 2912 else: 2913 unique_keys = "" 2914 2915 return_type = self.sql(expression, "return_type") 2916 return_type = f" RETURNING {return_type}" if return_type else "" 2917 encoding = self.sql(expression, "encoding") 2918 encoding = f" ENCODING {encoding}" if encoding else "" 2919 2920 return self.func( 2921 "JSON_OBJECT" if isinstance(expression, exp.JSONObject) else "JSON_OBJECTAGG", 2922 *expression.expressions, 2923 suffix=f"{null_handling}{unique_keys}{return_type}{encoding})", 2924 )
2929 def jsonarray_sql(self, expression: exp.JSONArray) -> str: 2930 null_handling = expression.args.get("null_handling") 2931 null_handling = f" {null_handling}" if null_handling else "" 2932 return_type = self.sql(expression, "return_type") 2933 return_type = f" RETURNING {return_type}" if return_type else "" 2934 strict = " STRICT" if expression.args.get("strict") else "" 2935 return self.func( 2936 "JSON_ARRAY", *expression.expressions, suffix=f"{null_handling}{return_type}{strict})" 2937 )
2939 def jsonarrayagg_sql(self, expression: exp.JSONArrayAgg) -> str: 2940 this = self.sql(expression, "this") 2941 order = self.sql(expression, "order") 2942 null_handling = expression.args.get("null_handling") 2943 null_handling = f" {null_handling}" if null_handling else "" 2944 return_type = self.sql(expression, "return_type") 2945 return_type = f" RETURNING {return_type}" if return_type else "" 2946 strict = " STRICT" if expression.args.get("strict") else "" 2947 return self.func( 2948 "JSON_ARRAYAGG", 2949 this, 2950 suffix=f"{order}{null_handling}{return_type}{strict})", 2951 )
2953 def jsoncolumndef_sql(self, expression: exp.JSONColumnDef) -> str: 2954 path = self.sql(expression, "path") 2955 path = f" PATH {path}" if path else "" 2956 nested_schema = self.sql(expression, "nested_schema") 2957 2958 if nested_schema: 2959 return f"NESTED{path} {nested_schema}" 2960 2961 this = self.sql(expression, "this") 2962 kind = self.sql(expression, "kind") 2963 kind = f" {kind}" if kind else "" 2964 return f"{this}{kind}{path}"
2969 def jsontable_sql(self, expression: exp.JSONTable) -> str: 2970 this = self.sql(expression, "this") 2971 path = self.sql(expression, "path") 2972 path = f", {path}" if path else "" 2973 error_handling = expression.args.get("error_handling") 2974 error_handling = f" {error_handling}" if error_handling else "" 2975 empty_handling = expression.args.get("empty_handling") 2976 empty_handling = f" {empty_handling}" if empty_handling else "" 2977 schema = self.sql(expression, "schema") 2978 return self.func( 2979 "JSON_TABLE", this, suffix=f"{path}{error_handling}{empty_handling} {schema})" 2980 )
2982 def openjsoncolumndef_sql(self, expression: exp.OpenJSONColumnDef) -> str: 2983 this = self.sql(expression, "this") 2984 kind = self.sql(expression, "kind") 2985 path = self.sql(expression, "path") 2986 path = f" {path}" if path else "" 2987 as_json = " AS JSON" if expression.args.get("as_json") else "" 2988 return f"{this} {kind}{path}{as_json}"
2990 def openjson_sql(self, expression: exp.OpenJSON) -> str: 2991 this = self.sql(expression, "this") 2992 path = self.sql(expression, "path") 2993 path = f", {path}" if path else "" 2994 expressions = self.expressions(expression) 2995 with_ = ( 2996 f" WITH ({self.seg(self.indent(expressions), sep='')}{self.seg(')', sep='')}" 2997 if expressions 2998 else "" 2999 ) 3000 return f"OPENJSON({this}{path}){with_}"
3002 def in_sql(self, expression: exp.In) -> str: 3003 query = expression.args.get("query") 3004 unnest = expression.args.get("unnest") 3005 field = expression.args.get("field") 3006 is_global = " GLOBAL" if expression.args.get("is_global") else "" 3007 3008 if query: 3009 in_sql = self.sql(query) 3010 elif unnest: 3011 in_sql = self.in_unnest_op(unnest) 3012 elif field: 3013 in_sql = self.sql(field) 3014 else: 3015 in_sql = f"({self.expressions(expression, flat=True)})" 3016 3017 return f"{self.sql(expression, 'this')}{is_global} IN {in_sql}"
3022 def interval_sql(self, expression: exp.Interval) -> str: 3023 unit = self.sql(expression, "unit") 3024 if not self.INTERVAL_ALLOWS_PLURAL_FORM: 3025 unit = self.TIME_PART_SINGULARS.get(unit, unit) 3026 unit = f" {unit}" if unit else "" 3027 3028 if self.SINGLE_STRING_INTERVAL: 3029 this = expression.this.name if expression.this else "" 3030 return f"INTERVAL '{this}{unit}'" if this else f"INTERVAL{unit}" 3031 3032 this = self.sql(expression, "this") 3033 if this: 3034 unwrapped = isinstance(expression.this, self.UNWRAPPED_INTERVAL_VALUES) 3035 this = f" {this}" if unwrapped else f" ({this})" 3036 3037 return f"INTERVAL{this}{unit}"
3042 def reference_sql(self, expression: exp.Reference) -> str: 3043 this = self.sql(expression, "this") 3044 expressions = self.expressions(expression, flat=True) 3045 expressions = f"({expressions})" if expressions else "" 3046 options = self.expressions(expression, key="options", flat=True, sep=" ") 3047 options = f" {options}" if options else "" 3048 return f"REFERENCES {this}{expressions}{options}"
3050 def anonymous_sql(self, expression: exp.Anonymous) -> str: 3051 # We don't normalize qualified functions such as a.b.foo(), because they can be case-sensitive 3052 parent = expression.parent 3053 is_qualified = isinstance(parent, exp.Dot) and expression is parent.expression 3054 return self.func( 3055 self.sql(expression, "this"), *expression.expressions, normalize=not is_qualified 3056 )
3076 def pivotalias_sql(self, expression: exp.PivotAlias) -> str: 3077 alias = expression.args["alias"] 3078 3079 identifier_alias = isinstance(alias, exp.Identifier) 3080 literal_alias = isinstance(alias, exp.Literal) 3081 3082 if identifier_alias and not self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3083 alias.replace(exp.Literal.string(alias.output_name)) 3084 elif not identifier_alias and literal_alias and self.UNPIVOT_ALIASES_ARE_IDENTIFIERS: 3085 alias.replace(exp.to_identifier(alias.output_name)) 3086 3087 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:
3125 def connector_sql( 3126 self, 3127 expression: exp.Connector, 3128 op: str, 3129 stack: t.Optional[t.List[str | exp.Expression]] = None, 3130 ) -> str: 3131 if stack is not None: 3132 if expression.expressions: 3133 stack.append(self.expressions(expression, sep=f" {op} ")) 3134 else: 3135 stack.append(expression.right) 3136 if expression.comments and self.comments: 3137 for comment in expression.comments: 3138 if comment: 3139 op += f" /*{self.pad_comment(comment)}*/" 3140 stack.extend((op, expression.left)) 3141 return op 3142 3143 stack = [expression] 3144 sqls: t.List[str] = [] 3145 ops = set() 3146 3147 while stack: 3148 node = stack.pop() 3149 if isinstance(node, exp.Connector): 3150 ops.add(getattr(self, f"{node.key}_sql")(node, stack)) 3151 else: 3152 sql = self.sql(node) 3153 if sqls and sqls[-1] in ops: 3154 sqls[-1] += f" {sql}" 3155 else: 3156 sqls.append(sql) 3157 3158 sep = "\n" if self.pretty and self.too_wide(sqls) else " " 3159 return sep.join(sqls)
def
cast_sql( self, expression: sqlglot.expressions.Cast, safe_prefix: Optional[str] = None) -> str:
3179 def cast_sql(self, expression: exp.Cast, safe_prefix: t.Optional[str] = None) -> str: 3180 format_sql = self.sql(expression, "format") 3181 format_sql = f" FORMAT {format_sql}" if format_sql else "" 3182 to_sql = self.sql(expression, "to") 3183 to_sql = f" {to_sql}" if to_sql else "" 3184 action = self.sql(expression, "action") 3185 action = f" {action}" if action else "" 3186 return f"{safe_prefix or ''}CAST({self.sql(expression, 'this')} AS{to_sql}{format_sql}{action})"
3200 def comment_sql(self, expression: exp.Comment) -> str: 3201 this = self.sql(expression, "this") 3202 kind = expression.args["kind"] 3203 materialized = " MATERIALIZED" if expression.args.get("materialized") else "" 3204 exists_sql = " IF EXISTS " if expression.args.get("exists") else " " 3205 expression_sql = self.sql(expression, "expression") 3206 return f"COMMENT{exists_sql}ON{materialized} {kind} {this} IS {expression_sql}"
3208 def mergetreettlaction_sql(self, expression: exp.MergeTreeTTLAction) -> str: 3209 this = self.sql(expression, "this") 3210 delete = " DELETE" if expression.args.get("delete") else "" 3211 recompress = self.sql(expression, "recompress") 3212 recompress = f" RECOMPRESS {recompress}" if recompress else "" 3213 to_disk = self.sql(expression, "to_disk") 3214 to_disk = f" TO DISK {to_disk}" if to_disk else "" 3215 to_volume = self.sql(expression, "to_volume") 3216 to_volume = f" TO VOLUME {to_volume}" if to_volume else "" 3217 return f"{this}{delete}{recompress}{to_disk}{to_volume}"
3219 def mergetreettl_sql(self, expression: exp.MergeTreeTTL) -> str: 3220 where = self.sql(expression, "where") 3221 group = self.sql(expression, "group") 3222 aggregates = self.expressions(expression, key="aggregates") 3223 aggregates = self.seg("SET") + self.seg(aggregates) if aggregates else "" 3224 3225 if not (where or group or aggregates) and len(expression.expressions) == 1: 3226 return f"TTL {self.expressions(expression, flat=True)}" 3227 3228 return f"TTL{self.seg(self.expressions(expression))}{where}{group}{aggregates}"
3245 def altercolumn_sql(self, expression: exp.AlterColumn) -> str: 3246 this = self.sql(expression, "this") 3247 3248 dtype = self.sql(expression, "dtype") 3249 if dtype: 3250 collate = self.sql(expression, "collate") 3251 collate = f" COLLATE {collate}" if collate else "" 3252 using = self.sql(expression, "using") 3253 using = f" USING {using}" if using else "" 3254 return f"ALTER COLUMN {this} SET DATA TYPE {dtype}{collate}{using}" 3255 3256 default = self.sql(expression, "default") 3257 if default: 3258 return f"ALTER COLUMN {this} SET DEFAULT {default}" 3259 3260 comment = self.sql(expression, "comment") 3261 if comment: 3262 return f"ALTER COLUMN {this} COMMENT {comment}" 3263 3264 allow_null = expression.args.get("allow_null") 3265 drop = expression.args.get("drop") 3266 3267 if not drop and not allow_null: 3268 self.unsupported("Unsupported ALTER COLUMN syntax") 3269 3270 if allow_null is not None: 3271 keyword = "DROP" if drop else "SET" 3272 return f"ALTER COLUMN {this} {keyword} NOT NULL" 3273 3274 return f"ALTER COLUMN {this} DROP DEFAULT"
3282 def altersortkey_sql(self, expression: exp.AlterSortKey) -> str: 3283 compound = " COMPOUND" if expression.args.get("compound") else "" 3284 this = self.sql(expression, "this") 3285 expressions = self.expressions(expression, flat=True) 3286 expressions = f"({expressions})" if expressions else "" 3287 return f"ALTER{compound} SORTKEY {this or expressions}"
3289 def alterrename_sql(self, expression: exp.AlterRename) -> str: 3290 if not self.RENAME_TABLE_WITH_DB: 3291 # Remove db from tables 3292 expression = expression.transform( 3293 lambda n: exp.table_(n.this) if isinstance(n, exp.Table) else n 3294 ).assert_is(exp.AlterRename) 3295 this = self.sql(expression, "this") 3296 return f"RENAME TO {this}"
3308 def alter_sql(self, expression: exp.Alter) -> str: 3309 actions = expression.args["actions"] 3310 3311 if isinstance(actions[0], exp.ColumnDef): 3312 actions = self.add_column_sql(expression) 3313 elif isinstance(actions[0], exp.Schema): 3314 actions = self.expressions(expression, key="actions", prefix="ADD COLUMNS ") 3315 elif isinstance(actions[0], exp.Delete): 3316 actions = self.expressions(expression, key="actions", flat=True) 3317 elif isinstance(actions[0], exp.Query): 3318 actions = "AS " + self.expressions(expression, key="actions") 3319 else: 3320 actions = self.expressions(expression, key="actions", flat=True) 3321 3322 exists = " IF EXISTS" if expression.args.get("exists") else "" 3323 on_cluster = self.sql(expression, "cluster") 3324 on_cluster = f" {on_cluster}" if on_cluster else "" 3325 only = " ONLY" if expression.args.get("only") else "" 3326 options = self.expressions(expression, key="options") 3327 options = f", {options}" if options else "" 3328 kind = self.sql(expression, "kind") 3329 not_valid = " NOT VALID" if expression.args.get("not_valid") else "" 3330 3331 return f"ALTER {kind}{exists}{only} {self.sql(expression, 'this')}{on_cluster} {actions}{not_valid}{options}"
3333 def add_column_sql(self, expression: exp.Alter) -> str: 3334 if self.ALTER_TABLE_INCLUDE_COLUMN_KEYWORD: 3335 return self.expressions( 3336 expression, 3337 key="actions", 3338 prefix="ADD COLUMN ", 3339 skip_first=True, 3340 ) 3341 return f"ADD {self.expressions(expression, key='actions', flat=True)}"
3351 def distinct_sql(self, expression: exp.Distinct) -> str: 3352 this = self.expressions(expression, flat=True) 3353 3354 if not self.MULTI_ARG_DISTINCT and len(expression.expressions) > 1: 3355 case = exp.case() 3356 for arg in expression.expressions: 3357 case = case.when(arg.is_(exp.null()), exp.null()) 3358 this = self.sql(case.else_(f"({this})")) 3359 3360 this = f" {this}" if this else "" 3361 3362 on = self.sql(expression, "on") 3363 on = f" ON {on}" if on else "" 3364 return f"DISTINCT{this}{on}"
3393 def div_sql(self, expression: exp.Div) -> str: 3394 l, r = expression.left, expression.right 3395 3396 if not self.dialect.SAFE_DIVISION and expression.args.get("safe"): 3397 r.replace(exp.Nullif(this=r.copy(), expression=exp.Literal.number(0))) 3398 3399 if self.dialect.TYPED_DIVISION and not expression.args.get("typed"): 3400 if not l.is_type(*exp.DataType.REAL_TYPES) and not r.is_type(*exp.DataType.REAL_TYPES): 3401 l.replace(exp.cast(l.copy(), to=exp.DataType.Type.DOUBLE)) 3402 3403 elif not self.dialect.TYPED_DIVISION and expression.args.get("typed"): 3404 if l.is_type(*exp.DataType.INTEGER_TYPES) and r.is_type(*exp.DataType.INTEGER_TYPES): 3405 return self.sql( 3406 exp.cast( 3407 l / r, 3408 to=exp.DataType.Type.BIGINT, 3409 ) 3410 ) 3411 3412 return self.binary(expression, "/")
3500 def log_sql(self, expression: exp.Log) -> str: 3501 this = expression.this 3502 expr = expression.expression 3503 3504 if self.dialect.LOG_BASE_FIRST is False: 3505 this, expr = expr, this 3506 elif self.dialect.LOG_BASE_FIRST is None and expr: 3507 if this.name in ("2", "10"): 3508 return self.func(f"LOG{this.name}", expr) 3509 3510 self.unsupported(f"Unsupported logarithm with base {self.sql(this)}") 3511 3512 return self.func("LOG", this, expr)
3521 def binary(self, expression: exp.Binary, op: str) -> str: 3522 sqls: t.List[str] = [] 3523 stack: t.List[t.Union[str, exp.Expression]] = [expression] 3524 binary_type = type(expression) 3525 3526 while stack: 3527 node = stack.pop() 3528 3529 if type(node) is binary_type: 3530 op_func = node.args.get("operator") 3531 if op_func: 3532 op = f"OPERATOR({self.sql(op_func)})" 3533 3534 stack.append(node.right) 3535 stack.append(f" {self.maybe_comment(op, comments=node.comments)} ") 3536 stack.append(node.left) 3537 else: 3538 sqls.append(self.sql(node)) 3539 3540 return "".join(sqls)
3549 def function_fallback_sql(self, expression: exp.Func) -> str: 3550 args = [] 3551 3552 for key in expression.arg_types: 3553 arg_value = expression.args.get(key) 3554 3555 if isinstance(arg_value, list): 3556 for value in arg_value: 3557 args.append(value) 3558 elif arg_value is not None: 3559 args.append(arg_value) 3560 3561 if self.dialect.PRESERVE_ORIGINAL_NAMES: 3562 name = (expression._meta and expression.meta.get("name")) or expression.sql_name() 3563 else: 3564 name = expression.sql_name() 3565 3566 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:
3568 def func( 3569 self, 3570 name: str, 3571 *args: t.Optional[exp.Expression | str], 3572 prefix: str = "(", 3573 suffix: str = ")", 3574 normalize: bool = True, 3575 ) -> str: 3576 name = self.normalize_func(name) if normalize else name 3577 return f"{name}{prefix}{self.format_args(*args)}{suffix}"
def
format_args( self, *args: Union[str, sqlglot.expressions.Expression, NoneType], sep: str = ', ') -> str:
3579 def format_args(self, *args: t.Optional[str | exp.Expression], sep: str = ", ") -> str: 3580 arg_sqls = tuple( 3581 self.sql(arg) for arg in args if arg is not None and not isinstance(arg, bool) 3582 ) 3583 if self.pretty and self.too_wide(arg_sqls): 3584 return self.indent( 3585 "\n" + f"{sep.strip()}\n".join(arg_sqls) + "\n", skip_first=True, skip_last=True 3586 ) 3587 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]:
3592 def format_time( 3593 self, 3594 expression: exp.Expression, 3595 inverse_time_mapping: t.Optional[t.Dict[str, str]] = None, 3596 inverse_time_trie: t.Optional[t.Dict] = None, 3597 ) -> t.Optional[str]: 3598 return format_time( 3599 self.sql(expression, "format"), 3600 inverse_time_mapping or self.dialect.INVERSE_TIME_MAPPING, 3601 inverse_time_trie or self.dialect.INVERSE_TIME_TRIE, 3602 )
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:
3604 def expressions( 3605 self, 3606 expression: t.Optional[exp.Expression] = None, 3607 key: t.Optional[str] = None, 3608 sqls: t.Optional[t.Collection[str | exp.Expression]] = None, 3609 flat: bool = False, 3610 indent: bool = True, 3611 skip_first: bool = False, 3612 skip_last: bool = False, 3613 sep: str = ", ", 3614 prefix: str = "", 3615 dynamic: bool = False, 3616 new_line: bool = False, 3617 ) -> str: 3618 expressions = expression.args.get(key or "expressions") if expression else sqls 3619 3620 if not expressions: 3621 return "" 3622 3623 if flat: 3624 return sep.join(sql for sql in (self.sql(e) for e in expressions) if sql) 3625 3626 num_sqls = len(expressions) 3627 result_sqls = [] 3628 3629 for i, e in enumerate(expressions): 3630 sql = self.sql(e, comment=False) 3631 if not sql: 3632 continue 3633 3634 comments = self.maybe_comment("", e) if isinstance(e, exp.Expression) else "" 3635 3636 if self.pretty: 3637 if self.leading_comma: 3638 result_sqls.append(f"{sep if i > 0 else ''}{prefix}{sql}{comments}") 3639 else: 3640 result_sqls.append( 3641 f"{prefix}{sql}{(sep.rstrip() if comments else sep) if i + 1 < num_sqls else ''}{comments}" 3642 ) 3643 else: 3644 result_sqls.append(f"{prefix}{sql}{comments}{sep if i + 1 < num_sqls else ''}") 3645 3646 if self.pretty and (not dynamic or self.too_wide(result_sqls)): 3647 if new_line: 3648 result_sqls.insert(0, "") 3649 result_sqls.append("") 3650 result_sql = "\n".join(s.rstrip() for s in result_sqls) 3651 else: 3652 result_sql = "".join(result_sqls) 3653 3654 return ( 3655 self.indent(result_sql, skip_first=skip_first, skip_last=skip_last) 3656 if indent 3657 else result_sql 3658 )
def
op_expressions( self, op: str, expression: sqlglot.expressions.Expression, flat: bool = False) -> str:
3660 def op_expressions(self, op: str, expression: exp.Expression, flat: bool = False) -> str: 3661 flat = flat or isinstance(expression.parent, exp.Properties) 3662 expressions_sql = self.expressions(expression, flat=flat) 3663 if flat: 3664 return f"{op} {expressions_sql}" 3665 return f"{self.seg(op)}{self.sep() if expressions_sql else ''}{expressions_sql}"
3667 def naked_property(self, expression: exp.Property) -> str: 3668 property_name = exp.Properties.PROPERTY_TO_NAME.get(expression.__class__) 3669 if not property_name: 3670 self.unsupported(f"Unsupported property {expression.__class__.__name__}") 3671 return f"{property_name} {self.sql(expression, 'this')}"
3679 def userdefinedfunction_sql(self, expression: exp.UserDefinedFunction) -> str: 3680 this = self.sql(expression, "this") 3681 expressions = self.no_identify(self.expressions, expression) 3682 expressions = ( 3683 self.wrap(expressions) if expression.args.get("wrapped") else f" {expressions}" 3684 ) 3685 return f"{this}{expressions}" if expressions.strip() != "" else this
3695 def when_sql(self, expression: exp.When) -> str: 3696 matched = "MATCHED" if expression.args["matched"] else "NOT MATCHED" 3697 source = " BY SOURCE" if self.MATCHED_BY_SOURCE and expression.args.get("source") else "" 3698 condition = self.sql(expression, "condition") 3699 condition = f" AND {condition}" if condition else "" 3700 3701 then_expression = expression.args.get("then") 3702 if isinstance(then_expression, exp.Insert): 3703 this = self.sql(then_expression, "this") 3704 this = f"INSERT {this}" if this else "INSERT" 3705 then = self.sql(then_expression, "expression") 3706 then = f"{this} VALUES {then}" if then else this 3707 elif isinstance(then_expression, exp.Update): 3708 if isinstance(then_expression.args.get("expressions"), exp.Star): 3709 then = f"UPDATE {self.sql(then_expression, 'expressions')}" 3710 else: 3711 then = f"UPDATE SET {self.expressions(then_expression, flat=True)}" 3712 else: 3713 then = self.sql(then_expression) 3714 return f"WHEN {matched}{source}{condition} THEN {then}"
3719 def merge_sql(self, expression: exp.Merge) -> str: 3720 table = expression.this 3721 table_alias = "" 3722 3723 hints = table.args.get("hints") 3724 if hints and table.alias and isinstance(hints[0], exp.WithTableHint): 3725 # T-SQL syntax is MERGE ... <target_table> [WITH (<merge_hint>)] [[AS] table_alias] 3726 table_alias = f" AS {self.sql(table.args['alias'].pop())}" 3727 3728 this = self.sql(table) 3729 using = f"USING {self.sql(expression, 'using')}" 3730 on = f"ON {self.sql(expression, 'on')}" 3731 whens = self.sql(expression, "whens") 3732 3733 returning = self.sql(expression, "returning") 3734 if returning: 3735 whens = f"{whens}{returning}" 3736 3737 sep = self.sep() 3738 3739 return self.prepend_ctes( 3740 expression, 3741 f"MERGE INTO {this}{table_alias}{sep}{using}{sep}{on}{sep}{whens}", 3742 )
3748 def tonumber_sql(self, expression: exp.ToNumber) -> str: 3749 if not self.SUPPORTS_TO_NUMBER: 3750 self.unsupported("Unsupported TO_NUMBER function") 3751 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3752 3753 fmt = expression.args.get("format") 3754 if not fmt: 3755 self.unsupported("Conversion format is required for TO_NUMBER") 3756 return self.sql(exp.cast(expression.this, exp.DataType.Type.DOUBLE)) 3757 3758 return self.func("TO_NUMBER", expression.this, fmt)
3760 def dictproperty_sql(self, expression: exp.DictProperty) -> str: 3761 this = self.sql(expression, "this") 3762 kind = self.sql(expression, "kind") 3763 settings_sql = self.expressions(expression, key="settings", sep=" ") 3764 args = f"({self.sep('')}{settings_sql}{self.seg(')', sep='')}" if settings_sql else "()" 3765 return f"{this}({kind}{args})"
3784 def distributedbyproperty_sql(self, expression: exp.DistributedByProperty) -> str: 3785 expressions = self.expressions(expression, flat=True) 3786 expressions = f" {self.wrap(expressions)}" if expressions else "" 3787 buckets = self.sql(expression, "buckets") 3788 kind = self.sql(expression, "kind") 3789 buckets = f" BUCKETS {buckets}" if buckets else "" 3790 order = self.sql(expression, "order") 3791 return f"DISTRIBUTED BY {kind}{expressions}{buckets}{order}"
3796 def clusteredbyproperty_sql(self, expression: exp.ClusteredByProperty) -> str: 3797 expressions = self.expressions(expression, key="expressions", flat=True) 3798 sorted_by = self.expressions(expression, key="sorted_by", flat=True) 3799 sorted_by = f" SORTED BY ({sorted_by})" if sorted_by else "" 3800 buckets = self.sql(expression, "buckets") 3801 return f"CLUSTERED BY ({expressions}){sorted_by} INTO {buckets} BUCKETS"
3803 def anyvalue_sql(self, expression: exp.AnyValue) -> str: 3804 this = self.sql(expression, "this") 3805 having = self.sql(expression, "having") 3806 3807 if having: 3808 this = f"{this} HAVING {'MAX' if expression.args.get('max') else 'MIN'} {having}" 3809 3810 return self.func("ANY_VALUE", this)
3812 def querytransform_sql(self, expression: exp.QueryTransform) -> str: 3813 transform = self.func("TRANSFORM", *expression.expressions) 3814 row_format_before = self.sql(expression, "row_format_before") 3815 row_format_before = f" {row_format_before}" if row_format_before else "" 3816 record_writer = self.sql(expression, "record_writer") 3817 record_writer = f" RECORDWRITER {record_writer}" if record_writer else "" 3818 using = f" USING {self.sql(expression, 'command_script')}" 3819 schema = self.sql(expression, "schema") 3820 schema = f" AS {schema}" if schema else "" 3821 row_format_after = self.sql(expression, "row_format_after") 3822 row_format_after = f" {row_format_after}" if row_format_after else "" 3823 record_reader = self.sql(expression, "record_reader") 3824 record_reader = f" RECORDREADER {record_reader}" if record_reader else "" 3825 return f"{transform}{row_format_before}{record_writer}{using}{schema}{row_format_after}{record_reader}"
3827 def indexconstraintoption_sql(self, expression: exp.IndexConstraintOption) -> str: 3828 key_block_size = self.sql(expression, "key_block_size") 3829 if key_block_size: 3830 return f"KEY_BLOCK_SIZE = {key_block_size}" 3831 3832 using = self.sql(expression, "using") 3833 if using: 3834 return f"USING {using}" 3835 3836 parser = self.sql(expression, "parser") 3837 if parser: 3838 return f"WITH PARSER {parser}" 3839 3840 comment = self.sql(expression, "comment") 3841 if comment: 3842 return f"COMMENT {comment}" 3843 3844 visible = expression.args.get("visible") 3845 if visible is not None: 3846 return "VISIBLE" if visible else "INVISIBLE" 3847 3848 engine_attr = self.sql(expression, "engine_attr") 3849 if engine_attr: 3850 return f"ENGINE_ATTRIBUTE = {engine_attr}" 3851 3852 secondary_engine_attr = self.sql(expression, "secondary_engine_attr") 3853 if secondary_engine_attr: 3854 return f"SECONDARY_ENGINE_ATTRIBUTE = {secondary_engine_attr}" 3855 3856 self.unsupported("Unsupported index constraint option.") 3857 return ""
3863 def indexcolumnconstraint_sql(self, expression: exp.IndexColumnConstraint) -> str: 3864 kind = self.sql(expression, "kind") 3865 kind = f"{kind} INDEX" if kind else "INDEX" 3866 this = self.sql(expression, "this") 3867 this = f" {this}" if this else "" 3868 index_type = self.sql(expression, "index_type") 3869 index_type = f" USING {index_type}" if index_type else "" 3870 expressions = self.expressions(expression, flat=True) 3871 expressions = f" ({expressions})" if expressions else "" 3872 options = self.expressions(expression, key="options", sep=" ") 3873 options = f" {options}" if options else "" 3874 return f"{kind}{this}{index_type}{expressions}{options}"
3876 def nvl2_sql(self, expression: exp.Nvl2) -> str: 3877 if self.NVL2_SUPPORTED: 3878 return self.function_fallback_sql(expression) 3879 3880 case = exp.Case().when( 3881 expression.this.is_(exp.null()).not_(copy=False), 3882 expression.args["true"], 3883 copy=False, 3884 ) 3885 else_cond = expression.args.get("false") 3886 if else_cond: 3887 case.else_(else_cond, copy=False) 3888 3889 return self.sql(case)
3891 def comprehension_sql(self, expression: exp.Comprehension) -> str: 3892 this = self.sql(expression, "this") 3893 expr = self.sql(expression, "expression") 3894 iterator = self.sql(expression, "iterator") 3895 condition = self.sql(expression, "condition") 3896 condition = f" IF {condition}" if condition else "" 3897 return f"{this} FOR {expr} IN {iterator}{condition}"
3905 def predict_sql(self, expression: exp.Predict) -> str: 3906 model = self.sql(expression, "this") 3907 model = f"MODEL {model}" 3908 table = self.sql(expression, "expression") 3909 table = f"TABLE {table}" if not isinstance(expression.expression, exp.Subquery) else table 3910 parameters = self.sql(expression, "params_struct") 3911 return self.func("PREDICT", model, table, parameters or None)
3923 def toarray_sql(self, expression: exp.ToArray) -> str: 3924 arg = expression.this 3925 if not arg.type: 3926 from sqlglot.optimizer.annotate_types import annotate_types 3927 3928 arg = annotate_types(arg) 3929 3930 if arg.is_type(exp.DataType.Type.ARRAY): 3931 return self.sql(arg) 3932 3933 cond_for_null = arg.is_(exp.null()) 3934 return self.sql(exp.func("IF", cond_for_null, exp.null(), exp.array(arg, copy=False)))
3943 def tsordstotimestamp_sql(self, expression: exp.TsOrDsToTimestamp) -> str: 3944 this = expression.this 3945 if isinstance(this, exp.TsOrDsToTimestamp) or this.is_type(exp.DataType.Type.TIMESTAMP): 3946 return self.sql(this) 3947 3948 return self.sql(exp.cast(this, exp.DataType.Type.TIMESTAMP, dialect=self.dialect))
3950 def tsordstodatetime_sql(self, expression: exp.TsOrDsToDatetime) -> str: 3951 this = expression.this 3952 if isinstance(this, exp.TsOrDsToDatetime) or this.is_type(exp.DataType.Type.DATETIME): 3953 return self.sql(this) 3954 3955 return self.sql(exp.cast(this, exp.DataType.Type.DATETIME, dialect=self.dialect))
3957 def tsordstodate_sql(self, expression: exp.TsOrDsToDate) -> str: 3958 this = expression.this 3959 time_format = self.format_time(expression) 3960 3961 if time_format and time_format not in (self.dialect.TIME_FORMAT, self.dialect.DATE_FORMAT): 3962 return self.sql( 3963 exp.cast( 3964 exp.StrToTime(this=this, format=expression.args["format"]), 3965 exp.DataType.Type.DATE, 3966 ) 3967 ) 3968 3969 if isinstance(this, exp.TsOrDsToDate) or this.is_type(exp.DataType.Type.DATE): 3970 return self.sql(this) 3971 3972 return self.sql(exp.cast(this, exp.DataType.Type.DATE))
3984 def lastday_sql(self, expression: exp.LastDay) -> str: 3985 if self.LAST_DAY_SUPPORTS_DATE_PART: 3986 return self.function_fallback_sql(expression) 3987 3988 unit = expression.text("unit") 3989 if unit and unit != "MONTH": 3990 self.unsupported("Date parts are not supported in LAST_DAY.") 3991 3992 return self.func("LAST_DAY", expression.this)
4001 def arrayany_sql(self, expression: exp.ArrayAny) -> str: 4002 if self.CAN_IMPLEMENT_ARRAY_ANY: 4003 filtered = exp.ArrayFilter(this=expression.this, expression=expression.expression) 4004 filtered_not_empty = exp.ArraySize(this=filtered).neq(0) 4005 original_is_empty = exp.ArraySize(this=expression.this).eq(0) 4006 return self.sql(exp.paren(original_is_empty.or_(filtered_not_empty))) 4007 4008 from sqlglot.dialects import Dialect 4009 4010 # SQLGlot's executor supports ARRAY_ANY, so we don't wanna warn for the SQLGlot dialect 4011 if self.dialect.__class__ != Dialect: 4012 self.unsupported("ARRAY_ANY is unsupported") 4013 4014 return self.function_fallback_sql(expression)
4016 def struct_sql(self, expression: exp.Struct) -> str: 4017 expression.set( 4018 "expressions", 4019 [ 4020 exp.alias_(e.expression, e.name if e.this.is_string else e.this) 4021 if isinstance(e, exp.PropertyEQ) 4022 else e 4023 for e in expression.expressions 4024 ], 4025 ) 4026 4027 return self.function_fallback_sql(expression)
4035 def truncatetable_sql(self, expression: exp.TruncateTable) -> str: 4036 target = "DATABASE" if expression.args.get("is_database") else "TABLE" 4037 tables = f" {self.expressions(expression)}" 4038 4039 exists = " IF EXISTS" if expression.args.get("exists") else "" 4040 4041 on_cluster = self.sql(expression, "cluster") 4042 on_cluster = f" {on_cluster}" if on_cluster else "" 4043 4044 identity = self.sql(expression, "identity") 4045 identity = f" {identity} IDENTITY" if identity else "" 4046 4047 option = self.sql(expression, "option") 4048 option = f" {option}" if option else "" 4049 4050 partition = self.sql(expression, "partition") 4051 partition = f" {partition}" if partition else "" 4052 4053 return f"TRUNCATE {target}{exists}{tables}{on_cluster}{identity}{option}{partition}"
4057 def convert_sql(self, expression: exp.Convert) -> str: 4058 to = expression.this 4059 value = expression.expression 4060 style = expression.args.get("style") 4061 safe = expression.args.get("safe") 4062 strict = expression.args.get("strict") 4063 4064 if not to or not value: 4065 return "" 4066 4067 # Retrieve length of datatype and override to default if not specified 4068 if not seq_get(to.expressions, 0) and to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4069 to = exp.DataType.build(to.this, expressions=[exp.Literal.number(30)], nested=False) 4070 4071 transformed: t.Optional[exp.Expression] = None 4072 cast = exp.Cast if strict else exp.TryCast 4073 4074 # Check whether a conversion with format (T-SQL calls this 'style') is applicable 4075 if isinstance(style, exp.Literal) and style.is_int: 4076 from sqlglot.dialects.tsql import TSQL 4077 4078 style_value = style.name 4079 converted_style = TSQL.CONVERT_FORMAT_MAPPING.get(style_value) 4080 if not converted_style: 4081 self.unsupported(f"Unsupported T-SQL 'style' value: {style_value}") 4082 4083 fmt = exp.Literal.string(converted_style) 4084 4085 if to.this == exp.DataType.Type.DATE: 4086 transformed = exp.StrToDate(this=value, format=fmt) 4087 elif to.this in (exp.DataType.Type.DATETIME, exp.DataType.Type.DATETIME2): 4088 transformed = exp.StrToTime(this=value, format=fmt) 4089 elif to.this in self.PARAMETERIZABLE_TEXT_TYPES: 4090 transformed = cast(this=exp.TimeToStr(this=value, format=fmt), to=to, safe=safe) 4091 elif to.this == exp.DataType.Type.TEXT: 4092 transformed = exp.TimeToStr(this=value, format=fmt) 4093 4094 if not transformed: 4095 transformed = cast(this=value, to=to, safe=safe) 4096 4097 return self.sql(transformed)
4157 def copyparameter_sql(self, expression: exp.CopyParameter) -> str: 4158 option = self.sql(expression, "this") 4159 4160 if expression.expressions: 4161 upper = option.upper() 4162 4163 # Snowflake FILE_FORMAT options are separated by whitespace 4164 sep = " " if upper == "FILE_FORMAT" else ", " 4165 4166 # Databricks copy/format options do not set their list of values with EQ 4167 op = " " if upper in ("COPY_OPTIONS", "FORMAT_OPTIONS") else " = " 4168 values = self.expressions(expression, flat=True, sep=sep) 4169 return f"{option}{op}({values})" 4170 4171 value = self.sql(expression, "expression") 4172 4173 if not value: 4174 return option 4175 4176 op = " = " if self.COPY_PARAMS_EQ_REQUIRED else " " 4177 4178 return f"{option}{op}{value}"
4180 def credentials_sql(self, expression: exp.Credentials) -> str: 4181 cred_expr = expression.args.get("credentials") 4182 if isinstance(cred_expr, exp.Literal): 4183 # Redshift case: CREDENTIALS <string> 4184 credentials = self.sql(expression, "credentials") 4185 credentials = f"CREDENTIALS {credentials}" if credentials else "" 4186 else: 4187 # Snowflake case: CREDENTIALS = (...) 4188 credentials = self.expressions(expression, key="credentials", flat=True, sep=" ") 4189 credentials = f"CREDENTIALS = ({credentials})" if cred_expr is not None else "" 4190 4191 storage = self.sql(expression, "storage") 4192 storage = f"STORAGE_INTEGRATION = {storage}" if storage else "" 4193 4194 encryption = self.expressions(expression, key="encryption", flat=True, sep=" ") 4195 encryption = f" ENCRYPTION = ({encryption})" if encryption else "" 4196 4197 iam_role = self.sql(expression, "iam_role") 4198 iam_role = f"IAM_ROLE {iam_role}" if iam_role else "" 4199 4200 region = self.sql(expression, "region") 4201 region = f" REGION {region}" if region else "" 4202 4203 return f"{credentials}{storage}{encryption}{iam_role}{region}"
4205 def copy_sql(self, expression: exp.Copy) -> str: 4206 this = self.sql(expression, "this") 4207 this = f" INTO {this}" if self.COPY_HAS_INTO_KEYWORD else f" {this}" 4208 4209 credentials = self.sql(expression, "credentials") 4210 credentials = self.seg(credentials) if credentials else "" 4211 kind = self.seg("FROM" if expression.args.get("kind") else "TO") 4212 files = self.expressions(expression, key="files", flat=True) 4213 4214 sep = ", " if self.dialect.COPY_PARAMS_ARE_CSV else " " 4215 params = self.expressions( 4216 expression, 4217 key="params", 4218 sep=sep, 4219 new_line=True, 4220 skip_last=True, 4221 skip_first=True, 4222 indent=self.COPY_PARAMS_ARE_WRAPPED, 4223 ) 4224 4225 if params: 4226 if self.COPY_PARAMS_ARE_WRAPPED: 4227 params = f" WITH ({params})" 4228 elif not self.pretty: 4229 params = f" {params}" 4230 4231 return f"COPY{this}{kind} {files}{credentials}{params}"
4236 def datadeletionproperty_sql(self, expression: exp.DataDeletionProperty) -> str: 4237 on_sql = "ON" if expression.args.get("on") else "OFF" 4238 filter_col: t.Optional[str] = self.sql(expression, "filter_column") 4239 filter_col = f"FILTER_COLUMN={filter_col}" if filter_col else None 4240 retention_period: t.Optional[str] = self.sql(expression, "retention_period") 4241 retention_period = f"RETENTION_PERIOD={retention_period}" if retention_period else None 4242 4243 if filter_col or retention_period: 4244 on_sql = self.func("ON", filter_col, retention_period) 4245 4246 return f"DATA_DELETION={on_sql}"
def
maskingpolicycolumnconstraint_sql( self, expression: sqlglot.expressions.MaskingPolicyColumnConstraint) -> str:
4248 def maskingpolicycolumnconstraint_sql( 4249 self, expression: exp.MaskingPolicyColumnConstraint 4250 ) -> str: 4251 this = self.sql(expression, "this") 4252 expressions = self.expressions(expression, flat=True) 4253 expressions = f" USING ({expressions})" if expressions else "" 4254 return f"MASKING POLICY {this}{expressions}"
4264 def scoperesolution_sql(self, expression: exp.ScopeResolution) -> str: 4265 this = self.sql(expression, "this") 4266 expr = expression.expression 4267 4268 if isinstance(expr, exp.Func): 4269 # T-SQL's CLR functions are case sensitive 4270 expr = f"{self.sql(expr, 'this')}({self.format_args(*expr.expressions)})" 4271 else: 4272 expr = self.sql(expression, "expression") 4273 4274 return self.scope_resolution(expr, this)
4282 def rand_sql(self, expression: exp.Rand) -> str: 4283 lower = self.sql(expression, "lower") 4284 upper = self.sql(expression, "upper") 4285 4286 if lower and upper: 4287 return f"({upper} - {lower}) * {self.func('RAND', expression.this)} + {lower}" 4288 return self.func("RAND", expression.this)
4290 def changes_sql(self, expression: exp.Changes) -> str: 4291 information = self.sql(expression, "information") 4292 information = f"INFORMATION => {information}" 4293 at_before = self.sql(expression, "at_before") 4294 at_before = f"{self.seg('')}{at_before}" if at_before else "" 4295 end = self.sql(expression, "end") 4296 end = f"{self.seg('')}{end}" if end else "" 4297 4298 return f"CHANGES ({information}){at_before}{end}"
4300 def pad_sql(self, expression: exp.Pad) -> str: 4301 prefix = "L" if expression.args.get("is_left") else "R" 4302 4303 fill_pattern = self.sql(expression, "fill_pattern") or None 4304 if not fill_pattern and self.PAD_FILL_PATTERN_IS_REQUIRED: 4305 fill_pattern = "' '" 4306 4307 return self.func(f"{prefix}PAD", expression.this, expression.expression, fill_pattern)
def
explodinggenerateseries_sql(self, expression: sqlglot.expressions.ExplodingGenerateSeries) -> str:
4313 def explodinggenerateseries_sql(self, expression: exp.ExplodingGenerateSeries) -> str: 4314 generate_series = exp.GenerateSeries(**expression.args) 4315 4316 parent = expression.parent 4317 if isinstance(parent, (exp.Alias, exp.TableAlias)): 4318 parent = parent.parent 4319 4320 if self.SUPPORTS_EXPLODING_PROJECTIONS and not isinstance(parent, (exp.Table, exp.Unnest)): 4321 return self.sql(exp.Unnest(expressions=[generate_series])) 4322 4323 if isinstance(parent, exp.Select): 4324 self.unsupported("GenerateSeries projection unnesting is not supported.") 4325 4326 return self.sql(generate_series)
def
arrayconcat_sql( self, expression: sqlglot.expressions.ArrayConcat, name: str = 'ARRAY_CONCAT') -> str:
4328 def arrayconcat_sql(self, expression: exp.ArrayConcat, name: str = "ARRAY_CONCAT") -> str: 4329 exprs = expression.expressions 4330 if not self.ARRAY_CONCAT_IS_VAR_LEN: 4331 rhs = reduce(lambda x, y: exp.ArrayConcat(this=x, expressions=[y]), exprs) 4332 else: 4333 rhs = self.expressions(expression) 4334 4335 return self.func(name, expression.this, rhs or None)
4337 def converttimezone_sql(self, expression: exp.ConvertTimezone) -> str: 4338 if self.SUPPORTS_CONVERT_TIMEZONE: 4339 return self.function_fallback_sql(expression) 4340 4341 source_tz = expression.args.get("source_tz") 4342 target_tz = expression.args.get("target_tz") 4343 timestamp = expression.args.get("timestamp") 4344 4345 if source_tz and timestamp: 4346 timestamp = exp.AtTimeZone( 4347 this=exp.cast(timestamp, exp.DataType.Type.TIMESTAMPNTZ), zone=source_tz 4348 ) 4349 4350 expr = exp.AtTimeZone(this=timestamp, zone=target_tz) 4351 4352 return self.sql(expr)
4354 def json_sql(self, expression: exp.JSON) -> str: 4355 this = self.sql(expression, "this") 4356 this = f" {this}" if this else "" 4357 4358 _with = expression.args.get("with") 4359 4360 if _with is None: 4361 with_sql = "" 4362 elif not _with: 4363 with_sql = " WITHOUT" 4364 else: 4365 with_sql = " WITH" 4366 4367 unique_sql = " UNIQUE KEYS" if expression.args.get("unique") else "" 4368 4369 return f"JSON{this}{with_sql}{unique_sql}"
4371 def jsonvalue_sql(self, expression: exp.JSONValue) -> str: 4372 def _generate_on_options(arg: t.Any) -> str: 4373 return arg if isinstance(arg, str) else f"DEFAULT {self.sql(arg)}" 4374 4375 path = self.sql(expression, "path") 4376 returning = self.sql(expression, "returning") 4377 returning = f" RETURNING {returning}" if returning else "" 4378 4379 on_condition = self.sql(expression, "on_condition") 4380 on_condition = f" {on_condition}" if on_condition else "" 4381 4382 return self.func("JSON_VALUE", expression.this, f"{path}{returning}{on_condition}")
4384 def conditionalinsert_sql(self, expression: exp.ConditionalInsert) -> str: 4385 else_ = "ELSE " if expression.args.get("else_") else "" 4386 condition = self.sql(expression, "expression") 4387 condition = f"WHEN {condition} THEN " if condition else else_ 4388 insert = self.sql(expression, "this")[len("INSERT") :].strip() 4389 return f"{condition}{insert}"
4397 def oncondition_sql(self, expression: exp.OnCondition) -> str: 4398 # Static options like "NULL ON ERROR" are stored as strings, in contrast to "DEFAULT <expr> ON ERROR" 4399 empty = expression.args.get("empty") 4400 empty = ( 4401 f"DEFAULT {empty} ON EMPTY" 4402 if isinstance(empty, exp.Expression) 4403 else self.sql(expression, "empty") 4404 ) 4405 4406 error = expression.args.get("error") 4407 error = ( 4408 f"DEFAULT {error} ON ERROR" 4409 if isinstance(error, exp.Expression) 4410 else self.sql(expression, "error") 4411 ) 4412 4413 if error and empty: 4414 error = ( 4415 f"{empty} {error}" 4416 if self.dialect.ON_CONDITION_EMPTY_BEFORE_ERROR 4417 else f"{error} {empty}" 4418 ) 4419 empty = "" 4420 4421 null = self.sql(expression, "null") 4422 4423 return f"{empty}{error}{null}"
4425 def jsonexists_sql(self, expression: exp.JSONExists) -> str: 4426 this = self.sql(expression, "this") 4427 path = self.sql(expression, "path") 4428 4429 passing = self.expressions(expression, "passing") 4430 passing = f" PASSING {passing}" if passing else "" 4431 4432 on_condition = self.sql(expression, "on_condition") 4433 on_condition = f" {on_condition}" if on_condition else "" 4434 4435 path = f"{path}{passing}{on_condition}" 4436 4437 return self.func("JSON_EXISTS", this, path)
4439 def arrayagg_sql(self, expression: exp.ArrayAgg) -> str: 4440 array_agg = self.function_fallback_sql(expression) 4441 4442 # Add a NULL FILTER on the column to mimic the results going from a dialect that excludes nulls 4443 # on ARRAY_AGG (e.g Spark) to one that doesn't (e.g. DuckDB) 4444 if self.dialect.ARRAY_AGG_INCLUDES_NULLS and expression.args.get("nulls_excluded"): 4445 parent = expression.parent 4446 if isinstance(parent, exp.Filter): 4447 parent_cond = parent.expression.this 4448 parent_cond.replace(parent_cond.and_(expression.this.is_(exp.null()).not_())) 4449 else: 4450 this = expression.this 4451 # Do not add the filter if the input is not a column (e.g. literal, struct etc) 4452 if this.find(exp.Column): 4453 # DISTINCT is already present in the agg function, do not propagate it to FILTER as well 4454 this_sql = ( 4455 self.expressions(this) 4456 if isinstance(this, exp.Distinct) 4457 else self.sql(expression, "this") 4458 ) 4459 4460 array_agg = f"{array_agg} FILTER(WHERE {this_sql} IS NOT NULL)" 4461 4462 return array_agg
4470 def grant_sql(self, expression: exp.Grant) -> str: 4471 privileges_sql = self.expressions(expression, key="privileges", flat=True) 4472 4473 kind = self.sql(expression, "kind") 4474 kind = f" {kind}" if kind else "" 4475 4476 securable = self.sql(expression, "securable") 4477 securable = f" {securable}" if securable else "" 4478 4479 principals = self.expressions(expression, key="principals", flat=True) 4480 4481 grant_option = " WITH GRANT OPTION" if expression.args.get("grant_option") else "" 4482 4483 return f"GRANT {privileges_sql} ON{kind}{securable} TO {principals}{grant_option}"
4507 def overlay_sql(self, expression: exp.Overlay): 4508 this = self.sql(expression, "this") 4509 expr = self.sql(expression, "expression") 4510 from_sql = self.sql(expression, "from") 4511 for_sql = self.sql(expression, "for") 4512 for_sql = f" FOR {for_sql}" if for_sql else "" 4513 4514 return f"OVERLAY({this} PLACING {expr} FROM {from_sql}{for_sql})"
@unsupported_args('format')
def
todouble_sql(self, expression: sqlglot.expressions.ToDouble) -> str:
4520 def string_sql(self, expression: exp.String) -> str: 4521 this = expression.this 4522 zone = expression.args.get("zone") 4523 4524 if zone: 4525 # This is a BigQuery specific argument for STRING(<timestamp_expr>, <time_zone>) 4526 # BigQuery stores timestamps internally as UTC, so ConvertTimezone is used with UTC 4527 # set for source_tz to transpile the time conversion before the STRING cast 4528 this = exp.ConvertTimezone( 4529 source_tz=exp.Literal.string("UTC"), target_tz=zone, timestamp=this 4530 ) 4531 4532 return self.sql(exp.cast(this, exp.DataType.Type.VARCHAR))
def
overflowtruncatebehavior_sql(self, expression: sqlglot.expressions.OverflowTruncateBehavior) -> str:
4542 def overflowtruncatebehavior_sql(self, expression: exp.OverflowTruncateBehavior) -> str: 4543 filler = self.sql(expression, "this") 4544 filler = f" {filler}" if filler else "" 4545 with_count = "WITH COUNT" if expression.args.get("with_count") else "WITHOUT COUNT" 4546 return f"TRUNCATE{filler} {with_count}"
4548 def unixseconds_sql(self, expression: exp.UnixSeconds) -> str: 4549 if self.SUPPORTS_UNIX_SECONDS: 4550 return self.function_fallback_sql(expression) 4551 4552 start_ts = exp.cast( 4553 exp.Literal.string("1970-01-01 00:00:00+00"), to=exp.DataType.Type.TIMESTAMPTZ 4554 ) 4555 4556 return self.sql( 4557 exp.TimestampDiff(this=expression.this, expression=start_ts, unit=exp.var("SECONDS")) 4558 )
4560 def arraysize_sql(self, expression: exp.ArraySize) -> str: 4561 dim = expression.expression 4562 4563 # For dialects that don't support the dimension arg, we can safely transpile it's default value (1st dimension) 4564 if dim and self.ARRAY_SIZE_DIM_REQUIRED is None: 4565 if not (dim.is_int and dim.name == "1"): 4566 self.unsupported("Cannot transpile dimension argument for ARRAY_LENGTH") 4567 dim = None 4568 4569 # If dimension is required but not specified, default initialize it 4570 if self.ARRAY_SIZE_DIM_REQUIRED and not dim: 4571 dim = exp.Literal.number(1) 4572 4573 return self.func(self.ARRAY_SIZE_NAME, expression.this, dim)
4575 def attach_sql(self, expression: exp.Attach) -> str: 4576 this = self.sql(expression, "this") 4577 exists_sql = " IF NOT EXISTS" if expression.args.get("exists") else "" 4578 expressions = self.expressions(expression) 4579 expressions = f" ({expressions})" if expressions else "" 4580 4581 return f"ATTACH{exists_sql} {this}{expressions}"
4595 def featuresattime_sql(self, expression: exp.FeaturesAtTime) -> str: 4596 this_sql = self.sql(expression, "this") 4597 if isinstance(expression.this, exp.Table): 4598 this_sql = f"TABLE {this_sql}" 4599 4600 return self.func( 4601 "FEATURES_AT_TIME", 4602 this_sql, 4603 expression.args.get("time"), 4604 expression.args.get("num_rows"), 4605 expression.args.get("ignore_feature_nulls"), 4606 )
def
watermarkcolumnconstraint_sql(self, expression: sqlglot.expressions.WatermarkColumnConstraint) -> str:
4613 def encodeproperty_sql(self, expression: exp.EncodeProperty) -> str: 4614 encode = "KEY ENCODE" if expression.args.get("key") else "ENCODE" 4615 encode = f"{encode} {self.sql(expression, 'this')}" 4616 4617 properties = expression.args.get("properties") 4618 if properties: 4619 encode = f"{encode} {self.properties(properties)}" 4620 4621 return encode
4623 def includeproperty_sql(self, expression: exp.IncludeProperty) -> str: 4624 this = self.sql(expression, "this") 4625 include = f"INCLUDE {this}" 4626 4627 column_def = self.sql(expression, "column_def") 4628 if column_def: 4629 include = f"{include} {column_def}" 4630 4631 alias = self.sql(expression, "alias") 4632 if alias: 4633 include = f"{include} AS {alias}" 4634 4635 return include
def
partitionbyrangeproperty_sql(self, expression: sqlglot.expressions.PartitionByRangeProperty) -> str:
4641 def partitionbyrangeproperty_sql(self, expression: exp.PartitionByRangeProperty) -> str: 4642 partitions = self.expressions(expression, "partition_expressions") 4643 create = self.expressions(expression, "create_expressions") 4644 return f"PARTITION BY RANGE {self.wrap(partitions)} {self.wrap(create)}"
def
partitionbyrangepropertydynamic_sql( self, expression: sqlglot.expressions.PartitionByRangePropertyDynamic) -> str:
4646 def partitionbyrangepropertydynamic_sql( 4647 self, expression: exp.PartitionByRangePropertyDynamic 4648 ) -> str: 4649 start = self.sql(expression, "start") 4650 end = self.sql(expression, "end") 4651 4652 every = expression.args["every"] 4653 if isinstance(every, exp.Interval) and every.this.is_string: 4654 every.this.replace(exp.Literal.number(every.name)) 4655 4656 return f"START {self.wrap(start)} END {self.wrap(end)} EVERY {self.wrap(self.sql(every))}"
4669 def analyzestatistics_sql(self, expression: exp.AnalyzeStatistics) -> str: 4670 kind = self.sql(expression, "kind") 4671 option = self.sql(expression, "option") 4672 option = f" {option}" if option else "" 4673 this = self.sql(expression, "this") 4674 this = f" {this}" if this else "" 4675 columns = self.expressions(expression) 4676 columns = f" {columns}" if columns else "" 4677 return f"{kind}{option} STATISTICS{this}{columns}"
4679 def analyzehistogram_sql(self, expression: exp.AnalyzeHistogram) -> str: 4680 this = self.sql(expression, "this") 4681 columns = self.expressions(expression) 4682 inner_expression = self.sql(expression, "expression") 4683 inner_expression = f" {inner_expression}" if inner_expression else "" 4684 update_options = self.sql(expression, "update_options") 4685 update_options = f" {update_options} UPDATE" if update_options else "" 4686 return f"{this} HISTOGRAM ON {columns}{inner_expression}{update_options}"
def
analyzelistchainedrows_sql(self, expression: sqlglot.expressions.AnalyzeListChainedRows) -> str:
4697 def analyzevalidate_sql(self, expression: exp.AnalyzeValidate) -> str: 4698 kind = self.sql(expression, "kind") 4699 this = self.sql(expression, "this") 4700 this = f" {this}" if this else "" 4701 inner_expression = self.sql(expression, "expression") 4702 return f"VALIDATE {kind}{this}{inner_expression}"
4704 def analyze_sql(self, expression: exp.Analyze) -> str: 4705 options = self.expressions(expression, key="options", sep=" ") 4706 options = f" {options}" if options else "" 4707 kind = self.sql(expression, "kind") 4708 kind = f" {kind}" if kind else "" 4709 this = self.sql(expression, "this") 4710 this = f" {this}" if this else "" 4711 mode = self.sql(expression, "mode") 4712 mode = f" {mode}" if mode else "" 4713 properties = self.sql(expression, "properties") 4714 properties = f" {properties}" if properties else "" 4715 partition = self.sql(expression, "partition") 4716 partition = f" {partition}" if partition else "" 4717 inner_expression = self.sql(expression, "expression") 4718 inner_expression = f" {inner_expression}" if inner_expression else "" 4719 return f"ANALYZE{options}{kind}{this}{partition}{mode}{inner_expression}{properties}"
4721 def xmltable_sql(self, expression: exp.XMLTable) -> str: 4722 this = self.sql(expression, "this") 4723 passing = self.expressions(expression, key="passing") 4724 passing = f"{self.sep()}PASSING{self.seg(passing)}" if passing else "" 4725 columns = self.expressions(expression, key="columns") 4726 columns = f"{self.sep()}COLUMNS{self.seg(columns)}" if columns else "" 4727 by_ref = f"{self.sep()}RETURNING SEQUENCE BY REF" if expression.args.get("by_ref") else "" 4728 return f"XMLTABLE({self.sep('')}{self.indent(this + passing + by_ref + columns)}{self.seg(')', sep='')}"